Skip to content

Instantly share code, notes, and snippets.

@cofob
Last active March 29, 2024 09:27
Show Gist options
  • Save cofob/88f507d9f8d93284dd2bd18f5aaed76a to your computer and use it in GitHub Desktop.
Save cofob/88f507d9f8d93284dd2bd18f5aaed76a to your computer and use it in GitHub Desktop.
Accelerometer + button
#include <Wire.h> // Wire library - used for I2C communication
int ADXL345 = 0x53; // The ADXL345 sensor I2C address
float X_out, Y_out, Z_out; // Outputs
const int BUTTON_READ_PIN = 5;
const int BUTTON_POWER_PIN = 6;
void setup() {
Serial.begin(9600); // Initiate serial communication for printing the results on the Serial monitor
Wire.begin(); // Initiate the Wire library
// Set ADXL345 in measuring mode
Wire.beginTransmission(ADXL345); // Start communicating with the device
Wire.write(0x2D); // Access/ talk to POWER_CTL Register - 0x2D
// Enable measurement
Wire.write(8); // (8dec -> 0000 1000 binary) Bit D3 High for measuring enable
Wire.endTransmission();
pinMode(BUTTON_READ_PIN, INPUT_PULLUP);
pinMode(BUTTON_POWER_PIN, OUTPUT);
digitalWrite(BUTTON_POWER_PIN, HIGH);
delay(10);
}
void loop() {
// === Read acceleromter data === //
Wire.beginTransmission(ADXL345);
Wire.write(0x32); // Start with register 0x32 (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(ADXL345, 6, true); // Read 6 registers total, each axis value is stored in 2 registers
X_out = ( Wire.read()| Wire.read() << 8); // X-axis value
X_out = X_out/256; //For a range of +-2g, we need to divide the raw values by 256, according to the datasheet
Y_out = ( Wire.read()| Wire.read() << 8); // Y-axis value
Y_out = Y_out/256;
Z_out = ( Wire.read()| Wire.read() << 8); // Z-axis value
Z_out = Z_out/256;
Serial.print("{\"type\":\"acc\",\"x\":");
Serial.print(X_out);
Serial.print(",\"y\":");
Serial.print(Y_out);
Serial.print(",\"z\":");
Serial.print(Z_out);
Serial.println("}");
Serial.print("{\"type\":\"btn\",\"s\":");
if (digitalRead(BUTTON_READ_PIN)) {
Serial.print("true");
} else {
Serial.print("false");
}
Serial.println("}");
Serial.println("{\"type\":\"ver\",\"c\":\"SECRETVALUE\"}");
delay(100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment