Skip to content

Accelerometer

The onboard accelerometer is a LSM303AGR from ST.

Library

Download the Sodaq_LSM303AGR library from the Arduino Library Manager or from our GitHub.

Code

/* Example for using the accelerometer with the Sodaq_LSM303AGR library */
/* The example is tested on an Arduino M0 and a Sodaq Explorer with a Sodaq NB-IoT shield */
/* This code prints accelerometer readings every second and registers whether the board is flipped by interrupt */
#include <Arduino.h>
#include <Sodaq_LSM303AGR.h>

Sodaq_LSM303AGR AccMeter;

// Print the debug information on the SerialUSB 
#define DEBUG_STREAM SerialUSB

// The interrupt pin for the Accelerometer is attached to D19
#define ACC_INT_PIN ACCEL_INT1

// Threshold for interrupt trigger
double threshold = -0.8;
int now = millis();

void setup() {
    DEBUG_STREAM.begin(115200);
    while ((!DEBUG_STREAM) && (millis() < 10000)) {
        // Wait 10 seconds for the Serial Monitor
    }

    // Start the I2C bus
    Wire.begin();

    AccMeter.rebootAccelerometer();
    delay(1000);

    // Enable the Accelerometer
    AccMeter.enableAccelerometer();

    // Attach interrupt event fot the Accelerometer
    pinMode(ACC_INT_PIN, INPUT);
    attachInterrupt(ACC_INT_PIN, interrupt_event, RISING);

    // Enable interrupts on the SAMD
    GCLK->CLKCTRL.reg = GCLK_CLKCTRL_ID(GCM_EIC) |
        GCLK_CLKCTRL_GEN_GCLK1 |
        GCLK_CLKCTRL_CLKEN;

    // If Z goes below threshold the interrupt is triggered
    AccMeter.enableInterrupt1(AccMeter.ZLow, threshold, 0, AccMeter.PositionRecognition);
}

void loop() {

    // Print sensor readings every second
    if ((now + 1000) < millis())
    {
        now = millis();
        read_AccMeter();
    }
}

void read_AccMeter()
{
    DEBUG_STREAM.print("x = ");
    DEBUG_STREAM.print(AccMeter.getX());

    DEBUG_STREAM.print("\ty = ");
    DEBUG_STREAM.print(AccMeter.getY());

    DEBUG_STREAM.print("\tz = ");
    DEBUG_STREAM.println(AccMeter.getZ());
}

void interrupt_event()
{
    // Do not print in an interrupt event when sleep is enabled.
    DEBUG_STREAM.println("Board flipped");
}