In this project, you will learn how to create a Simple Counter Using Global Variable in MicroPython for ESP32 and ESP8266. The counter will increase by one each time a button is pressed. This beginner-friendly project introduces the concept of global variables, which can be accessed and modified from anywhere within the code. You will also gain an understanding of button input, GPIO pins, and basic conditional logic in MicroPython. By following this tutorial, you’ll be able to control and track changes in your MicroPython projects using global variables.
Data Types and Variable Table for Simple Counter Using Global Variable:
Data Type | Variable Name | Description | Example Value |
Integer | counter | Tracks the number of button presses | 0, 1, 2, etc. |
Boolean | button_pressed | Stores the state of the button (pressed or not) | True or False |
The counter is an integer variable that increments by 1 each time the button is pressed, and the button_pressed variable tracks the state of the button to ensure the counter only increments when the button is pressed.
Syntax Table for Simple Counter Using Global Variable in MicroPython for ESP32 and ESP8266:
Function | Syntax | Example |
Global variable declaration | global variable_name | global counter |
Set GPIO input | pin = machine.Pin(pin_number, machine.Pin.IN) | button = machine.Pin(4, machine.Pin.IN) |
Read GPIO state | pin.value() | if button.value() == 1: |
Increment counter | counter += 1 | counter = counter + 1 |
The focus here is on how to declare and use a global variable in MicroPython for ESP32 and ESP8266.
Required Components:
To create a simple counter using a global variable in MicroPython for ESP32 and ESP8266, you will need the following components:
- ESP32 or ESP8266 microcontroller
- 1 Push Button
- 1 Resistor (10kΩ) (to act as a pull-down resistor)
- Breadboard
- Jumper wires
These components are readily available and easy to set up for beginners.
Circuit Diagram for Simple Counter Using Global Variable:
Button ESP32/ESP8266
——- ————
One Leg ——> GPIO4 (Pin 4)
Other Leg ——> GND
GPIO4 also connected to GND through 10kΩ resistor (pull-down)
Circuit Connection Table for Simple Counter Using Global Variable:
Component | Connection | ESP32/ESP8266 Pin | Explanation |
Button (Leg 1) | Connect to GPIO4 | GPIO4 on ESP32/ESP8266 | This pin detects button presses as input. |
Button (Leg 2) | Connect to GND | GND on ESP32/ESP8266 | Completes the button circuit to ground. |
Pull-down resistor | Connect between GPIO4 and GND | 10kΩ resistor | Ensures the GPIO reads LOW (0) when the button is not pressed. |
For beginners, this simple circuit ensures that pressing the button triggers the input, and the pull-down resistor helps to avoid false signals.
Warnings:
- Make sure the pull-down resistor is correctly connected to avoid floating input values, which can lead to inconsistent readings.
- Double-check the wiring of the button to ensure correct functionality and avoid short circuits.
Circuit Analysis:
In this project, the button is connected to GPIO4 of the ESP32/ESP8266. A 10kΩ pull-down resistor is used to keep the GPIO pin grounded when the button is not pressed. When the button is pressed, the GPIO pin is pulled high, triggering an increment in the counter. The counter value is stored in a global variable and printed to the console.
Installing MicroPython and Required Libraries:
- Install MicroPython on ESP32/ESP8266:
- To run MicroPython on your ESP32 or ESP8266, ensure you have flashed the MicroPython firmware using esptool or Thonny:
esptool.py –chip esp32 erase_flash
esptool.py –chip esp32 write_flash -z 0x1000 esp32-20210902-v1.17.bin
- No Additional Libraries Required:
- The built-in machine module is sufficient for controlling GPIO pins and handling button inputs.
Writing the MicroPython Code for Simple Counter Using Global Variable:
import machine
import time
# Initialize the button pin (GPIO4 in this case)
button = machine.Pin(4, machine.Pin.IN)
# Declare a global counter variable and initialize it to 0
counter = 0
# Function to increment the counter when the button is pressed
def increment_counter():
global counter # Declare that we are using the global counter variable
counter += 1 # Increment the counter by 1
print(“Button pressed! Current count:”, counter)
while True:
# Check if the button is pressed (GPIO reads HIGH)
if button.value() == 1:
increment_counter() # Increment the counter
# Wait until the button is released to avoid multiple increments from one press
while button.value() == 1:
time.sleep(0.1)
# Add a short delay to prevent bouncing issues
time.sleep(0.1)
This MicroPython code initializes the button and sets up a global variable called counter. The function increment_counter() is called each time the button is pressed, incrementing the global counter by 1.
Running the Code and Checking the Output:
- Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.
Press the button to increment the counter. The serial monitor will display the current count each time the button is pressed:
Button pressed! Current count: 1
Button pressed! Current count: 2
Button pressed! Current count: 3
Expanding the Project:
- Add a Reset Button: You can add another button to reset the counter to 0.
- Use an OLED Display: Display the counter value on an OLED screen for better visualization.
- Add Multiple Buttons: Create separate counters for each button press to track multiple inputs.
Common Problems and Solutions for Simple Counter Using Global Variable in MicroPython:
- Problem: The counter increments multiple times for a single button press.
- Solution: This issue is often caused by button bouncing. Add a short delay after detecting the button press (debouncing) to avoid multiple counts. The time.sleep(0.1) is included in the code for this reason.
- Problem: The counter is not incrementing when the button is pressed.
- Solution: Ensure that the button is correctly connected to the GPIO pin and ground, and that the pull-down resistor is in place.
- Problem: The button is unresponsive.
- Solution: Check the connections and confirm that the GPIO pin is properly assigned in the code.
FAQ:
Q: Can I use a different GPIO pin for the button?
A: Yes, you can use any available GPIO pin by changing the pin number in the code: button = machine.Pin(pin_number, machine.Pin.IN).
Q: How can I modify the code to reset the counter?
A: You can add another button to reset the counter to 0. Modify the code to include a reset button and create a function that sets counter = 0 when pressed.
Q: What is the purpose of the pull-down resistor?
A: The pull-down resistor ensures that the GPIO pin reads LOW when the button is not pressed, avoiding false readings caused by floating values.
Conclusion:
In this project, you learned how to create a simple counter using a global variable in MicroPython for ESP32 and ESP8266. By tracking button presses with a global variable, you gained a deeper understanding of GPIO input, global variable declaration, and conditional logic. This project is highly expandable, allowing you to add more buttons, use a display, or even connect to a server for IoT applications.