I'm stuck in writing two overlapping loops for switching a pump relay. If the timer "delayPump" ends (LOW) the timer "runnningPump" (HIGH) should start.
i guess some math madness, to be honest this loop is already making me mad, cause it should be easy!!!!
Any clue??
#define pumpSwitch_1 8
int delayPump = 10000; //delay time
int runnningPump = 5000; // running Timer
bool pumpState = LOW;
unsigned long TimerPump = 0;
unsigned long TimerDelay = 0;
void setup() {
pinMode(pumpSwitch_1, OUTPUT);
digitalWrite(pumpSwitch_1, LOW);
TimerPump = millis();
TimerDelay = millis();
}
void loop() {
digitalWrite(pumpSwitch_1, pumpState);
if (pumpState == HIGH){
if((millis() - TimerPump) >= runnningPump){
pumpState = LOW;
TimerPump = millis() + delayPump;
}
}else {
if((millis() - TimerDelay) >= delayPump){
pumpState = HIGH;
TimerDelay = millis() + runnningPump;
}
}
}
I think this is what you need:
You just need a single Timer variable, and each time you toggle the state, set it to current time, i.e. millis().
#define pumpSwitch_1 8
int delayPump = 10000; //delay time
int runnningPump = 5000; // running Timer
bool pumpState = LOW;
unsigned long Timer = 0;
void setup() {
pinMode(pumpSwitch_1, OUTPUT);
digitalWrite(pumpSwitch_1, LOW);
Timer = millis();
}
void loop() {
digitalWrite(pumpSwitch_1, pumpState);
if (pumpState == HIGH) {
if ((millis() - Timer) >= runnningPump) {
pumpState = LOW;
Timer = millis();
}
} else {
if ((millis() - Timer) >= delayPump) {
pumpState = HIGH;
Timer = millis();
}
}
}
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 have a basic code I wrote on Arduino, however, I need to change the delay to Millis instead.
Whatever I do I can't get it to work, it's always getting stuck at a red light and won't ever turn green.
I'm posting the original delay code as code I wrote using Millis seems useless and may confuse what I'm trying to do.
const int redPin = 2;
const int yellowPin = 3;
const int greenPin = 4;
int redDuration = 10000;
int greenDuration = 5000;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
}
void loop() {
setTrafficLight(1,0,0);
delay(redDuration);
setTrafficLight(1,1,0);
delay(2000);
setTrafficLight(0,0,1);
delay(greenDuration);
setTrafficLight(0,1,0);
delay(2000);
}
void setTrafficLight(int redState, int yellowState, int greenState) {
digitalWrite(redPin, redState);
digitalWrite(yellowPin, yellowState);
digitalWrite(greenPin, greenState);
}
Save the time when it started waiting.
If the difference of current time and the start time become the time to wait, proceed to the next status.
const int redPin = 2;
const int yellowPin = 3;
const int greenPin = 4;
int redDuration = 10000;
int greenDuration = 5000;
unsigned long startTime;
int status = 0; // using enum may be better
void setup() {
pinMode(redPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(greenPin, OUTPUT);
startTime = millis();
status = 0;
}
void loop() {
unsigned long currentTime = millis();
switch (status) {
case 0: // initial state
setTrafficLight(1, 0, 0);
status = 1;
break;
case 1: // waiting instead of delay(redDuration)
if (currentTime - startTime >= redDuration) {
setTrafficLight(1, 1, 0);
startTime = currentTime;
status = 2;
}
break;
case 2: // waiting instead of first delay(2000)
if (currentTime - startTime >= 2000) {
setTrafficLight(0, 0, 1);
startTime = currentTime;
status = 3;
}
break;
case 3: // waiting instead if delay(greenDuration)
if (currentTime - startTime >= greenDuration) {
setTrafficLight(0, 1, 0);
startTime = currentTime;
status = 4;
}
break;
case 4: // waiting instead of second delay(2000)
if (currentTime - startTime >= 2000) {
startTime = currentTime;
status = 0;
}
break;
default: // for in-case safety
status = 0;
break;
}
}
void setTrafficLight(int redState, int yellowState, int greenState) {
digitalWrite(redPin, redState);
digitalWrite(yellowPin, yellowState);
digitalWrite(greenPin, greenState);
}
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 writing an Arduino program to control a minigun for a friend's cosplay. I need to write a program that when the button is pressed the motor ramps up from 0 to a given value (for now lets say "analogWrite(output_pin,200);") then loop at that RPM until the button is released, at which point it needs to ramp down back to zero.
When I try to put ramping into a loop it doesn't finish the code. I
I need something like this in c++ code for the Arduino button. (I've tried similar things using the "delay" function to no avail)
motorspeed = 0
if buttonpress == True:
buttonheld = True
for i in range (0,10):
delay(1)
motorspeed =+ 20
if buttonpress == False:
motorspeed = 0
if buttonheld == True:
motorspeed = 200
if buttonpress == False:
for i in range(0,10):
delay(1)
motorspeed =- 20
else:
#shut off motor
#Play error sound
Here is the current code that only runs the motor at one speed when the button is held down.
const int button1 =4;
int BUTTONstate1 = 0;
void setup()
{
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(9, OUTPUT);
pinMode(button1, INPUT);
}
void loop()
{
//set button to read
BUTTONstate1 = digitalRead(button1);
//if button is pressed
if (BUTTONstate1 == HIGH)
{
//run current through motor
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
//set speed
//Rampup
analogWrite(9,200);
}
else
{
digitalWrite(2, LOW);
digitalWrite(3, LOW);
}
}
Here is a virtual environment for the circuit
https://www.tinkercad.com/things/cLOBc9JJuTz-copy-of-dayloncircuitrefinecode/editel?sharecode=b6cqTLlNqUCCN09-mQ_zykp5sMnXx6KLt_KNqlXJmcs
I would recommend using interrupts, it's pretty well documented in Arduino reference:
Arduino reference - Interrupts
Most helpful is "Parameters" and "Example code" section. I think you should prepare two methods and attach interrupt to your input (button) pin on RISING and FALLING trigger.
Make sure that the button pin can be used for interrupt (on Arduino UNO / NANO only pin 2 and 3).
I think it should look similar to this (I haven't tested that):
#define buttonPin 2; // pin usable for interrupt
#define outputPin 9;
#define powerPinA 3;
#define powerPinB 4;
bool running = false;
int currentSpeed = 0;
void buttonUp()
{
digitalWrite(powerPinA, LOW);
digitalWrite(powerPinB, LOW);
running = false;
}
void buttonDown()
{
digitalWrite(powerPinA, LOW);
digitalWrite(powerPinB, HIGH);
running = true;
}
void setup()
{
pinMode(outputPin, OUTPUT);
pinMode(powerPinA, OUTPUT);
pinMode(powerPinB, OUTPUT);
pinMode(buttonPin, INPUT);
attachInterrupt(digitalPinToInterrupt(interruptPin), buttonUp, RAISING);
attachInterrupt(digitalPinToInterrupt(interruptPin), buttonDown, FALLING);
}
void loop()
{
delay(1);
if (running && currentSpeed < 200)
currentSpeed += 20;
else if (!running && currentSpeed > 0)
currentSpeed -= 20;
analogWrite(outputPin, currentSpeed);
}
Here's an example that doesn't rely on any interrupts. Just reading the button and remembering the state in a variable and remembering the time of the last step in a variable to check against millis() (Compiled but Untested)
int buttonPin = 5;
int lastButtonState = HIGH;
unsigned long lastRampStep;
unsigned int stepTime = 10; // 10ms steps. Set to whatever you want.
int analogPin = 3;
int analogLevel = 0;
int maxLevel = 200;
int analogStepSize = 10;
void setup() {
pinMode(buttonPin, INPUT_PULLUP); // will read LOW when pressed
}
void loop() {
int buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
// The button just changed!
if (buttonState == LOW) {
// was just now pressed
analogLevel = 0; // start ramp up
lastRampStep = millis(); // note the time that we took this step
} else {
// Button just released.
// not sure what you want to happen here
}
}
else if (buttonState == LOW) {
// While button is held ramp until we reach the max level
if(analogLevel < maxLevel){
if(millis() - lastRampStep >= stepTime){
analogLevel += analogStepSize;
lastRampStep = millis();
}
}
} else {
// While button is released (HIGH) ramp back down:
if(analogLevel > 0){
if(millis() - lastRampStep >= stepTime){
analogLevel -= analogStepSize;
lastRampStep = millis();
}
}
}
analogWrite(analogPin, analogLevel);
lastButtonState = buttonState;
}
You could use interrupts to handle pressed/release, set a value, and handle the ramp up/down in the loop.
Keep in mind that you should also debounce the button.
Below is some pseudocode:
const byte maxLevel = 200; // some example values (max 255)
const int rampDelay = 5;
volatile byte targetLevel = 0;
byte currentLevel = 0;
// ...
ISR for Button { // Could be in one ore two ISR's
if pressed
targetLevel = maxLevel;
// possible other calls
if released
targetLevel = 0;
// possible other calls
}
void loop()
{
if (currentLevel < targetLevel) {
SetLevel(++currentLevel);
}
else if (currentLevel > targetLevel) {
SetLevel(--currentLevel);
}
// if currentLevel == targetLevel nothing changes
// if your device is battery powered you could even put the mcu
// to sleep when both levels are zero (and wake up from the ISR)
// no need for constantly polling the button when using ISR
delay(rampDelay);
}
This will also start ramping down immediately if the button is released before the motor is at full speed.
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.