For Loop with List in MicroPython for ESP32 and ESP8266

In this project, you will learn how to iterate through a list of numbers using a For Loop with List in MicroPython for ESP32 and ESP8266. The for loop is one of the most commonly used control structures in programming, allowing you to loop through items in a sequence. In this project, you’ll create a list of numbers and print each number one by one, helping you understand the basics of list iteration and loops in MicroPython.

Data Types and Variable Table for For Loop with List:

Data Type Variable Name Description Example Value
List numbers_list A list of numbers to iterate through [1, 2, 3, 4, 5]
Integer number Stores the current number in the loop 1, 2, 3

The list contains numbers that the for loop will iterate through, while the integer variable stores the value of each number as it is printed.

Syntax Table for For Loop with List in MicroPython:

Operation Syntax Example
Create a list list_name = [item1, item2, item3] numbers_list = [1, 2, 3, 4, 5]
For loop to iterate a list for item in list_name: for number in numbers_list:
Print each item print(item) print(number)

This project introduces the for loop and shows how to iterate through a list of numbers.

Required Components:

  • ESP32 or ESP8266
  • Computer with Thonny (or another MicroPython IDE)

Since this project focuses on programming, no additional hardware components are required.

Circuit Diagram:

(No circuit diagram is required as this project focuses on programming.)

Circuit Connection Table:

(No circuit connections are needed for this project.)

Warnings:

  • Ensure that the list used in the project contains valid data types to avoid errors during iteration.
  • Always ensure the for loop is correctly structured to avoid infinite loops.

Circuit Analysis:

This project does not require external components, as the focus is on for loops and list iteration in MicroPython. The loop will go through each number in the list and print it to the console.

Installing MicroPython and Required Libraries:

Install MicroPython on ESP32/ESP8266: Ensure that you have MicroPython installed on your ESP32 or ESP8266. Use esptool or Thonny to flash the MicroPython firmware:
esptool.py –chip esp32 erase_flash

esptool.py –chip esp32 write_flash -z 0x1000 esp32-20210902-v1.17.bin

  1. No Additional Libraries Needed: The built-in functionality of MicroPython is sufficient to handle the for loop and list iteration.

Writing the MicroPython Code for For Loop with List:

Here’s the simple code that creates a list of numbers and iterates through it using a for loop:

# Define a list of numbers

numbers_list = [1, 2, 3, 4, 5]

 

# Loop through the list and print each number

for number in numbers_list:

    print(“Number:”, number)

 

Explanation of the Code:

  1. The list numbers_list contains five numbers: [1, 2, 3, 4, 5].
  2. The for loop iterates through each number in the list.
  3. During each iteration, the current number is printed using the print() function, displaying it in the serial console.

Running the Code and Checking the Output:

  1. Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.

Open the serial monitor to observe the output, which will show each number printed one by one:

Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

Expanding the Project:

  • Modify the List: Change the list to contain different types of data, such as strings, and see how the for loop behaves.
  • Nested Loops: Add a nested loop inside the for loop to perform more complex iterations, such as printing combinations of two lists.
  • Sum of the List: Expand the project to calculate the sum of all numbers in the list using a for loop.

Common Problems and Solutions:

  1. Problem: The program throws an error when trying to iterate through a list.
    • Solution: Ensure that the list is properly defined and that all items in the list are of compatible data types.
  2. Problem: The list is not being printed correctly.
    • Solution: Double-check the syntax of the for loop and ensure that the print() function is inside the loop.
  3. Problem: The for loop runs indefinitely.
    • Solution: Ensure that the loop structure is correct and that it is iterating over a defined list. Infinite loops often occur when using while loops or incorrectly structured for loops.

FAQ:

Q: Can I iterate over a list with different data types?
A: Yes, a list in MicroPython can contain different data types (e.g., strings, integers, floats), and you can still iterate through the list using a for loop.

Q: How can I break out of the loop early?
A: Use the break statement inside the loop if you want to stop the iteration early based on a certain condition.

Q: Can I use a for loop to modify the list while iterating?
A: It’s not recommended to modify a list while iterating through it as it can lead to unexpected results. Instead, consider creating a copy of the list or iterating over a fixed range.

Conclusion:

In this project, you learned how to use a for loop to iterate through a list of numbers in MicroPython for ESP32 and ESP8266. By looping through the list and printing each item, you gained an understanding of how to work with lists and loops in MicroPython, which is a fundamental skill in programming. This project can be expanded to work with more complex data and operations.

Blinking LED with If-Else in MicroPython for ESP32 and ESP8266

In this project, you will learn how to control the Blinking LED with If-Else in MicroPython for ESP32 and ESP8266. The LED will blink when a button is pressed, and it will remain off when the button is not pressed. This project demonstrates how to use if-else conditional logic, which is an essential part of programming. By working through this simple project, you’ll gain a solid understanding of how conditional statements work in MicroPython.

Data Types and Variable Table for Blinking LED with If-Else:

Data Type Variable Name Description Example Value
Boolean button_pressed Stores the state of the button (True/False) True
Boolean led_state Controls whether the LED is on or off True or False

The boolean variable tracks whether the button is pressed, and the LED state determines whether the LED is blinking or turned off.

Syntax Table for Blinking LED with If-Else in MicroPython:

Function Syntax Example
Read button input button.value() if button.value() == 1:
If-else statement if condition: and else: if button_pressed:
Toggle LED led.value() led.value(1) (Turn LED on)
Add a delay time.sleep(seconds) time.sleep(0.5)

This project uses the if-else structure to control the LED’s behavior based on the state of the button.

Required Components:

  • ESP32 or ESP8266
  • 1 LED
  • 1 Button
  • 1 Resistor (220Ω for LED, 10kΩ for button)
  • Breadboard
  • Jumper wires

Circuit Diagram:

               LED          ESP32/ESP8266

               —–          ————

               Anode  ——> GPIO5 (Pin 5)

               Cathode ——> GND

 

                Button        ESP32/ESP8266

               —–          ————

               One Leg ——> GPIO4 (Pin 4)

               Other Leg —-> GND

 

Circuit Connection Table:

Component Connection ESP32/ESP8266 Pin Explanation
LED Anode Connect to GPIO5 GPIO5 on ESP32/ESP8266 Controls the LED ON/OFF state
LED Cathode Connect to GND GND on ESP32/ESP8266 Completes the LED circuit
Button (Leg 1) Connect to GPIO4 GPIO4 on ESP32/ESP8266 Detects when the button is pressed
Button (Leg 2) Connect to GND GND on ESP32/ESP8266 Completes the button circuit

