Generate the schematic and code necessary for controlling an LED via button pres
ID: 2080136 • Letter: G
Question
Generate the schematic and code necessary for controlling an LED via button press. Also include a feature such that if the button has been used to turn the LED on and off twice, the LED no longer responds. The serial monitor also then reports, “Button pushed too many times”. Build the circuit and test it. Hint: a simple way to do this is have a variable that is set to a certain value at startup, but is then potentially modified by subsequent code. Within the loop code, you have different segments of code that run depending on the value of this variable.
Explanation / Answer
Here I'm writing a sheatic program that you can turn on the LED when you press the button then turn it off when you press the button again. The initial state of the LED is off but if you want to be on you have to change int stateLED = HIGH.
int pinButton = 8;
int LED = 2;
int stateLED = LOW;
int stateButton;
int previous = LOW;
long time = 0;
long debounce = 200;
void setup() {
pinMode(pinButton, INPUT);
pinMode(LED, OUTPUT);
}
void loop() {
stateButton = digitalRead(pinButton);
if(stateButton == HIGH && previous == LOW && millis() - time > debounce) {
if(stateLED == HIGH){
stateLED = LOW;
} else {
stateLED = HIGH;
}
time = millis();
}
digitalWrite(LED, stateLED);
previous == stateButton;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.