State Change Detection

Hello,

This may be quite a simple question, but one that I myself cannot work out. I wish to use an LDR as a beam break detector and alarm, and to do this I need to compare one value against another. The code I have so far for this is as follows:

int lightPin = 0;
int variable = 0;
int secondVariable = 0;
int differenceVariable = 0;
int ledPin = 13;
void setup() {
  Serial.begin(9600);
}

void loop() {
  variable = analogRead(lightPin);
  Serial.println(variable);
  delay(500);
  secondVariable = analogRead(lightPin);
  secondVariable-variable = differenceVariable;
  if (differenceVariable > 50) {
    digitalWrite(ledPin, HIGH)
  }
}

however, secondVariable-variable is not the correct syntax for a variable calculation like this. How should it be written?

Thanks, 4r1

I have worked it out, but will leave this post here for others to see my obvious mistake! 4r1

int lightPin = 0;
int variable = 0;
int secondVariable = 0;
int differenceVariable = 0;
int ledPin = 13;
void setup() {
  Serial.begin(9600);
}

void loop() {
  variable = analogRead(lightPin);
  Serial.println(variable);
  delay(500);
  secondVariable = analogRead(lightPin);
  differenceVariable = variable - secondVariable;
  if (differenceVariable > 50) {
    digitalWrite(ledPin, HIGH);
  }
}

Or maybe squaring the difference variable would be better, for want of a way to find absolute values. (is there a sqrt function or similar for arduino?)

int lightPin = 0;
int variable = 0;
int secondVariable = 0;
int differenceVariable = 0;
int ledPin = 13;
void setup() {
  Serial.begin(9600);
}

void loop() {
  variable = analogRead(lightPin);
  Serial.println(variable);
  delay(500);
  secondVariable = analogRead(lightPin);
  differenceVariable = variable - secondVariable;
  if ((differenceVariable^2) > 50) {
    digitalWrite(ledPin, HIGH);
  }
}
  if ((differenceVariable^2) > 50) {

For the record ^2 doesn't raise differenceVariable to the power of 2. ^ is a bitwise XOR. If you want to square a value, you need to use pow(): http://arduino.cc/en/Reference/Pow

(is there a sqrt function or similar for arduino?)

If you look at the Reference page (http://www.arduino.cc/en/Reference/HomePage), you will see a section on Math. One of the operators is sqrt().

The ^ operator is the exclusive or operator in C