Increment error help

I'm writing a code that is supposed to count how many times a button has been pressed and track it. when I run the code the output produces a large number or a large negative number instead of 1 or 2. what am i doing wrong? code :

unsigned char pb1in = 9;             // for incoming serial data
unsigned char pb1value = 0;
int count = 0;
int count2 = 0;
void setup() {
  Serial.begin(9600);             // opens serial port, sets data rate to 9600 bps
  Serial.print("Start \n");       // let the user know the program is running
  pinMode(pb1in,INPUT);
}

void loop() {
  pb1value = digitalRead(pb1in);   //check status of pb1
  while(pb1value == 1)             //wait until pb1 is pushed, the while argument becomes false when the button is pushed and pb1value is zero
  {
    pb1value = digitalRead(pb1in); //update pb1 status
    count = count - 48;
    count2 = count ++; 
  }
  delay(10);
  Serial.print("PB1 has been pushed \n");
  Serial.print("The button has been pushed "); // printing amount of button pushes
  Serial.print(count2);
  Serial.print(" times \n");

  while(pb1value == 0)             //wait until pb1 is released, the while argument becomes false when the button is not pushed and pb1value is one
  {
    pb1value = digitalRead(pb1in); //update pb1 status
  }
  Serial.print("PB1 has been released \n");
  Serial.print(" \n");
  delay(10);
}

You probably should count when the button BECOMES pressed, rather than count during the entire time it IS pressed.

See the Arduino State Machine Example.

Suggest you avoid using while( ) in your sketches.

If not used wisely, while( ) can block code execution which is almost always not what you need to do.

As per the notes this while loop stays doing the things in the while loop till the button IS pressed.

Now looking at those things. One of them is count2 = count ++;. Making the count2 change, rapidly, during the time the button is not pressed. The source for large numbers and even -numbers from overflows.

Why???

Because there is no debounce in your code and mechanical pushbuttons are very noisy. Loop is normally executed many thousands of times a second unless you have blocking code, like while or delay. If your switch is noisy, you will never get an accurate count without debouncing the button.

Which Arduino? Do you have a 10K pulldown resistor between pin 9 and GND?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.