Home > Mobile >  Arduino Timer loop
Arduino Timer loop

Time:11-29

I'm Writing some code for my Arduino that displays "Timer(counts from 1-100)" then displays "Interrupts: b"( b acts as a placeholder for how many times it looped)It counts to 100 then prints out my else statement but it doesn't loop and my b value just keeps incrementing. Where am i going wrong?

    void loop() {

    int a = 0;
    int b = 0;

         if(a != 100){
    
          lcd.setCursor(0,0);
          lcd.print("Timer");
          lcd.print("");
          a  ;
          lcd.print(a); 
          delay(10);
          lcd.clear();
          
        }
        else{
    //
          b  ;
          lcd.print("Interrupt");
          
          lcd.print(b);
          delay(1000);
          lcd.clear();
          
    //      
    //   
       }
    }  

 

CodePudding user response:

You're defining a and b on the beginning of the loop(), the loop function is called every time, so your a and b are cleared every time. probably you have to define then out of the loop function.
Edit: In my example I declared the variables inside setup() function, as the guy who comment my answer said, it declares a variable only in the scope of that function, you actually need to declare it out of any function.

int a = 0;
int b = 0;
void loop() {
     if(a != 100){
      lcd.setCursor(0,0);
      lcd.print("Timer");
      lcd.print("");
      a  ;
      lcd.print(a); 
      delay(10);
      lcd.clear();
    }
    else{
      b  ;
      lcd.print("Interrupt");
      lcd.print(b);
      delay(1000);
      lcd.clear();
      a=0;
   }
}

Edit 2: Actually, your code don't do what you want. It counts 1 to 100 one time, then starts incrementing and printing b. You have to clear the a variable in your else statement to it starts counting again. I tested the code in Tinkercad and now it seems to work.
Code used in Tinkercad:

void setup()
{
  Serial.begin(9600);
}
int a = 0;
int b = 0;
void loop() {

     if(a != 100){
      a  ;
       Serial.println(a);
       delay(10);
    }
    else{
      b  ;
      Serial.println(b);
      delay(1000);
      a = 0;
   }
}  
  • Related