Accelerometer/LED program help...

Hey guys,
I wrote a code that I thought would recieve data from an accelerometer, and if that data's value was either greater than 500 or less than -500, would cause an LED to light up... Only thing is... The code is only displaying the serial data to the serial monitor, not lighting the LED when the values are correct. Here's the code, any help would be greatly appreciated...

int xPin = 2;
int yPin = 3;
int ledPin = 4;

void setup(){
  Serial.begin(9600);
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop(){
  int pulseX, pulseY;
  int accelerationX, accelerationY;
  pulseX = pulseIn(xPin, HIGH);
  pulseY = pulseIn(yPin, HIGH);
  accelerationX = ((pulseX / 10) - 500) * 8;
  accelerationY = ((pulseY / 10) - 500) * 8;
  Serial.print(accelerationX);
  Serial.print("\t");
  Serial.print(accelerationY);
  Serial.println();
  delay(100);
  if (xPin >= 500){
    digitalWrite(ledPin, HIGH);
  }
  if (xPin <= -500){
    digitalWrite(ledPin, HIGH);
  }
    if (yPin >= 500){
    digitalWrite(ledPin, HIGH);
  }
  if (yPin <= -500){
    digitalWrite(ledPin, HIGH);
  }
}

This

  if (xPin >= 500){
    digitalWrite(ledPin, HIGH);

will never execute the digitalWrite, because xPin == 2. Did you mean to use accelerationX or pulseX?

Would that work?
Or is there a way to say something like...

if ((value of) xPin >= 500){
    digitalWrite(ledPin, HIGH);

I'm semi-new to C programming, all my programming skills came from Atari BASIC... :stuck_out_tongue:

Do you mean something like "accelerationX >= 500" ?

Don't really get this style:

void loop(){
  int pulseX, pulseY;
  int accelerationX, accelerationY;
  pulseX = pulseIn(xPin, HIGH);
  pulseY = pulseIn(yPin, HIGH);
  accelerationX = ((pulseX / 10) - 500) * 8;
  accelerationY = ((pulseY / 10) - 500) * 8;

Why not:

void loop(){
  int pulseX = pulseIn(xPin, HIGH);
  int pulseY = pulseIn(yPin, HIGH);
  int accelerationX = ((pulseX / 10) - 500) * 8;
  int accelerationY = ((pulseY / 10) - 500) * 8;

?

The accelerationX/Y was what was throwing it off! Should have re-read the code a little more carefully. Thanks!

The only other thing I could ask is, now that it is working, the LED is constantly on after the value reaches <> 500, -500. How would I go about turning it off until the next value reaches <>500, -500?

How about an "else"?

Where should I put that in, and should I have 4, one after each "if", or one after the "if" statements?

How about writing a pin "LOW" once in a while?

That did it! Thanks for helping me out. :slight_smile:

bool ledOn = ( accelerationX >= 500 ) || ( accelerationX <= -500 ) ||
             ( accelerationY >= 500 ) || ( accelerationY <= -500 ) ;
digitalWrite( ledPin, ledOn ? HIGH : LOW );