I'm new to programming ARDUINO's, and I'm having trouble figuring out how to get a timer working using millis().
The function I'm trying to achieve:
When pushButton is pressed led-13 turns on. (easy enough)
While pushButton is being pressed a timer starts.
After timer reaches a previously set time, and the pushButton is still pressed, a buzzer sounds.
That's it
I've looked at a few different tutorials using millis(), but none of them quite use it in the way I'm trying to. What happens is after I press and release the button it will wait the set time then the buzzer goes off, but the timer should start and the buzzer should sound while the button is STILL pressed.
int light = 13;
int pushButton = 2;
int buzzer = 12;
unsigned long timer;
I added a flag to disable the timer code when the button isn't pressed, but it still doesn't work with the button pressed either. Not sure if I did it right.
int light = 13;
int pushButton = 2;
int buzzer = 12;
unsigned long timer;
You've got another problem here. As loop repeats, as long as the button is held down you'll set timer to millis on each pass of loop. So it can't possibly be 3 seconds later as long as the button stays pressed. You need to set timer to millis once when the button first becomes pressed. Have a look at the "state change example" in the IDE for some inspiration on how to do that.
incidentally using both of your suggestions I figured it out. Although I ran yours LarryD it works as well, and it's a bit simpler than what I came up with. It seems like you got it to work using "INPUT_PULLUP"? I'm not sure how that works, but it did the trick in this case
This is what I came up with:
int light = 13;
int pushButton = 2;
int buzzer = 12;
unsigned long timer;
int lastBS = 0;
boolean flag = false;
This will only run if the timer is up && the button it still currently pressed (the way mine was set up).
Larry D, I see now what you did. Much cleaner. I used the flag to check whether the button was pressed, but you also have the flag resetting the timer once when pressed.