Warnings:

  • Ensure that the LED has a 220Ω resistor to prevent it from being damaged by excessive current.
  • Use a 10kΩ pull-down resistor for the button to stabilize the button input and avoid floating signals.

Circuit Analysis:

  • The button is connected to GPIO4 and serves as an input to detect when it is pressed.
  • The LED is connected to GPIO5, and it will blink when the button is pressed. When the button is not pressed, the LED will stay off.
  • The program continuously checks the button state and uses an if-else statement to determine whether the LED should blink or remain off.

Installing MicroPython and Required Libraries:

Install MicroPython on ESP32/ESP8266: Ensure that MicroPython is installed on your ESP32 or ESP8266. Use esptool or Thonny to flash the MicroPython firmware:
esptool.py –chip esp32 erase_flash

esptool.py –chip esp32 write_flash -z 0x1000 esp32-20210902-v1.17.bin

  1. No Additional Libraries Needed: The built-in machine module is enough to handle GPIO control for the LED and button.

Writing the MicroPython Code for Blinking LED with If-Else:

import machine

import time

 

# Initialize the LED (GPIO5) and the button (GPIO4)

led = machine.Pin(5, machine.Pin.OUT)

button = machine.Pin(4, machine.Pin.IN)

 

while True:

    # Check if the button is pressed

    button_pressed = button.value() == 1

    

    # If the button is pressed, blink the LED

    if button_pressed:

        led.value(1)  # Turn LED ON

        time.sleep(0.5)  # Wait for half a second

        led.value(0)  # Turn LED OFF

        time.sleep(0.5)  # Wait for half a second

        print(“LED Blinking”)

    else:

        led.value(0)  # Keep LED OFF when the button is not pressed

        print(“LED OFF”)

 

    # Short delay to avoid rapid state changes

    time.sleep(0.1)

 

Explanation of the Code:

  1. LED and button are initialized using their respective GPIO pins.
  2. The program continuously checks if the button is pressed by reading the button’s state.
  3. If the button is pressed, the LED blinks by turning it on, waiting for 0.5 seconds, then turning it off.
  4. If the button is not pressed, the LED remains off.
  5. The program adds a short delay to avoid rapid state changes in the button reading.

Running the Code and Checking the Output:

  1. Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.
  2. Press the button to observe the LED blinking, and release the button to keep the LED off.

The output on the serial monitor will show:
LED Blinking

LED OFF

Expanding the Project:

  • Add Multiple LEDs: Add more LEDs and control each one with a separate button using the if-else logic.
  • Adjust Blinking Speed: Allow the button to control the speed of the blinking LED by adjusting the delay values.
  • Add a Display: Use an OLED display to show the status of the button and LED in real-time.

Common Problems and Solutions:

  1. Problem: The LED does not blink when the button is pressed.
    • Solution: Check the wiring of the button and the LED, and ensure the correct GPIO pins are being used in the code.
  2. Problem: The LED flickers or behaves inconsistently.
    • Solution: Ensure the pull-down resistor is properly connected to prevent floating input signals from the button.
  3. Problem: The program does not respond to the button press.
    • Solution: Make sure the button is correctly wired and that the GPIO pin reading the button’s state is properly initialized.

FAQ:

Q: Can I use a different GPIO pin for the button or LED?
A: Yes, you can use any available GPIO pin on the ESP32/ESP8266. Update the pin numbers in the code, such as button = machine.Pin(pin_number, machine.Pin.IN).

Q: How can I change the speed of the LED blinking?
A: You can adjust the time.sleep() values in the code to increase or decrease the time between the LED turning on and off.

Q: Can I control more than one LED with this project?
A: Yes, you can add more LEDs and buttons and use additional if-else statements to control multiple LEDs.

Conclusion:

In this project, you successfully built a blinking LED controlled by a button using if-else statements in MicroPython for ESP32 and ESP8266. The project demonstrates how to use conditional logic to control hardware components based on user input. This simple example can be expanded into more complex projects involving multiple LEDs, sensors, or even displays for real-time feedback.

Toggle LED Using OR Operator in MicroPython for ESP32 and ESP8266

In this project, you will control Toggle LED Using OR Operator in MicroPython for ESP32 and ESP8266. The LED will turn on if either Button A or Button B is pressed. This project demonstrates how to use the or operator, which is a fundamental logical operator that checks if at least one of the conditions is true. This is an excellent beginner-friendly project for learning how to use multiple input buttons to control a single output in MicroPython.

Data Types and Variable Table for Toggle LED Using OR Operator:

Data Type Variable Name Description Example Value
Boolean button_a_pressed Stores the state of Button A (True/False) True
Boolean button_b_pressed Stores the state of Button B (True/False) False
Boolean led_state Controls whether the LED is on or off True or False

In this project, boolean variables are used to store whether Button A or Button B is pressed, while another boolean variable controls the LED’s state.

Syntax Table for Toggle LED Using OR Operator in MicroPython:

Function Syntax Example
Read button input button.value() if button_a.value() == 1:
Apply OR condition if condition1 or condition2: if button_a_pressed or button_b_pressed:
Set LED state led.value() led.value(1) (Turn LED on)

This project uses the OR operator (or) to check if either Button A or Button B is pressed to toggle the LED.

Required Components:

  • ESP32 or ESP8266
  • 1 LED
  • 2 Buttons (Button A and Button B)
  • 2 Resistors (10kΩ for buttons, 220Ω for LED)
  • Breadboard
  • Jumper wires

Circuit Diagram:

               LED          ESP32/ESP8266

               —–          ————

               Anode  ——> GPIO5 (Pin 5)

               Cathode ——> GND

 

                Button A      ESP32/ESP8266

               —–          ————

               One Leg ——> GPIO4 (Pin 4)

               Other Leg —-> GND

 

                Button B      ESP32/ESP8266

               —–          ————

               One Leg ——> GPIO15 (Pin 15)

               Other Leg —-> GND

 

Circuit Connection Table:

Component Connection ESP32/ESP8266 Pin Explanation
LED Anode Connect to GPIO5 GPIO5 on ESP32/ESP8266 Controls the LED ON/OFF state
LED Cathode Connect to GND GND on ESP32/ESP8266 Completes the LED circuit
Button A (Leg 1) Connect to GPIO4 GPIO4 on ESP32/ESP8266 Detects when Button A is pressed
Button A (Leg 2) Connect to GND GND on ESP32/ESP8266 Completes Button A circuit
Button B (Leg 1) Connect to GPIO15 GPIO15 on ESP32/ESP8266 Detects when Button B is pressed
Button B (Leg 2) Connect to GND GND on ESP32/ESP8266 Completes Button B circuit

