Created
October 25, 2022 06:29
-
-
Save zjor/0a407def4efe58411ede7b30dd7cf555 to your computer and use it in GitHub Desktop.
Arduino Nano RP2040: reads LSM6DSOX sensor and switches RGB LED color depending on the orientation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Arduino_LSM6DSOX.h> | |
#include <WiFiNINA.h> | |
#define TOLERANCE 0.25 | |
enum Side { | |
TOP, BOTTOM, RIGHT, LEFT, FRONT, BACK | |
}; | |
typedef struct { | |
unsigned char r; | |
unsigned char g; | |
unsigned char b; | |
} RGB; | |
RGB colors[] = { | |
{191, 64, 191} /* purple */, | |
{255, 0, 0} /* red */, | |
{0, 255, 0} /* green */, | |
{0, 0, 255} /* blue */, | |
{255, 87, 51} /* orange */, | |
{255, 234, 0} /* yellow */ | |
}; | |
Side side = TOP; | |
bool eq(float a, float b) { | |
return abs(a - b) <= TOLERANCE; | |
} | |
void setColor(RGB c) { | |
analogWrite(LEDR, 255 - c.r); | |
analogWrite(LEDG, 255 - c.g); | |
analogWrite(LEDB, 255 - c.b); | |
} | |
void sendNotification(int side) { | |
} | |
void setSide(Side newSide) { | |
static unsigned long lastChange = millis(); | |
static bool isDirty = false; | |
if (side != newSide) { | |
Serial.print("Side: "); Serial.println(newSide); | |
isDirty = true; | |
lastChange = millis(); | |
} | |
side = newSide; | |
setColor(colors[side]); | |
unsigned long now = millis(); | |
if (isDirty && (now - lastChange) >= 1500) { | |
isDirty = false; | |
Serial.println("Sending notification..."); | |
sendNotification(side); | |
} | |
} | |
void setup() { | |
Serial.begin(115200); | |
while (!Serial); | |
pinMode(LEDR, OUTPUT); | |
pinMode(LEDG, OUTPUT); | |
pinMode(LEDB, OUTPUT); | |
if (!IMU.begin()) { | |
Serial.println("Failed to initialize IMU!"); | |
while (1); | |
} | |
Serial.print("Accelerometer sample rate = "); | |
Serial.print(IMU.accelerationSampleRate()); | |
Serial.println(" Hz"); | |
Serial.println(); | |
Serial.println("Acceleration in g's"); | |
Serial.println("X\tY\tZ"); | |
setSide(TOP); | |
} | |
void loop() { | |
float x, y, z; | |
if (IMU.accelerationAvailable()) { | |
IMU.readAcceleration(x, y, z); | |
if (eq(x, 0) && eq(y, 0) && eq(z, 1)) { | |
setSide(TOP); | |
} else if (eq(x, 0) && eq(y, -1) && eq(z, 0)) { | |
setSide(RIGHT); | |
} else if(eq(x, 0) && eq(y, 1) && eq(z, 0)) { | |
setSide(LEFT); | |
} else if(eq(x, 1) && eq(y, 0) && eq(z, 0)) { | |
setSide(FRONT); | |
} else if(eq(x, -1) && eq(y, 0) && eq(z, 0)) { | |
setSide(BACK); | |
} else if(eq(x, 0) && eq(y, 0) && eq(z, -1)) { | |
setSide(BOTTOM); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment