hi, i,m new here and this is my first project. i just managed to blinking three leds separately and used potentiometer to control their blinking speed. now i want to add enable/disable this blink function by pressing push button (button2) once. i,m totally new to this. what is the next code will be added to this project that i could enable/disable blink function by pressing once push button ? help will be appreciated and thanks in advance. (my english is weak hope you understand me)
and here is my first project code.
// Assign output variables to GPIO pins
int potPin= A0; //Declare potPin to be analog pin A0
int button = 14;
int button2 = 12;
int RED = 2;
int GREEN = 4;
int BLUE = 5;
int pwmMin = 0; // delay time
int pwmMax = 1023;
int analogState; // variable for reading blinking speed
int mode = 0;
int blink;
void setup() {
Serial.begin(9600);
pinMode(RED, OUTPUT);
pinMode(GREEN, OUTPUT);
pinMode(BLUE, OUTPUT);
//setup buttons
pinMode(potPin, INPUT);
pinMode (button, INPUT_PULLUP);
pinMode (button2, INPUT_PULLUP);
}
void loop() {
analogState = analogRead(potPin);
blink = map(analogState, pwmMin, pwmMax, 50, 1023); //allows for pot to control bliking speed
if (digitalRead(button) == LOW) {
mode = mode + 1;
delay(300);
}
//Green
if (mode == 0) {
digitalWrite(BLUE, 255);
digitalWrite(GREEN, 255);
digitalWrite(RED, 255);
delay(blink);
digitalWrite(BLUE, 255);
digitalWrite(GREEN, 0);
digitalWrite(RED, 255);
delay(blink);
}
//Blue
if (mode == 1) {
digitalWrite(BLUE, 255);
digitalWrite(GREEN, 255);
digitalWrite(RED, 255);
delay(blink);
digitalWrite(BLUE, 0);
digitalWrite(GREEN, 255);
digitalWrite(RED, 255);
delay(blink);
}
//Red
if (mode == 2) {
digitalWrite(BLUE, 255);
digitalWrite(GREEN, 255);
digitalWrite(RED, 255);
delay(blink);
digitalWrite(BLUE, 255);
digitalWrite(GREEN, 255);
digitalWrite(RED, 0);
delay(blink);
}
//back
if (mode == 3) {
mode = 0;
}
}
You need to detect when the button becomes pressed rather than when it is pressed
See the StateChangeDetection example in the IDE
Once you can detect when the button has become pressed you can use that action to set the value of a boolean variable. Set it to true when you want the blinking to occur and false when you want it to stop. Test the value of the boolean and only execute the blinking code when it is true
Now let's acknowledge the elephant in the room. The delay() function stops all other code in your sketch from doing anything while the delay() is in progress. This can make code unresponsive because it takes time for inputs to be acted upon
The solution is to use non blocking code for timing events but it is not a simple drop in replacement for the delay() function