Reputation: 1
With an Arduino I'm taking analog input from a potentiometer. With the input I regulate how much my lamp blink. The problem is when I try to have a button that turn the lamp on and off so that it blinks or not blinks. I can make the button turn on the lamp but I cannot get it to turn the lamp off.
My loop that makes the lamp blink has a variable that has to be 1 for it to run. However when i change the variable to 0 with an if statement the blink loop does not stop and the lamp keeps blinking.
Here is my code:
int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
int buttonPin = 11; //select the pin for the button
int buttonState = 0; //variable to start and stop the led
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
if(digitalRead(buttonPin)==HIGH){
buttonState = 1;
delay(1000) //So that buttonState does not instantly change back
}
if(digitalRead(buttonPin)==HIGH && buttonState == 1;){
buttonState = 0;
delay(1000) //So that buttonState does not instantly change back
}
while(buttonState == 1){
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// turn the ledPin on
digitalWrite(ledPin, HIGH);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
digitalWrite(ledPin, LOW);
// stop the program for for <sensorValue> milliseconds:
delay(sensorValue);
}
}
Thanks for helping!
Upvotes: 0
Views: 938
Reputation: 1835
A while inside loop is always suspicious, and you provide a good example.
Inside the while loop buttonState
will never change, thus you have a while forever
Simply change it to an if
and your sketch will behave better.
Showing that delay(1000);
is not optimal for button handling. You rather want to handle state changes (and consider bouncing buttons). But that's an advanced question. :)
Upvotes: 0