Warnings:

  • Ensure the LED has a 220Ω resistor to prevent it from burning out due to excessive current.
  • Use 10kΩ pull-down resistors with the buttons to ensure stable and accurate readings.

Circuit Analysis:

  • Button A is connected to GPIO4, and Button B is connected to GPIO15 on the ESP32/ESP8266. These buttons act as inputs that detect user presses.
  • The LED is connected to GPIO5 and will turn on when either Button A or Button B is pressed, thanks to the use of the OR operator in the code.

Installing MicroPython and Required Libraries:

Install MicroPython on ESP32/ESP8266: Ensure MicroPython is installed on your ESP32 or ESP8266. You can flash 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

  1. No Additional Libraries Needed: The built-in machine module is sufficient for handling GPIO pins in this project.

Writing the MicroPython Code for Toggle LED Using OR Operator:

import machine

import time

# Initialize the LED (GPIO5), Button A (GPIO4), and Button B (GPIO15)

led = machine.Pin(5, machine.Pin.OUT)

button_a = machine.Pin(4, machine.Pin.IN)

button_b = machine.Pin(15, machine.Pin.IN)

 

while True:

    # Check if Button A or Button B is pressed

    button_a_pressed = button_a.value() == 1

    button_b_pressed = button_b.value() == 1

    

    # If either button is pressed, turn on the LED

    if button_a_pressed or button_b_pressed:

        led.value(1)  # Turn the LED ON

        print(“LED ON – Either Button A or Button B is pressed”)

    else:

        led.value(0)  # Turn the LED OFF

        print(“LED OFF”)

 

    # Add a short delay to avoid rapid state changes

    time.sleep(0.1)

 

Explanation of the Code:

  1. LED, Button A, and Button B are initialized using their respective GPIO pins.
  2. The program continuously checks if either Button A or Button B is pressed using the OR operator (or).
  3. If either button is pressed, the LED is turned on. Otherwise, the LED remains off.
  4. The LED state is printed to the console, indicating whether the LED is ON or OFF.

Running the Code and Checking the Output:

  1. Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.
  2. Press Button A or Button B, and observe the LED turning on.

The output on the serial monitor will show:
LED ON – Either Button A or Button B is pressed

LED OFF

Expanding the Project:

  • Add a Buzzer: Include a buzzer that sounds when either button is pressed, along with the LED lighting up.
  • Add More Buttons: Expand the project by adding additional buttons and controlling multiple LEDs based on different conditions.
  • Wireless Control: Integrate Wi-Fi to control the buttons and LED remotely via a mobile app.

Common Problems and Solutions:

  1. Problem: The LED does not turn on when either button is pressed.
    • Solution: Double-check the button wiring and ensure the correct GPIO pins are used in the code for Button A and Button B.
  2. Problem: The LED flickers or behaves erratically.
    • Solution: Ensure that pull-down resistors are correctly connected to stabilize the button inputs.
  3. Problem: The serial monitor does not display the expected output.
    • Solution: Ensure that the MicroPython code is correctly uploaded and that the serial monitor is open and working in your IDE.

FAQ:

Q: Can I use different GPIO pins for the buttons and LED?
A: Yes, you can change the GPIO pin assignments in the code by updating the pin numbers during initialization, such as button_a = machine.Pin(pin_number, machine.Pin.IN).

Q: Can I add more buttons to this project?
A: Yes, you can easily expand the project by adding more buttons and using additional logical operators like and or not to control the LED in different ways.

Q: Why do I need pull-down resistors for the buttons?
A: Pull-down resistors ensure that the GPIO pins read a LOW state when the buttons are not pressed, preventing erratic behavior caused by floating input values.

Conclusion:

In this project, you learned how to toggle an LED using the OR operator in MicroPython for ESP32 and ESP8266. By using two buttons, you controlled the LED to turn on when either Button A or Button B is pressed.

Light Control with AND Condition in MicroPython for ESP32 and ESP8266

In this project, you will learn how to control an Light Control with AND Condition in MicroPython for ESP32 and ESP8266. The LED will only turn on when both conditions are met: a button is pressed, and the light sensor reading is low (indicating darkness). This project helps you understand how to use the and operator in MicroPython to combine multiple conditions. By using boolean logic, you can control hardware based on multiple inputs, which is a key concept in many IoT and automation projects.

Data Types and Variable Table for Light Control with AND Condition:

Data Type Variable Name Description Example Value
Boolean button_pressed Stores the state of the button (True/False) True
Integer light_level Stores the reading from the light sensor 300
Boolean led_state Controls whether the LED is on or off True or False

In this project, boolean variables track whether the button is pressed and if the light sensor reading is low, while the integer variable stores the light sensor reading.

Syntax Table for Light Control with AND Condition in MicroPython:

Function Syntax Example
Read button input button.value() if button.value() == 1:
Read light sensor value adc.read() light_level = adc.read()
Apply AND condition if condition1 and condition2: if button_pressed and light_level < 500:
Set LED state led.value() led.value(1) (Turn LED on)

Required Components:

  • ESP32 or ESP8266
  • 1 LED
  • 1 Button
  • 1 Light Sensor (LDR)
  • 1 Resistor (220Ω for LED, 10kΩ for LDR)
  • Breadboard
  • Jumper wires

Circuit Diagram:

               LED          ESP32/ESP8266

               —–          ————

               Anode  ——> GPIO5 (Pin 5)

               Cathode ——> GND

 

                Button        ESP32/ESP8266

               —–          ————

               One Leg ——> GPIO4 (Pin 4)

               Other Leg —-> GND

 

                LDR           ESP32/ESP8266

               —–          ————

               One Leg ——> GPIO32 (Pin 32)

               Other Leg —-> GND through 10kΩ resistor

 

Circuit Connection Table:

Component Connection ESP32/ESP8266 Pin Explanation
LED Anode Connect to GPIO5 GPIO5 on ESP32/ESP8266 Controls the LED ON/OFF state
LED Cathode Connect to GND GND on ESP32/ESP8266 Completes the LED circuit
Button (Leg 1) Connect to GPIO4 GPIO4 on ESP32/ESP8266 Detects button presses
Button (Leg 2) Connect to GND GND on ESP32/ESP8266 Completes the button circuit
LDR (Leg 1) Connect to GPIO32 GPIO32 on ESP32/ESP8266 Measures light levels
LDR (Leg 2) Connect to GND through 10kΩ resistor GND Acts as a voltage divider to ensure accurate light sensor readings

Warnings:

  • Make sure the LED has a 220Ω resistor to prevent it from burning out due to excessive current.
  • Use a 10kΩ pull-down resistor with the light sensor (LDR) to ensure stable and accurate readings.

