Go Down

Topic: State Change Detection (Read 449 times) previous topic - next topic

amouse197

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:

Code: [Select]
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,
Code: [Select]
secondVariable-variable is not the correct syntax for a variable calculation like this.
How should it be written?

Thanks,
4r1

amouse197

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

Code: [Select]
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);
  }
}

amouse197

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

Code: [Select]
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);
  }
}

James C4S

#3
Oct 30, 2011, 06:33 am Last Edit: Oct 30, 2011, 03:35 pm by James C4S Reason: 1
Code: [Select]
 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

Quote
(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().
Capacitor Expert By Day, Enginerd by night.  ||  Personal Blog: www.baldengineer.com  || Electronics Tutorials for Beginners:  www.addohms.com

AWOL

The ^ operator is the exclusive or operator in C
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Go Up