0

I'm trying to print a message every time a button is pressed, and so far it's working fine, but the message is printed several times (somewhere around 4000 times) and I'd like it to be printed only once.

How can I fix this? I've tried several forms of validation that worked in parts, however, when I use them, the software ends or exits in the loop.

#include <stdio.h>
#include <wiringPi.h>
int main(){
    wiringPiSetup();
    pinMode(25, OUTPUT);
    pinMode(3, INPUT);
    
    int pressed =0;
while (1){
    
    
    if(digitalRead(3)==1){
            //printf("pressed");
            pressed++;
            printf("RESULT  %d \n",pressed);
        }
}
return 0;
}
7
  • 1
    google switch debounce
    – jsotola
    Dec 22 '21 at 18:30
  • 2
    This is a how do I learn to program question.
    – joan
    Dec 22 '21 at 19:49
  • 2
    The reason it happens so many times is because you are busy looping. Don't do that. Throw a 50-100ms pause into the loop. That won't deal with the debouncing issue but it will get you a step closer.
    – goldilocks
    Dec 22 '21 at 20:11
  • 1
    "Contact Bounce" could easily be responsible for the issue you're seeing. A previous Q&A here described both hardware and software solutions. If you try one of these solutions, and it doesn't work, please edit your question to include that. This is almost definitely fix-able.
    – Seamus
    Dec 23 '21 at 1:19
  • 1
    This question is off topic, but any attempt to use wiringPi is futile as it was deprecated 2 years ago - it is not in Bullseye.
    – Milliways
    Dec 23 '21 at 6:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.