Circuit Analysis:

  • The button is connected to GPIO4 and is used to trigger the LED when pressed.
  • The light sensor (LDR) is connected to GPIO32 and acts as a voltage divider to measure the ambient light level. The ESP32/ESP8266 will read the voltage drop across the LDR to determine whether the environment is dark or bright.
  • The LED is connected to GPIO5 and will turn on when the button is pressed, and the light sensor detects low light conditions.

Installing MicroPython and Required Libraries:

Install MicroPython on ESP32/ESP8266: To get started, ensure that you have MicroPython installed on your ESP32 or ESP8266. You can flash 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

  1. No Additional Libraries Needed: The built-in machine module is sufficient for handling GPIO pins and analog input for this project.

Writing the MicroPython Code for Light Control with AND Condition:

import machine

import time

 

# Initialize the LED (GPIO5), button (GPIO4), and light sensor (GPIO32)

led = machine.Pin(5, machine.Pin.OUT)

button = machine.Pin(4, machine.Pin.IN)

adc = machine.ADC(machine.Pin(32))  # ADC channel for the light sensor

 

# Set the threshold for low light condition (adjust based on your environment)

light_threshold = 500

 

while True:

    # Read the button state (pressed or not)

    button_pressed = button.value() == 1

    

    # Read the light level from the light sensor (ADC)

    light_level = adc.read()

 

    # Check if both the button is pressed AND the light level is low

    if button_pressed and light_level < light_threshold:

        led.value(1)  # Turn the LED ON

        print(“LED ON – Button Pressed and Light is Low”)

    else:

        led.value(0)  # Turn the LED OFF

        print(“LED OFF”)

 

    # Delay to avoid rapid state changes

    time.sleep(0.1)

Explanation of the Code:

  1. LED, button, and light sensor are initialized using GPIO pins.
  2. The ADC (Analog to Digital Converter) reads the light level from the light sensor.
  3. The program continuously checks if the button is pressed and if the light level is below the threshold. If both conditions are true (using the AND condition), the LED turns on.
  4. If either condition is false, the LED remains off.

Running the Code and Checking the Output:

  1. Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.
  2. Press the button in a low-light environment to see the LED turn on.

The output on the serial monitor will show:
LED ON – Button Pressed and Light is Low

LED OFF

Expanding the Project:

  • Add a Buzzer: Include a buzzer that sounds when the button is pressed and light conditions are met.
  • Adjust the Light Sensitivity: Use a potentiometer to adjust the light sensor’s sensitivity to changing light conditions.
  • Wireless Control: Connect the project to a mobile app using Wi-Fi to control the LED remotely, based on light sensor input.

Common Problems and Solutions:

  1. Problem: The LED does not turn on when the button is pressed.
    • Solution: Double-check the button wiring and ensure that GPIO4 is properly connected to the button. Also, confirm that the light sensor reading is below the threshold.
  2. Problem: The light sensor is giving inconsistent readings.
    • Solution: Ensure the 10kΩ pull-down resistor is connected correctly to stabilize the readings from the light sensor.
  3. Problem: The LED remains on even when the light level is not low.
    • Solution: Adjust the light threshold value to better match your environment’s lighting conditions.

FAQ:

Q: Can I use a different GPIO pin for the button or LED?
A: Yes, you can change the GPIO pin assignments in the code by updating the pin numbers during initialization, such as button = machine.Pin(pin_number, machine.Pin.IN).

Q: How do I adjust the light sensitivity of the sensor?
A: Modify the light_threshold value in the code to change the point at which the LED turns on or off based on the light sensor’s readings.

Q: What happens if the button is pressed but the light level is not low?
A: The LED will remain off unless both the button is pressed and the light level is below the specified threshold. This is because the project uses the AND operator, meaning both conditions must be true for the LED to turn on.

Q: Can I use a different sensor instead of the light sensor (LDR)?
A: Yes, you can use other sensors, such as a temperature or motion sensor. Just update the code to read the appropriate sensor values and modify the threshold or conditions accordingly.

Conclusion:

In this project, you learned how to control an LED using the AND condition in MicroPython for ESP32 and ESP8266. By using a combination of a button press and a light sensor reading, you successfully controlled the LED based on multiple conditions. This project is an excellent introduction to working with boolean logic in hardware projects, enabling you to combine multiple inputs for complex control scenarios. With some adjustments, this project can be expanded into an advanced light control system, making it a great building block for future projects.

 

Temperature Difference Calculation in MicroPython for ESP32 and ESP8266

In this project, we will read two temperature values from a sensor (such as the DHT11 or DHT22) and calculate the temperature difference between them. This project demonstrates how to use subtraction and division operators to calculate and display the difference. By performing simple arithmetic operations on sensor data, you’ll gain a practical understanding of how to work with Temperature Difference Calculation in MicroPython for ESP32 and ESP8266.

Data Types and Variable Table for Temperature Difference Calculation:

Data Type Variable Name Description Example Value
Float temp1 Stores the first temperature reading 25.0°C
Float temp2 Stores the second temperature reading 30.5°C
Float temp_difference Stores the difference between the two values 5.5°C

In this project, temperature values are read as floating-point numbers and used to calculate their difference.

Syntax Table for Temperature Difference Calculation in MicroPython:

Operation Syntax Example
Subtraction temp_difference = temp1 – temp2 temp_difference = 30.5 – 25.0
Division (optional) average_temp = (temp1 + temp2) / 2 average_temp = (25.0 + 30.5) / 2

This table outlines the key operations used in this project, focusing on subtraction and division for temperature calculations.

Required Components:

  • ESP32 or ESP8266
  • DHT11 or DHT22 Sensor (Temperature and humidity sensor)
  • Jumper wires
  • Breadboard

These components will allow you to read temperature data and perform calculations on it.

Circuit Diagram:

          DHT11/DHT22       ESP32/ESP8266

           ————      ————

           VCC  ———->  3.3V

           GND  ———->  GND

           DATA ———->  GPIO4 (Pin 4)

 

Circuit Connection Table:

Component Connection ESP32/ESP8266 Pin Explanation
DHT11/DHT22 Pin VCC (Power) 3.3V on ESP32/ESP8266 Supplies power to the DHT11/DHT22 sensor.
DHT11/DHT22 Pin GND (Ground) GND on ESP32/ESP8266 Connects the sensor to ground.
DHT11/DHT22 Pin DATA (Data line) GPIO4 on ESP32/ESP8266 Sends temperature data to the microcontroller.

Warnings:

  • Ensure the sensor is connected to the 3.3V pin of the ESP32/ESP8266 to avoid damaging the sensor.
  • Always check wiring before powering the circuit to prevent connection issues.

