Button speed

I've only just started learning things to do with Arduino, and I've started on my first project. I'm trying to control a 12v LED downlight using a TIP122 transistor and the Arduino Uno SMD to switch it.

The only problem I've run into is the time I have to hold down the button to switch it on/off. If I just quickly push the button and release it, it doesn't actually switch. I have to hold the button down for a second or so for it to switch. Is there a a way around it, or is it a limitation from the Arduino?

The script that I'm using is very basic, but I'll post it anyway. I've also tried it a few ways, but they all act the same.

int ledPin = 13; int buttonPin = 3; int ledLight = 0; int buttonState = 0;

void setup() { pinMode(ledPin, OUTPUT); pinMode(buttonPin, INPUT); }

void loop() { ledLight = digitalRead(ledPin); buttonState = digitalRead(buttonPin); if (buttonState == LOW) { if (ledLight == HIGH) { digitalWrite(ledPin, LOW); } else { digitalWrite(ledPin, HIGH); } } }

Is there a a way around it,

Yes program it correctly. Think through what you are asking this program to do. If the button state is low then it will continually keep obeying the code that changes the state of the light. So when the button is held the light turns on an off incredibly quickly and when you release it then the light stays at the same level. If you wanted to program a heads & tales program then this is how you would do it.

You need to only do the changing of the light when the button is down and last time it was up. This requires you to remember the last state of the button at the end of one loop to be used in the next.

When you've fixed the code as Mike suggests, you'll also need to debounce the button. Adding a delay(5) call in the loop may be sufficient.

Thanks a heap guys, I got it working by using the buttonState var to remember if the input was high last time, just like you suggested.

And thanks even more for leading me to the answer instead of straight out giving it to me. It was fun.