Skip to content

Instantly share code, notes, and snippets.

@yuasatakayuki
Last active June 4, 2017 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuasatakayuki/a7a1aaea67ae0aa5049a7cb5ecde9f8e to your computer and use it in GitHub Desktop.
Save yuasatakayuki/a7a1aaea67ae0aa5049a7cb5ecde9f8e to your computer and use it in GitHub Desktop.
NUCLEO-L432KC accelerometer example
#include "mbed.h"
#include "LIS3DH.h"
#include <math.h>
#define USE_LED
#define USE_SERIAL
#ifdef USE_SERIAL
Serial pc(SERIAL_TX, SERIAL_RX);
#endif
#ifdef USE_LED
DigitalOut myled(LED1);
#endif
DigitalOut buzzer(PB_4);
const uint8_t CHIP_ADDRESS = 0x30; // Pulled-down by Jumper C
// LIS3DH accelerometer(I2C_SDA, I2C_SCL, SA0);
LIS3DH accelerometer(PB_7, PB_6, CHIP_ADDRESS);
const char* AXIS_LABEL[] = { "X", "Y", "Z" };
const float GRAVITY_VECTOR[] = {0, 0, 1};
const float RAD_TO_DEG = 360.0/(2*3.1415926535);
const float OFF_ANGLE_THRESHOLD_DEG = 80;
const uint8_t WAIT_DURATION_SEC = 1;
float magnitude(const float* vec)
{
return sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]);
}
float inner_product(const float* vec_a, const float* vec_b)
{
return vec_a[0]*vec_b[0] + vec_a[1]*vec_b[1] + vec_a[2]*vec_b[2];
}
float off_angle_deg(const float* vec_a, const float* vec_b)
{
float cos_theta = inner_product(vec_a, vec_b) / (magnitude(vec_a) * magnitude(vec_b));
float theta_rad = acos(cos_theta);
return theta_rad * RAD_TO_DEG;
}
void pulse_buzzer()
{
for(size_t i=0; i<10; i++) {
buzzer = 1;
wait(0.05);
buzzer = 0;
wait(0.05);
}
}
void set_buzzer(float off_angle)
{
if ( off_angle > OFF_ANGLE_THRESHOLD_DEG) {
pulse_buzzer();
} else {
buzzer = 0;
}
}
int main()
{
pulse_buzzer();
float acc[3];
uint32_t id = 0;
uint32_t ready = 0;
float off_angle = 0;
id = accelerometer.read_id();
#ifdef USE_SERIAL
pc.printf("LIS3DH ID = 0x%02x\n", id);
#endif
while(true) {
wait(WAIT_DURATION_SEC);
ready = accelerometer.data_ready();
accelerometer.read_data(acc);
off_angle = off_angle_deg(acc, GRAVITY_VECTOR);
set_buzzer(off_angle);
#ifdef USE_SERIAL
pc.printf("LIS3DH Ready = %d\n", ready);
for(size_t i=0; i < 3; i++) {
pc.printf("%s = %.4f\n", AXIS_LABEL[i], acc[i]);
}
pc.printf("Off angle %.1f deg\n", off_angle);
#endif
#ifdef USE_LED
myled = !myled;
#endif
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment