Go Down

Topic: countdown (Read 703 times) previous topic - next topic

jimregister595


in this code , the counter is decremented every time i pressed the button.However, what i want is that the counter starts only decrementing the moment i press the button once and will continue not until i press again the button and stop and then display the number. Anybody who can help me find to troubleshoot the code. thanks a lot.

Code: [Select]





static byte displayDigit[10]={63,6,91,79,102,109,125,7,127,111};

const int dataPin=2;
const int clockPin=3;
const int latchPin=4;
int displayTens=25;
const int buttonPin=8;
int buttonState;
int previousbuttonState;
//int displayOnes=1;
int counter1;
int counter2;
int currentTime;
int previousTime=0;
int duration=1000;
int state=0;



 void setup()
 {
  pinMode(dataPin,OUTPUT);
  pinMode(clockPin,OUTPUT);
  pinMode(latchPin,OUTPUT);
  pinMode(buttonPin,INPUT);
  initdisplay();
  }


  void loop()
  {
    buttonState=digitalRead(buttonPin);
    if(buttonState==HIGH && buttonState!=previousbuttonState)
    {
     
     
    currentTime=millis();
    if(currentTime-previousTime>duration)
    {
     previousTime=currentTime;
     
    if(displayTens!=0)
    {
    displayTens--;
    counter1=displayTens/10;
    counter2=displayTens%10;
    score();
    }
    else if(displayTens==0)
    {
      displayTens=25;
      //digitalWrite(buzzerPin,HIGH);
      //delay(1000);
      score();
      }
   
  }
 
   
  previousbuttonState=buttonState;
 
  }


  void score()
  {
    digitalWrite(latchPin,LOW);
    shiftOut(dataPin,clockPin,MSBFIRST,displayDigit[counter2]);
    shiftOut(dataPin,clockPin,MSBFIRST,displayDigit[counter1]);
    digitalWrite(latchPin,HIGH);
    }

     void initdisplay()
  {
    digitalWrite(latchPin,LOW);
    shiftOut(dataPin,clockPin,MSBFIRST,displayDigit[4]);
    shiftOut(dataPin,clockPin,MSBFIRST,displayDigit[2]);
    digitalWrite(latchPin,HIGH);
    }


gfvalvo

1. First, all variables you use with the 'millis()' function (currentTime, previousTime, duration, etc) must be type 'unsigned long' or 'uint32_t', not 'int'.

2. So, you want the countdown to start with the 1st button push and stop with the 2nd button push? What do you want to happen on the 3rd and subsequent button pushes?

3. In general, you would use the detection of button push (which are currently doing correctly) to toggle a state variable. Call it 'counting'. When setting 'counting' to TRUE, you'd also set 'previousTime' to 'millis()'. Each time through the loop you'd check the value of 'counting'. Only if it's true, you'd then check 'previousTime' and 'currentTime' to see if it's time to decrement the count.
No technical questions via PM. They will be ignored. Post your questions in the forum so that all may learn.

Go Up