Beginner here working on coding an accelerometer to trigger an on and off led light bulb. Any advice would be greatly appreciated. attached is the coding, it turns on fine but it wont shut off after it stops moving.
int xPin = A0;
const int yPin = A1;
const int zPin = A2;
const int ledPin = 11;
const int threshold = 15;
int analogValue = -analogValue;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int x = analogRead(xPin) - 368 ;
delay(1);
int y = analogRead (yPin);
delay(1);
int z = analogRead (zPin);
delay(1);
Serial.print(x);
Serial.print("\t");
Serial.print(y);
Serial.print("\t");
Serial.print(z);
Serial.print("\n");
//int analogValue = analogRead(xPin);
if( analogRead(xPin) > threshold){
digitalWrite(ledPin,HIGH);
}
else{
digitalWrite(ledPin,LOW);
}
}
Please edit your post to add code tags, as described in the "How to use this forum" post, and add a link to the product page for the sensor.
Your program won't work for arbitrary sensor orientations.
To see why not, remove the "- 368" subtractive term from the x value, upload the revised program, and study the sensor value printouts as you hold the sensor in different orientations. Note the orientation of the X Y and Z markings on the sensor board and how they relate to the printed values.
Reconcile your observations with the fact that when the sensor is held still, it reports the acceleration due to Earth's gravity.
If you actually do have the Sparkfun SEN-12756 sensor you linked, you are using it incorrectly, and the results are meaningless. You need completely different code and wiring for the sensor you linked.