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?
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);
}
}
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?)