Installing MicroPython and Libraries:

Install MicroPython on ESP32/ESP8266: If you haven’t already installed MicroPython on your ESP32 or ESP8266, follow these steps:
esptool.py –chip esp32 erase_flash

esptool.py –chip esp32 write_flash -z 0x1000 esp32-20210902-v1.17.bin

Install Required Libraries: To read data from the DHT11 or DHT22 sensor, you’ll need to import the dht module:
import dht

import machine

import time

Writing the MicroPython Code for Temperature Difference Calculation:

Here’s the code to read temperature values from the DHT11 sensor, calculate the difference, and display the result:

import dht

import machine

import time

 

# Initialize the DHT sensor (DHT11 or DHT22)

sensor = dht.DHT11(machine.Pin(4))  # Use DHT22 for DHT22 sensor

 

def read_temperature():

    # Trigger the sensor to measure temperature

    sensor.measure()

    # Return the temperature reading as a float

    return float(sensor.temperature())

 

# Read two temperature values

print(“Reading first temperature…”)

temp1 = read_temperature()

time.sleep(2)

 

print(“Reading second temperature…”)

temp2 = read_temperature()

 

# Calculate the temperature difference

temp_difference = temp2 – temp1

print(“Temperature 1:”, temp1, “°C”)

print(“Temperature 2:”, temp2, “°C”)

print(“Temperature difference:”, temp_difference, “°C”)

 

# Optional: Calculate the average temperature

average_temp = (temp1 + temp2) / 2

print(“Average temperature:”, average_temp, “°C”)

 

Explanation of the Code:

  1. The read_temperature() function reads the temperature from the DHT sensor and converts it to a float.
  2. The program reads two temperature values, temp1 and temp2, with a 2-second delay in between.
  3. The temperature difference is calculated by subtracting temp1 from temp2.
  4. The result is printed along with the individual temperatures.
  5. Optionally, the code calculates and prints the average temperature using the division operator.

Running the Code and Checking the Output:

  1. Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.

Observe the output on the serial monitor, which will display the two temperature values, their difference, and the average temperature:
Reading first temperature…

Temperature 1: 25.0 °C

Reading second temperature…

Temperature 2: 30.5 °C

Temperature difference: 5.5 °C

Average temperature: 27.75 °C

Expanding the Project:

  • Multiple Sensor Readings: Expand the project to read more than two temperature values and calculate the difference between multiple readings.
  • Add an OLED Display: Display the temperature values and their difference on an OLED screen instead of the serial monitor.
  • Log Data: Store temperature readings and their differences in a file for later analysis.

Common Problems and Solutions:

  1. Problem: Incorrect temperature readings or no data output.
    • Solution: Check the wiring, especially the DATA pin. Ensure the correct GPIO pin is used in the code.
  2. Problem: Sensor is not responding or giving an error.
    • Solution: Ensure the sensor is powered correctly and connected to the right pin. Also, verify the integrity of the sensor.
  3. Problem: Incorrect temperature difference calculation.
    • Solution: Double-check the order of subtraction (e.g., temp2 – temp1) to ensure the difference is calculated correctly.

FAQ:

Q: Can I use a different GPIO pin for the sensor?
A: Yes, you can connect the sensor’s DATA pin to any available GPIO pin on the ESP32/ESP8266. Be sure to update the pin number in the code accordingly.

Q: How do I handle sensor errors?
A: Use try-except blocks to handle potential sensor errors and avoid program crashes.

Q: Can I use a different sensor like DHT22?
A: Yes, simply change the sensor initialization from dht.DHT11() to dht.DHT22() in the code.

Conclusion:

In this project, you successfully built a program to calculate the temperature difference between two readings using MicroPython for ESP32 and ESP8266. By utilizing subtraction and division operators, you learned how to process sensor data and perform basic calculations. This project can be expanded by adding displays, logging data, or even connecting multiple sensors for advanced temperature monitoring.

Basic Arithmetic Calculator in MicroPython for ESP32 and ESP8266

In this project, you will build a simpleBasic Arithmetic Calculator in MicroPython for ESP32 and ESP8266. The calculator will perform the four basic arithmetic operations: addition, subtraction, multiplication, and division, displaying the result of each operation. By working through this project, you will gain hands-on experience with arithmetic operators in MicroPython, making it an ideal starting point for beginners to understand fundamental mathematical operations in programming.

Data Types and Variable Table for Basic Arithmetic Calculator:

Data Type Variable Name Description Example Value
Integer/Float num1 The first number for arithmetic operations 5 or 5.0
Integer/Float num2 The second number for arithmetic operations 3 or 3.0
Float result Stores the result of the arithmetic operations 8.0 or 2.5

In this project, you’ll see how arithmetic operators interact with different data types such as integers and floats.

Syntax Table for Basic Arithmetic Calculator in MicroPython:

Operation Syntax Example
Addition result = num1 + num2 result = 5 + 3
Subtraction result = num1 – num2 result = 5 – 3
Multiplication result = num1 * num2 result = 5 * 3
Division result = num1 / num2 result = 5 / 2

Each of these operations will be performed by the calculator, and the result will be printed to the console.

Required Components:

  • ESP32 or ESP8266 (For running the MicroPython code)
  • Computer (For writing and uploading the MicroPython script)

Since this project focuses on arithmetic operations and does not involve external hardware, no additional components are needed.

Circuit Diagram:

(No circuit diagram is required as this project is purely programming-based.)

Circuit Connection Table:

(No circuit connections are needed for this project.)

Warnings:

  • Division by zero is not allowed and will result in a runtime error. Ensure that you handle this case properly in the code.

Installing MicroPython and Libraries (If Needed):

Install MicroPython on ESP32/ESP8266: If you haven’t installed MicroPython on your ESP32 or ESP8266, follow these steps:
esptool.py –chip esp32 erase_flash

esptool.py –chip esp32 write_flash -z 0x1000 esp32-20210902-v1.17.bin

  1. No Additional Libraries Needed: The built-in operators in MicroPython are enough to perform basic arithmetic operations.

Writing the MicroPython Code for Basic Arithmetic Calculator:

Here’s the code that performs addition, subtraction, multiplication, and division using input numbers:

# Function for basic arithmetic calculator

def basic_calculator(num1, num2):

    # Addition

    result = num1 + num2

    print(“Addition: “, num1, “+”, num2, “=”, result)

    

    # Subtraction

    result = num1 – num2

    print(“Subtraction: “, num1, “-“, num2, “=”, result)

    

    # Multiplication

    result = num1 * num2

    print(“Multiplication: “, num1, “*”, num2, “=”, result)

    

    # Division (handling division by zero)

    if num2 != 0:

        result = num1 / num2

        print(“Division: “, num1, “/”, num2, “=”, result)

    else:

        print(“Error: Division by zero is not allowed.”)

 

