1

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

1 回答 1

6

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;
}
于 2013-07-07T22:15:33.233 回答