Patrick
Patrick

Reputation: 11

C++ If Then Won't Work/Stop

I am trying to make a simple Arduino code for when a photocell reading is less than 900, it will add 1 to the CurrentNumber and display it on a 4 digit 7 segment display. The problem is that it wont stop adding one even though it's reading more than 1000.

void loop() {
 photocellReading = analogRead(photocellPin);  
 Serial.print("Analog reading = ");
 Serial.println(photocellReading);    // the raw analog reading
 photocellReading = 1023 - photocellReading;

 if(photocellReading << 10){
 CurrentNumber = CurrentNumber + 1;
 }

 displayNumber(CurrentNumber);
}

Upvotes: 1

Views: 125

Answers (1)

Borgleader
Borgleader

Reputation: 15916

Your problem is in your if condition:

 if(photocellReading << 10){
     CurrentNumber = CurrentNumber + 1;
 }

What you're essentially doing he is: shifting the bits of photocellReading to the left by 10 (which is equivalent to multiplying by 2^10 aka 1024). Most likely this means the only time this is ever going to be false is if the value of photocellReading was 0 to start with. (I say most likely because it depends on if the bits loop back around or not, but this is not entirely relevant).

tl;dr your code is conceptually equivalent to:

if((photocellReading * 1024) != 0){
    CurrentNumber = CurrentNumber + 1;
}

What I'm guessing you wanted to do (considering you subtracted 1023, which coincidentally is 1024 - 1) is:

if(photocellReading < 1024){ // again 1024 == 2^10
    CurrentNumber = CurrentNumber + 1;
}

Upvotes: 6

Related Questions