HI folks, I'm new to adruino, not to C, but yes to arduino.
I have 2 push buttons, one LED.
First I used a simple program to swith the on with the push of Button A, and turn it off with the push of button B.
That worked fine.
Then I wanted the LED to turn on and keep blinking, until I pushed button B. I couldn't.
Then, for the LED to start blinking without delay() I used this, but I couldn't find any way to stop it with the push of button B.
int ledPin = 5;
int buttonApin = 9;
int buttonBpin = 8;
unsigned long previousMillis = 0;
const long interval = 1000;
int ledState;
byte leds = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonApin, INPUT_PULLUP);
pinMode(buttonBpin, INPUT_PULLUP);
}
void loop()
{
if (digitalRead(buttonApin) == LOW){
while(digitalRead(buttonBpin) =! LOW){
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}
}
}
I used the mills() function to avoid delay(), but the while loop doesn' seem to stop when I press the button B.
This is the circuit attached.
Thank you all in advance.-
'Internal' as opposed to reading the I/O directly. You can either make it a global variable or declare ir in the loop(), in which case it needs to be static so that it does not get re-initiliased every time through loop().
Hi,
You need to detect when the buttons are BEING pressed , not pressed.
I think you need in Pseudo Code;
If Button A goes from HIGH to LOW.
Set stateBlink variable HIGH
If stateBlink is HIGH
then Blink
else
don't Blink
If Button B goes from HIGH to LOW.
Set stateBlink variable LOW
code loops back
The thing about this method is you don't need to worry about debouncing.
const int ledPin = 5;
const int buttonApin = 9;
const int buttonBpin = 8;
const unsigned long interval = 1000;
boolean Blinking = false;
boolean ledState = false;
unsigned long previousMillis = 0;
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(buttonApin, INPUT_PULLUP);
pinMode(buttonBpin, INPUT_PULLUP);
}
void loop()
{
if (digitalRead(buttonApin) == LOW)
Blinking = true;
if (digitalRead(buttonBpin) == LOW)
Blinking = false;
if (Blinking)
{
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
// save the last time you blinked the LED
previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa:
ledState = !ledState;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
} // end if (Blinking)
}