I wrote a code supposed to do the following: if I press one button while in loop void btnpress(), the program is sent to another function void blink2(), and then one led goes on and after 3 secs the led should go off, and it should also return to void btnpress() again via btnpress();.
The issue is that if i press the button and release, the led goes on and stay still infinitely on, program seems not to execute the following last parts digitalWrite(LED_BUILTIN, LOW); and btnpress();.
const int btnpin = 9;
int btnstate = 0;
unsigned long currentTime;
unsigned long previousTime;
const long period = 3000;
// the setup
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(btnpin, INPUT);
Serial.begin(9600);
}
// the loop
void loop()
{
btnpress();
}
void btnpress()
{
Serial.println("Press button");
delay(500);
btnstate = digitalRead(btnpin);
if (btnstate == HIGH) {
previousTime = millis();
blink2();
}
}
void blink2()
{
if (currentTime - previousTime >= period) {
Serial.println("Led on");
previousTime = currentTime;
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on
}
else {
Serial.println("Led off");
digitalWrite(LED_BUILTIN, LOW);
btnpress();
}
}
if I press one button while in loop void btnpress(), the program is
sent to another function void blink2(), and then one led goes on and
after 3 secs the led should go off, and it should also return to void
btnpress() again via btnpress();
According to this statement, I can suggest you to use the following code just to be sure if your functions are working according to your reqirement.
const int btnpin = 9;
int btnstate = 0;
//unsigned long currentTime;
//unsigned long previousTime;
const long period = 3000;
// the setup
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
pinMode(btnpin, INPUT);
Serial.begin(9600);
}
// the loop
void loop()
{
btnpress();
}
void btnpress()
{
Serial.println("Press button");
delay(500);
btnstate = digitalRead(btnpin);
if (btnstate == HIGH) {
// previousTime = millis();
blink2();
}
}
void blink2()
{
Serial.println("Led on");
digitalWrite(LED_BUILTIN, HIGH);
delay(3000);
Serial.println("Led off");
digitalWrite(LED_BUILTIN, LOW);
//btnpress(); It's already inside the Void loop
}
If it's working well then function call is okay.
And there has no issue with "How to call a void function within if statement (Arduino)"
The problem may be inside your if statement,
if (currentTime - previousTime >= period) {
Serial.println("Led on");
previousTime = currentTime;
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on
}
here, the currentTime is not Defined.
Related
I am working on two way communication between arduino and android phone. Currently everything is working, however I have couple of issues I have been trying to solve recently.
How I can ignite ignition for 5 seconds? I mean if IgnitionPin is on HIGH, run it for 5 seconds then automatically turn off? There is an easy way with delay, but it will not work in my case as don't want any other delays to slow up my script.
I am using Arduino Uno. I want to start my Arduino with pin in OFF position. Why pin 10 always turns ON then shuts down, even with digitalWrite(IgnitionPin, HIGH); I have tried other pins and they work fine -> turned OFF on start.
SoftwareSerial BTserial(12,13);
char choice;
const int loopDelay = 50;
int IgnitionPin = 10;
const long ignitionInterval = 5000;
int ignitionState = HIGH;
unsigned long previousMillis = 0;
void setup()
{
BTserial.begin(115200);
digitalWrite(IgnitionPin, HIGH);
pinMode(IgnitionPin, OUTPUT);
}
void loop()
{
if (BTserial.available())
{
choice = BTserial.read();
}
if( choice == 'm' )
{
ignitionState = HIGH;
digitalWrite(IgnitionPin, ignitionState);
ignitionCountTime = millis();
}
if (ignitionCountTime - previousMillis >= ignitionInterval) {
previousMillis = ignitionCountTime;
if (ignitionState == HIGH)
{
ignitionState = LOW;
}
digitalWrite(IgnitionPin, ignitionState);
}
delay(loopDelay);
}
EDIT:
SoftwareSerial BTserial(12,13);
char choice;
const int loopDelay = 50;
int IgnitionPin = 10;
unsigned long startTime;
unsigned long ignitionInterval = 30000;
unsigned long ignitionCountTime = 0;
void setup()
{
BTserial.begin(115200);
digitalWrite(IgnitionPin, HIGH);
pinMode(IgnitionPin, OUTPUT);
}
void loop()
{
if (BTserial.available())
{
choice = BTserial.read();
}
if( choice == 'm' )
{
digitalWrite(IgnitionPin, HIGH);
ignitionCountTime = millis();
}
if (ignitionCountTime - startTime >= ignitionInterval)
{
digitalWrite(IgnitionPin, LOW);
}
delay(loopDelay);
}
#1
Use the TimerOne library or setup an ISR.
Run the ISR at, 5 times per second.
uint32_t timeout = 5 * 60;
uint8_t flag = 1;
digitalWrite (myPin, HIGH);
if (timeout && flag) {
timeout--;
} else {
digitalWrite (myPin, LOW);
flag = 0;
}
OR
by checking time elapsed since some specific point in time.
unsigned long startTime;
unsigned long interval = 60000;
const byte aPin = 13;
void setup()
{
pinMode(aPin, OUTPUT);
digitalWrite(aPin, HIGH);
}
void loop()
{
if (millis() - startTime >= interval)
{
digitalWrite(aPin, LOW);
}
}
EDIT
Arduino is a microcontroller, it can do only one thing at once.
SoftwareSerial BTserial(12,13);
char choice;
const int loopDelay = 50;
int IgnitionPin = 10;
uint32_t timeout = 5 * 60;
uint8_t flag = 0;
void setup()
{
BTserial.begin(115200);
pinMode(IgnitionPin, OUTPUT);
digitalWrite(IgnitionPin, LOW);
}
void loop()
{
if (BTserial.available())
{
choice = BTserial.read();
}
if (choice == "m")
{
timeout = 5 * 60; //modify this timeout.
flag = 1;
digitalWrite(IgnitionPin, HIGH);
}
else if ((timeout > 0) && (flag == 1))
{
timeout--;
}
else
{
digitalWrite(IgnitionPin, LOW);
flag = 0;
}
delay(loopDelay);
}
#2 - In setup you are running 'digitalWrite(IgnitionPin, HIGH);' this will make it high
just use pinMode(IgnitionPin, OUTPUT); for setting pin as output pin
void setup()
{
Serial.begin(115200);
Serial.println("Enter AT commands:");
BTserial.begin(115200);
sensors.begin();
// Set Pin as an output pin
pinMode(IgnitionPin, OUTPUT);
digitalWrite(IgnitionPin, LOW);
}
If you want IgnitionPin as LOW at each restart - use 'digitalWrite(IgnitionPin, LOW);' in setup() after pinMode call.
I am trying to write a code for an Arduino, which is a model of a redlight.
The idea is that pressing the button will switch to the first state (turning LEDs on and off).
Then the second and finally the third state will revert it back to the first state waiting for the button to be pressed again
There is the need for a time gap between the 2 states....it works perfectly well using the delay() function
But I am not allowed to use it, so instead, I am trying to use millis(), the idea is that the time should start once the button is pressed and stop once it's reverts back to the first state and restart over once the button is pressed again.
And it's sadly not working, whenever I press the button nothing happens.
Does anybody know how I can fix it?
here is the code:
const long delay2 = 4000;
int but = 2;
int leda = 3;
int ledb = 4;
int ledc = 5;
int ledd = 6;
int lede = 7;
volatile byte state=LOW;
void setup() {
Serial.begin(9600);
for(int p=3; p <= 8; p++) pinMode(p, OUTPUT);
pinMode(but, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(but), changestate, FALLING);
}
void car(){
digitalWrite(leda, HIGH);
digitalWrite(ledb, LOW);
digitalWrite(ledc, LOW);
digitalWrite(ledd, LOW);
digitalWrite(lede, HIGH);
}
void wait(){
digitalWrite(leda, LOW);
digitalWrite(ledb, HIGH);
digitalWrite(ledc, LOW);
digitalWrite(ledd, LOW);
digitalWrite(lede, HIGH);
}
void ped(){
digitalWrite(leda, LOW);
digitalWrite(ledb, LOW);
digitalWrite(ledc, HIGH);
digitalWrite(ledd, HIGH);
digitalWrite(lede, LOW);
}
void changestate() {
state=state+1;
if (state > 3){
state=0;
}
}
void loop(){
switch(state){
case 0:
car();
unsigned long start_time = millis();
break;
case 1:
wait();
while (millis() > start_time + delay1);
state=2;
break;
case 2:
ped();
while (millis() > start_time + delay2);
state=0;
break;
default:
break;
}
}
EDIT: The issue has been solved! Here's the code for further reference:
#define delay1 500
#define delay2 4000
int but = 2;
int leda = 3;
int ledb = 4;
int ledc = 5;
int ledd = 6;
int lede = 7;
volatile byte state=LOW;
void setup() {
Serial.begin(9600);
for(int p=3; p <= 8; p++) pinMode(p, OUTPUT);
pinMode(but, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(but), changestate, FALLING);
}
void car(){
digitalWrite(leda, HIGH);
digitalWrite(ledb, LOW);
digitalWrite(ledc, LOW);
digitalWrite(ledd, LOW);
digitalWrite(lede, HIGH);
}
void wait(){
digitalWrite(leda, LOW);
digitalWrite(ledb, HIGH);
digitalWrite(ledc, LOW);
digitalWrite(ledd, LOW);
digitalWrite(lede, HIGH);
}
void ped(){
digitalWrite(leda, LOW);
digitalWrite(ledb, LOW);
digitalWrite(ledc, HIGH);
digitalWrite(ledd, HIGH);
digitalWrite(lede, LOW);
}
void changestate() {
state=state+1;
if (state > 3){
state=0;
}
}
unsigned long start_time = millis();
void loop(){
switch(state){
case 0:
car();
break;
case 1:
start_time = millis();
while(millis() < start_time + delay1){
wait();
state=2;
}
break;
case 2:
while(millis() < start_time + delay2){
ped();
}
state=0;
break;
default:
break;
}
}
Problematic things in code:
unsigned long start_time = millis(); start_time can't be a local variable. After break command, loop function will end. Local variable on the stack will be destroed. After new calling loop will created again and content is unpredictable. Make it global.
while (millis() > start_time + delay1); if this become true it will hangup for 49 days. You probably want do while (millis() < start_time + delay1); But this is same as use delay()
millis() < start_time + delay1; don't use this form. It produce falsely result shortly before internal counter overflow (every 49.x days). Use form (millis() - start_time > delay1 This calculate valid elapsed time also if result of millis() is lower then start_time
Also, do you have debouced button? It's seem as school exercise. I will don't write code for you. Only standart hint - Use Serial.println() to log where your code is running and what is in yours variables.
Here is an untested suggestion. It only allows state changes if a sufficient amount of time has passed. You may want to have different times in an array if (millis() - start_time > mydelays[state]) {
volatile bool change_allowed = true;
volatile bool statechanged = true;
volatile unsigned long start_time = 0;
void changestate() {
if (millis() - start_time > DELAY) {
change_allowed = true;
}
if (change_allowed) {
start_time = millis();
change_allowed = false;
state=state+1;
statechanged = true;
if (state > 2) {
state=0;
}
}
}
void loop() {
if (statechanged) {
statechanged = false;
switch(state){
case 0:
...
}
Kindly help me in the Arduino code as I am new in this field. I have Arduino code that turns the light in bulb ON and OFF using toggle switch. It is successfully running and giving output.
The following is the code:
int buttonPinBulb = 11;
int relay1 = 10;
void setup() {
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMode(relay1, OUTPUT);
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
int buttonBulb = digitalRead(buttonPinBulb);
if(buttonBulb == HIGH){
digitalWrite(relay1, HIGH);
} else {
digitalWrite(relay1, LOW);
}
Serial.println(buttonBulb);
}
Before following suggestion in the comment, the output was:
Issue
Bulb is turning ON and OFF when I toggle switch ON and OFF, and the output is showing on serial monitor continuously. But I want only one value that is not repeated. Like if I toggle the switch ON, then the value shown on serial monitor should be 1 and not 11111111....
Please help me about that. How can I do that?
After following suggestion in the comment, the code is:
int buttonPinBulb = 11;
int relay1 = 10;
int buttonBulb;
void setup() {
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMode(relay1, OUTPUT);
Serial.begin(115200);
Serial.println(buttonBulb);
}
void loop() {
// put your main code here, to run repeatedly:
buttonBulb = digitalRead(buttonPinBulb);
if(buttonBulb == HIGH){
digitalWrite(relay1, HIGH);
}else{
digitalWrite(relay1, LOW);
}
//Serial.println(buttonBulb);
}
And the output was:
You can use a global variable to store the current status of the button.
You may also want to debounce your button (using millis() in the below example, unless the debouncing is already done in hardware) - especially when you want to update a database each time the status changes.
int buttonPinBulb = 11;
int relay1 = 10;
int currentStatus = LOW;
// Debounce
unsigned long lastMillis = 0;
const unsigned long debounceTime = 100; // 100ms wait
void setup() {
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMode(relay1, OUTPUT);
Serial.begin(115200);
}
void loop() {
unsigned long currentMillis = millis();
if ( (currentMillis - lastMillis > debounceTime)
|| (currentMillis < lastMillis)) { // protect against overflow
int buttonBulb = digitalRead(buttonPinBulb);
if (buttonBulb != currentStatus) {
digitalWrite(relay1, buttonBulb);
Serial.println(buttonBulb);
currentStatus = buttonBulb;
// update database here
}
lastMillis = currentMillis;
}
}
As you have been told in comments, just store the current value of the pin and issue digitalWrite () only if a change is required.
ccesfully running and giving output. The following is the code:
int buttonPinBulb = 11;
int relay1 = 10;
int curRel1;
void setup()
{
pinMode(buttonPinBulb, INPUT_PULLUP);
pinMode(relay1, OUTPUT);
curRel1 = digitalRead(relay1);
Serial.begin(115200);
}
void loop()
{
int buttonBulb = digitalRead(buttonPinBulb);
if(buttonBulb == HIGH)
{
digitalWrite(relay1, HIGH);
}
else
{
digitalWrite(relay1, LOW);
}
if (buttonBulb != curRel1)
{
Serial.println(buttonBulb);
curRel1 = buttonBulb;
}
}
You could also update curRel1 in loop() calling digitalRead().
So i have been experimenting with TinkerCad, waiting for my arduino to arrive. Currently I have a loop of ledlights and i want to start and stop the loop by pressing a button.
Currently i am able to start my loop via the button, but not able to stop the loop with the same button press. Does this have something to do with the debouncing?
const int button = 10;
const int led1 = 8;
const int led2 = 4;
const int led3 = 3;
const int timedelay = 250;
boolean buttonstate = false;
void setup()
{
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(button, INPUT);
}
void loop() {
if(digitalRead(button)==HIGH) // check if button is pushed
buttonstate = !buttonstate; //reverse buttonstate value
if(buttonstate==true)
{
digitalWrite(led1, HIGH);
delay(timedelay);
digitalWrite(led1, LOW);
delay(timedelay);
digitalWrite(led2, HIGH);
delay(timedelay);
digitalWrite(led2, LOW);
delay(timedelay);
digitalWrite(led3, HIGH);
delay(timedelay);
digitalWrite(led2, HIGH);
delay(timedelay);
digitalWrite(led1, HIGH);
delay(timedelay);
digitalWrite(led3, LOW);
delay(timedelay);
digitalWrite(led2, LOW);
delay(timedelay);
digitalWrite(led1, LOW);
delay(timedelay);
digitalWrite(led1, HIGH); }
else {
digitalWrite(led1, HIGH);
}
}
My circuit setup:
EDIT:
I have adjusted my code, replaced the delay with millis and looking for a change in button state. Still looking for a way to adjust interval_led1 at the end of the loop to make sick ledlight sequences.
const int led1 = 13;
const int led2 = 8;
const int led3 = 5;
const int button = 10;
int ledState_led1 = LOW; // ledState used to set the LED
int ledState_led2 = LOW;
int ledState_led3 = LOW;
// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis_led1 = 0; // will store last time LED was updated
unsigned long previousMillis_led2 = 0;
unsigned long previousMillis_led3 = 0;
long interval_led1 = 500; // interval at which to blink (milliseconds)
long interval_led2 = 600;
long interval_led3 = 700;
boolean buttonstate = false;
void setup() {
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(button, INPUT);
}
void loop() {
// check to see if it's time to blink the LED; that is, if the difference
// between the current time and last time you blinked the LED is bigger than
// the interval at which you want to blink the LED.
unsigned long currentMillis_led1 = millis();
unsigned long currentMillis_led2 = millis();
unsigned long currentMillis_led3 = millis();
bool current_state = digitalRead(button);
bool prev_buttonstate= false;
if(current_state==HIGH && current_state != prev_buttonstate)
{
buttonstate = !buttonstate; //reverse buttonstate value
}
prev_buttonstate = current_state;
if(buttonstate==true)
if (currentMillis_led1 - previousMillis_led1 >= interval_led1) {
previousMillis_led1 = currentMillis_led1;
if (ledState_led1 == LOW) {
ledState_led1 = HIGH;
} else {
ledState_led1 = LOW;
}
digitalWrite(led1, ledState_led1);
}
if(buttonstate==true)
if (currentMillis_led2 - previousMillis_led2 >= interval_led2) {
previousMillis_led2 = currentMillis_led2;
if (ledState_led2 == LOW) {
ledState_led2 = HIGH;
} else {
ledState_led2 = LOW;
}
digitalWrite(led2, ledState_led2);
}
if(buttonstate==true)
if (currentMillis_led3 - previousMillis_led3 >= interval_led3) {
previousMillis_led3 = currentMillis_led3;
if (ledState_led3 == LOW) {
ledState_led3 = HIGH;
} else {
ledState_led3 = LOW;
}
digitalWrite(led3, ledState_led3);
}
}
Here your two cases are very different in terms of delay:
if(buttonstate==true) is very long to execute because of the multiple delay instructions in it,
else is very fast because there is no delay in it.
When buttonstate==True and you press the button (as Delta_G said, the delay() prevent the test to happen most of the time and you should use millis() for instance to do the timing, but let say you are lucky and you pass your first if statement), so buttonstate will flip to false.
As there is no delay in your else instruction, the board will come back in no time to your initial if, which, unfortunately will still be true as you are not fast enough to press this button for only a few microseconds. So buttonstate will flip again and your code will fall in your if(buttonstate==true) which is very long, allowing you to release the button in time before the if(digitalRead(button)==HIGH) is reevaluated.
The solution (apart from timing issues raised by #Delta_G, and hardware issues raised by #TomServo) is to seek for changes of the button state. You thus have to compare to the previous value it had. You can declare another boolean boolean prev_buttonstate = false; and could do something like:
bool current_state = digitalRead(button);
if(current_state==HIGH && current_state != prev_buttonstate)
{
buttonstate = !buttonstate; //reverse buttonstate value
}
prev_buttonstate = current_state;
Hope it helps!
Your circuit is correct. If you keep pressing the button little longer, the condition will continue to hold good and the state falsely resets again.
To simulate the toggling effect, use a bool variable like so:. You reset the variable when the signal goes low.
void loop() {
static bool ready = true;
if(digitalRead(button)==HIGH && ready)
{
ready = false;
buttonstate = !buttonstate; //reverse buttonstate value
if(buttonstate){
digitalWrite(led1, HIGH);
delay(timedelay);
digitalWrite(led1, LOW);
delay(timedelay);
/* Etc*/ }
else {
digitalWrite(led1, HIGH);
}
}
else
if(digitalRead(button)==LOW && !ready)
{
ready = true;
}
}
I'm trying to blink a LED according to press of toggle button. If I press the first toggle switch the first time, LED blinks at 5 Hz, when I press the toggle button for the second time, LED blink at 6 Hz and when I press the third time, LED turns off.
I tried using the program below, but It's not working as I wanted.
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 7; // the number of the pushbutton pin
const int ledPin = 6; // the number of the LED pin
// variables will change:
int buttonState = 0;
// variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
int x=0;
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
Serial.print(x);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if (buttonState == HIGH && x==0) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
Serial.print(x);
} else {
// turn LED off:
x = x+1;
}
if (buttonState == HIGH && x==1) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(2000);
digitalWrite(ledPin, LOW);
delay(2000);
Serial.print(x);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
x = x+1;
}
if (buttonState == HIGH && x==2) {
// turn LED on:
digitalWrite(ledPin, HIGH);
delay(3000);
digitalWrite(ledPin, LOW);
delay(3000);
Serial.print(x);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
x = x+1;
}
if (buttonState == HIGH && x==3) {
// turn LED off:
digitalWrite(ledPin, LOW);
x = 0;
}
}
When I use this code it works for first case that is LED blinks at 1000 ms delay, but if I toggle switch it again works for first condition. How can I make it to execute second condition i.e. to blink at delay of 2000 ms?
Firstly this is your circuit. I tried this circuit and code and worked for me. I used interrupt for checking button state. And millis calculation is simple.
Frequency = 1 / Period
Period = Ton + Toff
6Hz = 1000 millis / T => T = 166 millis
166 = Ton + Toff (for %50 duty cycle Ton=Toff) => Ton = Toff = 83 millis
enter image description here
const int ledPin = 13;
const int buttonPin = 2;
int state = -1;
bool willLightOn = false;
unsigned long currentDelay = 0;
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(buttonPin), changeState, FALLING);
}
void loop() {
if(state % 3 == 0) { //6Hz
currentDelay = 83;
willLightOn = true;
} else if (state % 3 == 1) { //5Hz
currentDelay = 100;
willLightOn = true;
} else if (state % 3 == 2) { //LED off
currentDelay = 0;
willLightOn = false;
digitalWrite(ledPin, LOW);
}
currentMillis = millis();
if (currentMillis - previousMillis >= currentDelay && willLightOn) {
previousMillis = currentMillis;
digitalWrite(ledPin, !digitalRead(ledPin));
}
}
void changeState() {
state++;
}
Right now your logic checks 3 times for the value of x in a single loop.
Below code toggles light whenever x is greater than zero. x's value is changed when button is pressed.
But there is a big problem here: If button is pressed when there's something else going on in the processor or it is sleeping (like the long delays you want to use), it may be ignored. So you better study interrupts and implement this behavior using them.
if (x > 0)
{
digitalWrite(ledPin, HIGH);
delay(1000 * x);
digitalWrite(ledPin, LOW);
}
if (buttonState == HIGH)
{
x++;
if (x > 3)
x = 0;
}
You should create a global state of the application. This state is where you remember if you are blinking at 50hz/60hz/off. Then you can use a switch to do the right thing.
Then you check if the button is pressed and change the application state.
See my example below:
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 7; // the number of the pushbutton pin
const int ledPin = 6; // the number of the LED pin
// variables will change:
int applicationState = 0;
bool lightOn = true;
int currentDelay = 1000;
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
// variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop() {
if (digitalRead(buttonPin) == HIGH) {
applicationState++;
if(applicationState >= 3) {
applicationState = 0;
}
delay(100);
}
switch(applicationState){
case 0:
currentDelay = 1000;
lightOn = true;
break;
case 1:
currentDelay = 2000;
lightOn = true;
break;
case 2:
digitalWrite(ledPin, LOW);
lightOn = false;
break;
}
currentMillis = millis();
if (currentMillis - previousMillis >= currentDelay && lightOn) {
previousMillis = currentMillis;
digitalWrite(ledPin, !digitalRead(ledPin));
}
}
I hope you understand what I try to say and demo with the example code.
Your code can not work:
You do need to check if the button state changes, detect when there is a edge. And make sure you detect a single edge only once.
You must repeat the blinking it in a loop till the button is pressed, then you can change the frequency.
You must check the button while you sleep, otherwise your program do not recognize when you press the button.
To make it work, you must change the complete program.
#define BLINK_SLEEP_TIME <some value> // insert value for 16.6666ms
//return 1 after a positive edge
bool button_read(void)
{
static bool lastState=1; //set this to 1, so that a pressed button at startup does not trigger a instant reaction
bool state = digitalRead(buttonPin);
if(state != lastState)
{
state=lastState;
return state;
}
return 0;
}
//Blink the LED with a given period, till button is pressed
//Times are in x*16.666ms or x/60Hz
//At least one time should be more than 0
void blink(uint8_t ontime, uint8_t offtime)
{
while(1)
{
for(uint8_t i=0;i<ontime;i++)
{
led_setOn();
delay(BLINK_SLEEP_TIME);
if(button_read())
{
return;
}
}
for(uint8_t i=0;i<offtime;i++)
{
led_setOff();
delay(BLINK_SLEEP_TIME);
if(button_read())
{
return;
}
}
}
}
const uint8_t time_table[][]=
{
{0,50},//LED is off
{6,6}, //LED blinks with 5Hz, 60Hz/2/6=5Hz
{5,5}, //LED blinks with 6Hz, 60Hz/2/5=6Hz
}
void endless(void)
{
uint8_t i=0;
for(;;)
{
i++;
if(i>2)
{
i=0;
}
blink(time_table[i][0],time_table[i][1]);
}
}
A better approach would be to use a hardware PWM-Module and change the values after a edge on the button.