I think I may have what you need. Here is a simple program that toggles a output from HIGH to LOW everytime you push a momenatry button. In my example I use pin 13 as the output, because of the on board LED, but you can of course make it anything you like. Try it and see if it works for you. I got the idea from one of the examples and just made a few cahnges to it. Hope this helps. You will need a pull up resistor of around 10k. I explain it in the top.
/*
So here's a simple sketch that will allow you to use a momentary switch to toggle a output from a high state to a low state.
It DOES REQUIRE a pull up resistor of around 10k or so, But it is very simple to design and works very well.
If you want to make the LED start in the "off" mode, simply invert the "OutputStatus = HIGH to LOW" and "PreviousOutputStatus from LOW to HIGH".
This will start you output in the "LOW" mode. In my case I needed it to be HIGH.
It doesn't matter how long you hold down the button, the status will only change when you push it from on to off. If for some reason
you are experiencing a debounce issue, simply adjust the Debounce time a bit higher and this should resolve you issue
Resistor - one side to 5V, other side to input pin. In this case 12(MomentaryPushButton)
Push button switch - one side to input pin. In this case 12(MomentaryPushButton), Other side of push button tied to ground
In this case the input see's a high when off or not presssed, assuming a normal open switch(N/O), and a low when pushed
Above I stated you can start the LED in the off mode by changes to some code, you can also use a normally closed(N/C) switch
and this should work as well to start the routine off with the output "off" or "LOW"
I'm not going to leave much in the way of notes, because this is pretty simple and figure, what the hell. You can't figure this
one out you shouldn't be bangin' out code.
*/
int MomentaryPushButton = 12; //It was next to pin 13. So I used it. Silly I know
int OutputPin = 13; //I only used this pin as a example. You can use any pin of course
int OutputStatus = HIGH;
int Reading;
int PreviousOutputStatus = LOW;
long Time = 0;
long Debounce = 50;
void setup()
{
pinMode(MomentaryPushButton, INPUT);
pinMode(OutputPin, OUTPUT);
}
void loop()
{
Reading = digitalRead(MomentaryPushButton);
if (Reading == HIGH && PreviousOutputStatus == LOW && millis() - Time > Debounce) {
if (OutputStatus == HIGH)
OutputStatus = LOW;
else
OutputStatus = HIGH;
Time = millis();
}
digitalWrite(OutputPin, OutputStatus);
PreviousOutputStatus = Reading;
}