I am using 2 accelerometers connected to an arduino. The code below does not work.
> if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <=40)) //If acc1 is between 20 and 40 AND if acc2 is between 20 and 40
> {
> digitalWrite(13, HIGH);
> }
But, the following code does:
> if((acc1 >= 20 && acc1 <= 40)) //If acc1 is between 20 and 40
> {
> digitalWrite(13, HIGH);
> }
Can anyone tell me why please? Edit with full code:
const int acc1_xPin = 0; //X Pin on acc1
const int acc1_yPin = 1; //Y Pin on acc1
const int acc2_xPin = 2; //X Pin on acc2
const int acc2_yPin = 3; //Y Pin on acc2
int xAcc1_maxVal = 409; //Maximum value for X-axis Acc1
int xAcc1_minVal = 269; //Minimum value for X-axis Acc1
int yAcc1_maxVal = 410; //Maximum value for Y-axis Acc1
int yAcc1_minVal = 270; //Minimum value for Y-axis Acc1
int xAcc2_maxVal = 411; //Maximum value for X-axis Acc2
int xAcc2_minVal = 268; //Minimum value for X-axis Acc2
int yAcc2_maxVal = 402; //Maximum value for Y-axis Acc2
int yAcc2_minVal = 263; //Minimum value for Y-axis Acc2
//Hold Calculated Values
double acc1; //acc1 angle
double acc2; //acc2 angle
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
int acc1_xRead = analogRead(acc1_xPin); //acc1 X-axis
int acc1_yRead = analogRead(acc1_yPin); //acc1 Y-axis
int acc2_xRead = analogRead(acc2_xPin); //acc2 X-axis
int acc2_yRead = analogRead(acc2_yPin); //acc2 Y-axis
//convert read values to degrees -90 to 90 - Needed for atan2
int acc1_xAng = map(acc1_xRead, xAcc1_minVal, xAcc1_maxVal, -90, 90);
int acc1_yAng = map(acc1_yRead, yAcc1_minVal, yAcc1_maxVal, -90, 90);
int acc2_xAng = map(acc2_xRead, xAcc2_minVal, xAcc2_maxVal, -90, 90);
int acc2_yAng = map(acc2_yRead, yAcc2_minVal, yAcc2_maxVal, -90, 90);
//Caculate 360deg values like so: atan2(-yAng, -zAng)
//atan2 outputs the value of -π to π (radians)
//We are then converting the radians to degrees
acc1 = RAD_TO_DEG * (atan2(-acc1_yAng, -acc1_xAng) + PI); //acc1 in degrees
acc2 = RAD_TO_DEG * (atan2(-acc2_yAng, acc2_xAng) + PI); //acc2 in degrees
if((acc1 >= 20 && acc1 <= 40) && (acc2 >= 20 && acc2 <= 40))
{
digitalWrite(13, HIGH);
Serial.println("HIGH");
}
else if ((acc1 >= 41 && acc1 <= 60) && (acc2 >= 41 && acc2 <= 60))
{
digitalWrite(13, LOW);
Serial.println("LOW");
}
Serial.print("Acc1: ");
Serial.print(acc1);
Serial.print(" Acc2: ");
Serial.print(acc2);
delay(1000);
}
I'd really appreciate any input as to way the if statements are not working when I have 2 conditions in them but will work when I have 1 condition.
Edit: I have corrected the typos in the code. My laptop gave up on me last night so I had to retype the code on a friends laptop, hence the typos and why I didn't post the whole code initially. The IF statements still don't work as stated above when the 2 conditions are in the IF statements together, but when I only put 1 condition in, it works fine.
acc2is never between 20 and 40 at the same time thatacc1is?