# Test the calculator with example values

num1 = float(input(“Enter the first number: “))

num2 = float(input(“Enter the second number: “))

basic_calculator(num1, num2)

 

Explanation of the Code:

  • The function basic_calculator(num1, num2) performs the four arithmetic operations using the input values num1 and num2.
  • The addition, subtraction, and multiplication results are printed directly.
  • Division includes a check to ensure that division by zero does not occur. If num2 is zero, an error message is displayed.
  • The input function allows the user to provide two numbers (which are converted to floats), making this calculator dynamic for various numbers.

Running the Code and Checking the Output:

  1. Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.
  2. Enter the values for num1 and num2 when prompted.

Observe the results printed on the serial monitor, displaying the outcomes of the arithmetic operations:

Enter the first number: 5

Enter the second number: 3

Addition:  5.0 + 3.0 = 8.0

Subtraction:  5.0 – 3.0 = 2.0

Multiplication:  5.0 * 3.0 = 15.0

Division:  5.0 / 3.0 = 1.6666666666666667

Expanding the Project:

  • Add more operations: You can add other operations like modulus (%) or exponentiation (**) to extend the calculator.
  • Handle invalid input: Add input validation to ensure the user enters numeric values only.
  • Create an interactive loop: Allow the user to continuously enter numbers and perform operations until they choose to exit.

Common Problems and Solutions:

  1. Problem: Division by zero causes the program to crash.
    • Solution: The program already includes a check for division by zero, which ensures the user is notified when they attempt to divide by zero. Always add such checks in real-world programs.
  2. Problem: Invalid input results in an error.
    • Solution: You can wrap the input section in a try-except block to handle invalid input (such as non-numeric values). Use try: float(input()) to safely parse the input.
  3. Problem: Floating-point precision issues.
    • Solution: Floating-point arithmetic can sometimes lead to precision errors. Use round() if necessary to format the result to a specified number of decimal places.

FAQ:

Q: Can I extend the calculator to handle other mathematical operations?
A: Yes, you can easily add more operations like modulus (%) or exponentiation (**). Simply extend the basic_calculator function to include more operators.

Q: How do I handle invalid inputs (like text) in the calculator?
A: You can use try-except blocks to catch errors when non-numeric values are entered, ensuring the program doesn’t crash.

Q: Why does division by zero cause an error?
A: Division by zero is mathematically undefined, and MicroPython (like other programming languages) will raise an error when attempting this. Always check for division by zero before performing the division.

Conclusion:

In this project, you successfully built a Basic Arithmetic Calculator in MicroPython for ESP32 and ESP8266 that performs addition, subtraction, multiplication, and division. By using arithmetic operators and handling division by zero, you gained hands-on experience with fundamental mathematical operations in MicroPython. This project can be expanded to include more complex calculations, providing a strong foundation for future programming projects.

Local and Global Variable Interaction in MicroPython for ESP32 and ESP8266

In this project, you will explore the interaction between Local and Global Variable Interaction in MicroPython for ESP32 and ESP8266. This project demonstrates the difference between variables declared globally (accessible throughout the entire program) and variables declared locally within a function (only accessible within that function). Understanding variable scope is essential for controlling data flow in programs, and this simple project will guide you through the key concepts with clear examples.

Data Types and Variable Table for Local and Global Variable Interaction:

Data Type Variable Name Scope Description Example Value
Integer global_var Global Accessible throughout the entire program 10
Integer local_var Local Accessible only within a function 5

In this project, you’ll see how global variables are available both inside and outside of functions, whereas local variables are only accessible within the function in which they are defined.

Syntax Table for Local and Global Variable Interaction in MicroPython:

Function Syntax Example
Declare a global variable global variable_name global global_var
Access local variable in function def function_name(): def my_function(): local_var = 5
Modify global variable in function global variable_name inside a function global global_var

Required Components:

  • ESP32 or ESP8266 (For running the MicroPython code)
  • Computer (For writing and uploading the MicroPython script)

This project does not require any external components like LEDs or sensors, as it focuses on understanding the programming concept of variable scope.

Circuit Diagram:

(No circuit diagram is needed as this project is focused on programming.)

Circuit Connection Table:

(No circuit connections are required for this project.)

Warnings:

  • Ensure that global variables are explicitly declared inside functions using the global keyword to avoid confusion with local variables.
  • Be careful when modifying global variables inside functions, as changes will persist across the entire program.

Installing MicroPython and Libraries:

Install MicroPython on ESP32/ESP8266: If you haven’t already installed MicroPython on your ESP32 or ESP8266, follow these steps:
esptool.py –chip esp32 erase_flash

esptool.py –chip esp32 write_flash -z 0x1000 esp32-20210902-v1.17.bin

  1. No Additional Libraries Needed:
    The built-in functions of MicroPython are enough to demonstrate the interaction between local and global variables.

Writing the MicroPython Code for Local and Global Variable Interaction:

Here’s a simple example of how local and global variables interact in MicroPython:

# Declare a global variable

global_var = 10

def my_function():

    # Declare a local variable

    local_var = 5

    # Access and modify the global variable inside the function

    global global_var

    global_var += 1

    

    # Print the local variable (only accessible within this function)

    print(“Inside function – Local variable:”, local_var)

    

    # Print the modified global variable

    print(“Inside function – Global variable:”, global_var)

 

# Call the function

my_function()

 

# Print the global variable outside the function

print(“Outside function – Global variable:”, global_var)

 

# Trying to access the local variable outside its function will cause an error

# print(“Outside function – Local variable:”, local_var)  # This will cause an error

 

Explanation of the Code:

  • The global variable global_var is declared outside the function and is available throughout the entire program. Inside the function, it is modified using the global keyword to indicate that we are accessing the global version, not a new local variable.
  • The local variable local_var is declared within the function and can only be accessed inside the function. Attempting to access it outside the function will result in an error.
  • When you run this code, you’ll see that the global variable global_var is modified both inside and outside the function, while the local variable local_var only exists within the function.

Running the Code and Checking the Output:

  1. Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.

Monitor the serial output, and you’ll see the following printed messages:
Inside function – Local variable: 5

Inside function – Global variable: 11

Outside function – Global variable: 11

  1. Important Note:
    If you uncomment the last line (print(“Outside function – Local variable:”, local_var)), the program will produce an error because the local variable local_var is not accessible outside the function.

