I'm learning on an Arduno UNO board, and im trying to turn a LED on three times when I connect pin 10 to ground and then turn it off. Then when I unplug the pin number 10 it should NOT blink again... yet it does and I can't find the issue.
this is the entire code:
bool ledBlinked = false;
void setup() {
// put your setup code here, to run once:
pinMode(7, OUTPUT);
pinMode(10, INPUT_PULLUP);
}
//Turns on and off a digital pin, a number of times, with a certain delay
void blinkLed(int pin, int times, int del){
// activates a pin a number of times
for (int i=0; i<=times; i++){
digitalWrite(pin, HIGH);
delay(del);
digitalWrite(pin, LOW);
delay(del);
}
}
//Checks if passed pin number is connected to ground
bool pinIsGround(int pin){
return (digitalRead(10) == LOW);
}
void loop() {
// put your main code here, to run repeatedly:
if(pinIsGround(10) && !ledBlinked){ //if pin is connected to ground and the LED hasn't blinked
blinkLed(7,3, 100); //blink pin 7, 3 times, with a delay of 100ms
ledBlinked = true; //LED has blinked already
}
if (!pinIsGround(10) && ledBlinked){ //if pin is not connected to ground and the LED hasn blinked
digitalWrite(7, LOW); //turn LED off (unnecesary?)
ledBlinked = false; //LED hasn't blinked yet
}
}
1 Answer 1
SInce I can coment I have to write this as answer.
there are two ways of understanding your question:
If you dont want it to ever blink again then simply remove
ledBlinked = false;
If you are trying to prevent the blinking until the button is depressed and pressed again then first think I see is the error in blinkLed function as
for (int i=0; i<=times; i++)
would run times+one time. because it runs first with value of i being 0
(Eg times=4 would run for i equal 0,1,2,3,4 -> Five times )
So correction to for (int i=0; i<times; i++)
would run correct number of times (Eg times=4 would run for i equal 0,1,2,3 -> four times )
Although as you are not checking status during the running of blinkLed function for the status of the button, if you release it while blink is running the script would not notice unless its still unpressed when script gets back to Loop.
Although since hardware operation take more work then logical operation I would recommend if...else statement rather then multiple hardware operations. Although they make code simpler to read
if(digitalRead(10) == LOW){
if(ledBlinked != true)...
} else { ...}
-
I have intentionally avoided writing full code as that would kill the point of you learningTomas– Tomas10/06/2020 01:24:51Commented Oct 6, 2020 at 1:24
switch bounce