I am new to Arduino and have a question. I would like to seek your advice and appreciate it if you can help me to find out the problem.
The problem that I encountered is, sometimes the push button switch is not working, not very often. But I have to press twice to make the relay switching.
Replaced with a new push button switch, still the same.
This is the push button that I'm using right now.
Yes I have found that sort of button to be problematic in the past. Only last week I used one on a Pico to allow the user to power up into boot mode and it occasionally fails. You have to hold the button down and give it a bit of a wiggle with your finger to make sure you have contact.
Your code should work Ok I think. Certainly there is nothing in your code which would give randomly different results. So probably the problem is hardware.
The whole world in in consensus over this one.
It is right for three reasons
economic and environmental- you don’t have to have an external resistor, you can use the internal one, so you save money and don’t need to manafacature an other resistor.
Safety - by not having 5V going to all the buttons you reduce the risk of accidental shorts. Yes you can get shorts on ground connections but this is less likely to cause problems.
universality- a pull up can apply to all technologies TTL and MOS based where as pull down on TTL systems require different, much lower resistor values and you shouldn’t connect inputs directly to 5V.
It won't make any difference in this case. But you should use i = 1 in preference to i += 1 for clarity, although "i" is not a good choice for the name. You are not counting anything here. You are using "i" as a flag variable, and they normally have only 2 values like true & false, yes & no, or in your case 0 & 1.
The usual way to do this is to keep the previous result of digitalRead() in a flag variable, to compare with the next result of digitalRead(). Then your flag variable has one of the 2 values HIGH & LOW.