You will make a push button switch turn on and off the light in different ways.
Software Discovery: Variable, Digital input, if-else, toggle switch
Other Discovery: Switch
Qty Part
1 LED
1 Resistor [10 kΩ]
1 Resistor [150Ω]
1 Push button
Software Discovery: Variable, Digital input, if-else, toggle switch
Other Discovery: Switch
Qty Part
1 LED
1 Resistor [10 kΩ]
1 Resistor [150Ω]
1 Push button
Resources: |
|
|
Let get Coding!
Part 1: On/Off Switch const int button = 11; // the number of the pushbutton pin const int led = 4; // the number of the LED pin int buttonState = 0; // variable for reading the pushbutton status void setup() { pinMode(led, OUTPUT); // initialize the LED pin as an output pinMode(button, INPUT); // initialize the pushbutton pin as an input } void loop() { buttonState = digitalRead(button); // read state of the pushbutton value if (buttonState == HIGH) // check if the pushbutton is pressed digitalWrite(led, HIGH); // if HIGH, turn LED on else digitalWrite(led, LOW); // turn LED off } | Part 2: Latch Switch const int button = 11; const int led = 4; int currentState = LOW; int previousState = LOW; int ledState = LOW; void setup() { pinMode(button, INPUT); pinMode(led, OUTPUT); digitalWrite(led, LOW); } void loop() { currentState = digitalRead(button); if ((currentState == HIGH) && (previousState == LOW)) { if (ledState == LOW) // toggle ledstate from LOW to HIGH ledState = HIGH; // or HIGH to LOW else // depending on the initial state ledState = LOW; } previousState = currentState; // moves currentState to previousState digitalWrite(led, ledState); // for next cycle delay(10); } |