Pull down resistor nfor push button not working as expected

Hi,
I have a piece of code that is started by pressing a push button. Its connected to 5V and uses a 1k pull down resistor. The switch seems to be working erratically. As in some times the button needs to be pressed twice to start the code other times pressing it once will work. Another issue seen is that sometimes once the code starts it will stop before the predetermined amount of time. I have the code attached.The button is designed that if pressed a second time it will terminate the program during a given sequence. Any help or advice would be greatly appreciated. Not from a coding background so any help or advice would be great. I have confirmed with a DMM that my switch is producing the 5V on the output.

1-1_PW4_INT_16_65_F30.ino (2.37 KB)

Typical case of button bounce, causing multiple presses to be recorded.
After the first press has been seen, ignore subsequent presses for some time - 50 ms is usually enough - to allow the contacts to settle.

Two things:
Please post your code. The IDE has a “copy for forum” link to put these “code” markings (as generated by the “</>” icon in the posting window) on a highlighted block for you so you then just paste it here in a posting window. But even before doing that, don’t forget to use the “Auto-Format” (Ctrl-T) option first to make it easy to read. If you do not post it as “code” it can be quite garbled and is always more difficult to read. Go and read the forum instructions, point number 7.

It is inappropriate to attach it as a “.ino” file unless it is clearly too long to include in the post proper. People can usually see the mistakes directly and do not want to have to actually load it in their own IDE. And that would also assume they are using a PC and have the IDE running on that PC.

Also tidy up your blank space first. Do use blank lines, but only between complete functional blocks.


Second, it is bad engineering practice to connect buttons to power lines. Connect it to ground and use a pull-up resistor to 5 V. That way, no external leads to the button carry the supply voltage and the worst fault situation would be that the switch gets shorted out to ground and appears permanently on. If the button is designed for low current such as a “Tact” button and is not too distant from the Arduino, then use pinMode of INPUT_PULLUP which approximates a 47k pull-up.