Expanding the Project:

  • Modify multiple global variables: Add more global variables to see how they interact with local variables.
  • Pass variables to functions: Try passing local variables as arguments to functions and see how their values change within different scopes.
  • Multiple functions: Create multiple functions, each modifying the same global variable, and observe how its value changes across the program.

Common Problems and Solutions:

  1. Problem: Modifying a global variable inside a function without declaring it as global results in unexpected behavior.
    • Solution: Always use the global keyword to indicate that you are modifying the global variable, not creating a new local variable.
  2. Problem: Trying to access a local variable outside its function results in an error.
    • Solution: Local variables are restricted to the function they are defined in. Declare variables globally if they need to be accessed throughout the program.

FAQ:

Q: What’s the difference between local and global variables?
A: Global variables are accessible from anywhere in the program, while local variables are only accessible within the function in which they are defined.

Q: Why do I need to declare a global variable inside a function using the global keyword?
A: Without using the global keyword, Python will assume you are creating a new local variable inside the function, which won’t modify the global version.

Q: Can I use the same variable name for both local and global variables?
A: Yes, but it can cause confusion. Inside the function, the local variable will take precedence unless you explicitly use the global keyword to access the global variable.

Conclusion:

This project demonstrated how to interact with local and global variables in MicroPython for ESP32 and ESP8266. By understanding how variable scope works, you can control how data is accessed and modified throughout your program. This is a foundational concept for writing efficient and organized code in MicroPython or any programming language.

Simple Counter Using Global Variable in MicroPython for ESP32 and ESP8266

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:

  1. 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

  1. 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:

  1. 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:

  1. 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.
  2. 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.
  3. 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.

LED Control with Boolean in MicroPython for ESP32 and ESP8266

In this simple project, you will learn how to control an LED and print messages based on a LED Control with Boolean in MicroPython for ESP32 and ESP8266. By setting a boolean value (True or False), you will determine whether the LED should be ON or OFF and display a corresponding message on the serial monitor. This project helps you understand how to work with boolean variables, strings, and conditional statements in MicroPython, making it ideal for beginners.

Data Types and Variable Table for LED Control with Boolean in MicroPython:

Data Type Variable Name Description Example Value
Boolean led_status Stores the state of the LED (ON or OFF) True or False
String message Displays the status message based on led_status “LED is ON” or “LED is OFF”

Syntax Table for LED Control with Boolean in MicroPython for ESP32 and ESP8266:

Function Syntax Example
Define a boolean led_status = True led_status = False
Set GPIO output pin.value() pin.value(1) for HIGH (LED ON)
Print string print(“message”) print(“LED is ON”)
Conditional check if condition: if led_status == True:

Required Components:

  • ESP32 or ESP8266
  • 1 LED (Any color)
  • 1 Resistor (220Ω) (To limit current to the LED)
  • Breadboard
  • Jumper wires

Circuit Diagram:

           ESP32/ESP8266

           ————

           GPIO5   ——> Resistor ——> LED Anode (+)

           GND     ————————> LED Cathode (-)

 

Circuit Connection Table:

Component Connection ESP32/ESP8266 Pin Explanation
LED Anode Connect through a resistor to GPIO5 Controls the ON/OFF state of the LED based on the GPIO output.
LED Cathode Connect to GND GND on ESP32/ESP8266 Completes the circuit for the LED.

Warnings:

  • Ensure that the resistor is connected in series with the LED to prevent damage to the LED.
  • Double-check that the LED’s anode (positive) and cathode (negative) are connected correctly to avoid reverse polarity issues.

Circuit Analysis:

In this circuit, the LED is connected to GPIO5 of the ESP32 or ESP8266, with a 220Ω resistor limiting the current flowing through the LED. The GND is connected to the cathode of the LED. When the GPIO pin outputs HIGH (1), the LED will turn on, and when it outputs LOW (0), the LED will turn off.

Installing MicroPython and Libraries (If Needed):

  1. Install MicroPython on ESP32/ESP8266:
    • Ensure that you have MicroPython installed on your ESP32 or ESP8266. You can use esptool or Thonny for flashing the MicroPython firmware:

esptool.py –chip esp32 erase_flash

esptool.py –chip esp32 write_flash -z 0x1000 esp32-20210902-v1.17.bin

  1. No Additional Libraries Needed:
    The built-in machine module is all you need for controlling GPIO pins in MicroPython.

Writing the MicroPython Code to Control LED Based on Boolean Value:

import machine

import time

 

# Initialize the LED pin (GPIO5 in this case)

led_pin = machine.Pin(5, machine.Pin.OUT)

 

# Set the initial status of the LED (True means ON, False means OFF)

led_status = True

 

while True:

    # Turn the LED ON if led_status is True, OFF if False

    if led_status:

        led_pin.value(1)  # LED ON

        message = “LED is ON”

    else:

        led_pin.value(0)  # LED OFF

        message = “LED is OFF”

    

    # Print the status message

    print(message)

    

    # Toggle the led_status value (switch between ON and OFF)

    led_status = not led_status

    

    # Wait for 2 seconds before toggling again

    time.sleep(2)

 

Running the Code and Checking the Output:

  1. Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.

Open the serial monitor to observe the messages. The LED will toggle ON and OFF every 2 seconds, and the corresponding message will be printed:
LED is ON

LED is OFF

LED is ON

Expanding the Project:

  • Add a Button: Use a button to manually toggle the LED ON or OFF based on the button press.
  • Adjust Timing: Modify the delay to change how frequently the LED toggles.
  • Add Multiple LEDs: Control multiple LEDs by assigning a boolean variable for each, creating more complex lighting patterns.

Common Problems and Solutions:

  1. Problem: The LED does not turn ON or OFF.
    • Solution: Check that the LED is connected properly, with the correct polarity (anode to GPIO, cathode to GND). Ensure that the GPIO pin number is correctly assigned in the code.
  2. Problem: The LED blinks too fast or too slow.
    • Solution: Adjust the time.sleep() delay in the code to control the speed of the LED toggling.
  3. Problem: The LED is always ON or OFF.
    • Solution: Check the boolean logic in the code and ensure that led_status is toggling correctly with led_status = not led_status.

FAQ:

Q: Can I change the GPIO pin used to control the LED?
A: Yes, you can use any available GPIO pin. Just update the pin number in the code, such as led_pin = machine.Pin(pin_number, machine.Pin.OUT).

Q: How can I change the delay between the ON and OFF states of the LED?
A: You can modify the time.sleep(2) line to adjust the delay. For example, time.sleep(1) will toggle the LED every 1 second.

Q: Can I control more than one LED?
A: Yes, you can define multiple LED pins and boolean variables. Just add additional GPIO pins and control logic for each LED.

