Go Down

Topic: Button State (Read 663 times) previous topic - next topic


Hi, currently I am working on coding which requires a remote switching a light on. I have worked it all into the code by the use of a relay switch on the remote. When a push button in 'HIGH' a signal is sent to turn the light on and when i released the button (low) the sign is send to turn the light off.

I want the light to stay on for as long as I'm holding down the button but i don't want the remote to constantly be sending a signal. What do I need to add to the code so when i push and hold the button down the signal is send for 3 seconds then stops sending it to the light as its already on?



One way to do this is to record when then button is first pressed by saving the value returned from the millis() function. Each time through loop() check if the difference between current value of millis() and your saved value is bigger than 3000 (3 seconds). Once you have reached that you can then decide what to do.
Arduino Libraries http://arduinocode.codeplex.com
Parola for Arduino http://parola.codeplex.com


would that allow the signal to be switched off automatically after the 3 seconds?


Apr 23, 2012, 01:59 am Last Edit: Apr 23, 2012, 02:00 am by marco_c Reason: 1
Depends on what you mean by automatically. Remember you are writing the software that makes things happen so if you don't tell the controller to do (or not do) something, it won't happen. To the outside it looks automatic, but in your code you need to spell it out.

Without writing the code, the flow should look something like this:

button_current_state = digitalRead();
If (button_previous_state = OFF) and (button_current_state = ON)
 last_press_time = millis()

if (button_current_state = ON) and (millis()-last_press_time <= 3000)
 send your signal
 turn your signal off, stop sending, or whatever

button_previous_state = button current state  // this remembers the current state of the button for the detect transition test

You see that the code will set the time when the button changes state (not pressed to pressed), so you need to remember the last state of the button in a global variable (one outside of the loop() function). When you detect the change of state, remember the time, and the rest is 'automatic' :-).

Hope this helps.
Arduino Libraries http://arduinocode.codeplex.com
Parola for Arduino http://parola.codeplex.com


Got it to work  :) , thanks for your help!

Go Up