Hi everyone,
Experience has showed me that sometimes its easier just to ask knowledeable people a question if you hit a brick wall.
This is probably the easiest question that will ever be answered, i've only had the arduino leonardo for about 2 days so im pretty fresh with it.
In the interest of learning, i decided to try and make a program that will make an led flash once when a switch is turned HIGH. I have been messing around with the code for a while now, and have managed to make the led turn off when the switch is turned off, but when turned on, the switch will continuely flash. I want the switch to only flash once.
const int led = 13;
int switchOne = 2;
int buttonLog = 0;
void setup()
{
pinMode(led, OUTPUT);
pinMode(switchOne, INPUT);
Serial.begin(9600);
}
void loop()
{
int buttonState = digitalRead(switchOne);
if (buttonState != buttonLog);
{
if (buttonState == HIGH)
{
digitalWrite(led, HIGH);
delay(250);
digitalWrite(led, LOW);
delay(250);
buttonLog = buttonState;
}
else
{
digitalWrite(led, LOW);
delay(30);
buttonLog = buttonState;
}
}
Serial.println(digitalRead(switchOne));
}
Any help you can provide would be greatly appreciated!
Thanks
Paul
There is a difference between the circuit diagram i linked to and mine actually, replace the momentary with a toggle switch. Which i thought would still work. Once its on, it should only flash once...Either that or im picking up random noise on the switch pin...
With that extra semicolon there, the first if() statement will do nothing.
Which means the second inner if() statement will be executed every time through the loop(),
rather than just when the state has changed.
The effect of this, is that the blink operation will occur whenever the switch is "high", not just once, when it goes high for the first time.
The other thing I would change, is the very last line, where you text the button state to the PC ( presumably ).
Don't read the pin again, send the state which you already read at the top of the function.
....and if that Serial.println( ) at the end is to be of much use for debugging your switch wiring issues, it would probably be a good
idea to send it to the PC immediately after you read it, rather than after a half a second delay, which would just be confusing.
Thanks michinyon, this is very good info for me as im new to programming! I have changed the location of Serial.println() to directly after where buttonState is checked, thanks!
If theres anything other advice you have please feel free to share it!