Conclusion:

This project demonstrated how to control an LED and display messages based on a boolean variable using MicroPython for ESP32 and ESP8266. By learning how to use conditional statements and work with boolean logic, you have taken the first step toward controlling hardware and making decisions based on program logic. This project can be easily expanded by adding more LEDs, buttons, or even integrating with sensors to trigger the LED states.

Storing Sensor Data in MicroPython for ESP32 and ESP8266

In this project, we will learn how to use Storing Sensor Data in MicroPython for ESP32 and ESP8266 to store sensor data from a DHT11 sensor. You will read the temperature and humidity values from the sensor and store them in variables using basic data types such as integers and floats. This beginner-friendly project demonstrates how to handle data types in MicroPython, use sensor readings, and display the data. Additionally, this project lays the foundation for more advanced IoT projects.

Data Types and Variable Table for Storing Sensor Data in MicroPython:

Data Type Variable Name Description Example Value
Integer temperature Stores the temperature reading from the sensor 25°C
Float humidity_float Stores the humidity reading as a float 60.5%

In this project, temperature will be stored as an integer, while humidity will be converted to and stored as a float to allow for greater precision.

Syntax Table for Storing Sensor Data in MicroPython for ESP32 and ESP8266:

Function Syntax Example
Initialize DHT11 sensor = dht.DHT11(machine.Pin(pin)) sensor = dht.DHT11(machine.Pin(4))
Trigger measurement sensor.measure() sensor.measure()
Read temperature sensor.temperature() temperature = sensor.temperature()
Read humidity sensor.humidity() humidity = sensor.humidity()
Convert to float float(value) humidity_float = float(humidity)

Required Components:

  • ESP32 or ESP8266 microcontroller
  • DHT11 sensor (Temperature and Humidity Sensor)
  • Jumper wires
  • Breadboard

Circuit Diagram:

          DHT11          ESP32/ESP8266

           ——-         ————

           VCC  ———-> 3.3V

           GND  ———-> GND

           DATA ———-> GPIO4 (Pin 4)

 

Circuit Connection Table:

DHT11 Pin Connection ESP32/ESP8266 Pin Explanation
VCC Connect to 3.3V 3.3V on ESP32/ESP8266 Provides power to the DHT11 sensor.
GND Connect to GND GND on ESP32/ESP8266 Connects the sensor to ground (GND).
DATA Connect to GPIO4 GPIO4 on ESP32/ESP8266 Sends temperature and humidity data to the ESP32/ESP8266 via GPIO4.

Warnings:

  • Ensure that the DHT11 sensor is connected to 3.3V and not 5V, as the ESP32/ESP8266 operates at 3.3V. Connecting the sensor to a higher voltage may damage the microcontroller.
  • Double-check the wiring before powering the circuit to avoid short circuits or incorrect sensor readings.

Circuit Analysis:

The DHT11 sensor provides temperature and humidity readings through its DATA pin, which is connected to GPIO4 of the ESP32/ESP8266. The sensor requires VCC (3.3V) and GND to operate. The ESP32/ESP8266 reads the sensor data through GPIO4 and stores the values in variables, which can then be displayed or further processed.

Installing MicroPython and Libraries:

  1. Install MicroPython on ESP32/ESP8266:
    • To run MicroPython, you first need to install the firmware on your ESP32 or ESP8266. You can use esptool or Thonny to install MicroPython:

esptool.py –chip esp32 erase_flash

esptool.py –chip esp32 write_flash -z 0x1000 esp32-20210902-v1.17.bin

  1. Install Required Libraries:
    • Use the built-in dht and machine modules. Import them into your MicroPython code:

import dht

import machine

Writing the MicroPython Code for Storing Sensor Data:

Here’s the code that reads the temperature and humidity data from the DHT11 sensor and stores it in variables:

import dht

import machine

import time

 

# Initialize the DHT11 sensor on GPIO4

sensor = dht.DHT11(machine.Pin(4))

 

while True:

    try:

        # Trigger measurement

        sensor.measure()

        

        # Store temperature as an integer

        temperature = sensor.temperature()

        

        # Store humidity, converting it to a float

        humidity = sensor.humidity()

        humidity_float = float(humidity)

        

        # Print the sensor data

        print(“Temperature:”, temperature, “°C”)

        print(“Humidity:”, humidity_float, “%”)

        

        # Delay for 2 seconds before next reading

        time.sleep(2)

    

    except OSError as e:

        print(“Failed to read from DHT sensor:”, e)

 

Running the Code and Checking the Output:

  1. Upload the code to your ESP32/ESP8266 using Thonny or another MicroPython IDE.

Open the serial monitor to see the sensor readings. The temperature and humidity values will be printed every 2 seconds:
Temperature: 25 °C

Humidity: 60.0 %

Expanding the Project:

  • Add a Display: You can add an OLED or LCD screen to display the temperature and humidity readings.
  • Data Logging: Store the sensor data in a text file on the ESP32/ESP8266 filesystem for later analysis.
  • Wi-Fi Integration: Expand the project to send temperature and humidity data to an online server via HTTP for IoT applications.

Common Problems and Solutions:

  1. Problem: The sensor readings are not appearing on the serial monitor.
    • Solution: Check the wiring, especially the connection between the DATA pin and the GPIO pin. Ensure you are using the correct GPIO pin in the code.
  2. Problem: OSError occurs when reading the sensor.
    • Solution: Ensure that the sensor is connected correctly and receiving power. You might also need to ensure the sensor is functioning properly.
  3. Problem: Incorrect or fluctuating sensor readings.
    • Solution: Add a delay between readings to give the sensor enough time to stabilize. DHT11 needs at least 2 seconds between readings.

FAQ:

Q: Can I use a different GPIO pin for the DHT11 sensor?
A: Yes, you can change the pin by connecting the DATA pin of the sensor to another available GPIO pin. Be sure to update the pin number in the code.

Q: How often can I take sensor readings?
A: The DHT11 sensor has a delay of 1-2 seconds between measurements to ensure accurate readings.

Q: How can I convert the temperature from Celsius to Fahrenheit?
A: You can convert the Celsius reading to Fahrenheit using this formula:

fahrenheit = (temperature * 9/5) + 32

Conclusion:

In this project, you successfully learned how to store sensor data from a DHT11 sensor using MicroPython on ESP32 and ESP8266. By reading temperature and humidity data, you explored the usage of integers and floats in MicroPython. This foundational project can be further expanded with displays, data logging, or by sending the data to the cloud for IoT applications. Understanding how to handle sensor data is a critical step in building more advanced projects with MicroPython and ESP32/ESP8266.