-
Notifications
You must be signed in to change notification settings - Fork 8
Exercise 06: Monitor Pushbutton Status on GPIP0 (LED ON OFF)
Pushbutton is a momentary switch that closed the circuit during press of the button, while the button is released, the circuit disconnected, such as shown in the animation below. It is not a toggle switch, where it has ON and OFF position. Pushbutton usually used to act as an input to trigger the system.
On Hibiscus Sense, there are two pushbutton:
-
RSTpush the button to reset the ESP32 program. -
IO0connected to GPIO0.
Both pushbutton in Hibiscus Sense applying pull-up resistor, to prevent floating voltage with capacitor to fix debouncing effect of pushbutton. The circuit is complete when we push the IO0 pushbutton, then ESP32 saw LOW state at GPIO0, because GND is connected to the junction of GPIO0 in the circuit, as shown in the schematic below.
Somehow, if a pushbutton circuit is applying pull-down resistor, as shown in the schematic below. ESP32 saw HIGH state at GPIO0 when the IO0 pushbutton is pressed, because 3.3V is connected to the junction of GPIO0. This is NOT the circuit on Hibiscus Sense.
Since we know that ESP32 will sense LOW state at GPIO0 during pushbutton pressed, so the program as follows:
Complete Sketch
void setup() {
pinMode(0, INPUT); // declaring GPIO0 as an INPUT pin.
pinMode(2, OUTPUT); // declaring GPIO2 as an OUTPUT pin.
}
void loop() {
// we use if() function to compare the GPIO0 reading state with the LOW state.
// if the GPIO0 reading is LOW, light ON the LED on GPIO2 with LOW state.
// else means, the GPIO0 reading is HIGH, light OFF the LED on GPIO2 with HIGH state.
int pbstatus = digitalRead(0);
if(pbstatus == LOW) digitalWrite(2, LOW);
else digitalWrite(2, HIGH);
}Detail Sketch Explanations
In the void setup() function we declare two pinMode() function:
- To declare GPIO0 as an INPUT pin, connected to the Pushbutton.
- To declare GPIO2 as an OUTPUT pin, connected to the blue LED.
pinMode(0, INPUT); // declaring GPIO0 as an INPUT pin.
pinMode(2, OUTPUT); // declaring GPIO2 as an OUTPUT pin.In the void loop() function we want to repeatedly monitor the state of GPIO0, either LOW or HIGH depending the action happen on the pushbutton, either pressed or release.
- Create local variable named as
pbstatusto store the current state of GPIO.
int pbstatus = digitalRead(0);- Applying
if()function to compare, either the value ofpbstatusvariable equal toLOWor else (HIGH). If thepbstatus == LOWturn ON the LED and ifpbstatusequal to other thanLOWturn OFF the LED.
if(pbstatus == LOW) digitalWrite(2, LOW);
else digitalWrite(2, HIGH);Now, we can upload the complete sketch to ESP32. Now we'll see the blue is turn OFF, as it will only turn ON once we pressed the IO0 pushbutton.




