Arduino and MicroPython a Sequence of Statements ESP32
In this section, we delve into using loops to repeat a block of instructions in your ESP32 projects based on specific conditions. Loops such as while and do…while are essential for executing repetitive tasks, such as monitoring sensor inputs or implementing continuous operations until a condition is met or no longer true.
What We Will Learn in This Section:
- How to use the while loop to repeat instructions while a condition is true.
- Implementing continuous operations, such as flashing an LED or monitoring sensor values.
- Understanding the do…while loop and its application when you need to ensure at least one execution before checking a condition.
Why Is This Lesson Important to You?
Understanding loops is fundamental in programming to automate tasks that require repetitive actions based on conditions. Whether you’re developing IoT applications or sensor monitoring systems, mastery of loops enhances efficiency and responsiveness in your ESP32 projects.
Components List:
- ESP32 Board
- LED
- Sensor/Potentiometer
- Resistors (if necessary)
- Jumper Wires
- Breadboard (optional, for easier connections)
Arduino and MicroPython for ESP32" is your go-to guide for mastering ESP32 projects with clear examples and practical code. For free reading, visit Mechatronics Lab and grab your copy here
Circuit Diagram (With Connection):

Connection format:
LED:
- Anode (long leg): Connect to GPIO 2 (or a designated GPIO pin) through a current-limiting resistor.
- Cathode (short leg): Connect to GND.
- LED:Anode (long leg): Connect to GPIO 2 (or a designated GPIO pin) through a current-limiting resistor.Cathode (short leg): Connect to GND.
Sensor/Potentiometer:
- One terminal: Connect to the 3.3V supply.
- Wiper (middle terminal): Connect to GPIO 34 (analog input pin).
- Other terminal: Connect to GND.
Sensor/Potentiometer:One terminal: Connect to the 3.3V supply.Wiper (middle terminal): Connect to GPIO 34 (analog input pin).Other terminal: Connect to GND.
Code Arduino:
const int sensorPin = 34; // analog input pin (change this to a valid ADC pin on ESP32)
const int LED_BUILTIN = 2; // built-in LED pin on ESP32 (adjust if needed)
void setup()
{
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT); // enable LED pin as output
}
void loop()
{
while(analogRead(sensorPin) > 1000) // Adjust threshold value if needed
{
blink(); // call a function to turn an LED on and off
Serial.print(" More Than 1000: ");
Serial.println(analogRead(sensorPin)); // Print the sensor value
}
Serial.println(analogRead(sensorPin)); // this is not executed until after
// the while loop finishes!!!
}
void blink()
{
digitalWrite(LED_BUILTIN, HIGH);
delay(100);
digitalWrite(LED_BUILTIN, LOW);
delay(100);
}
Here’s the explanation of the Arduino code:
1. Variable Declarations
const int sensorPin = 34; // analog input pin (change this to a valid ADC pin on ESP32)
const int LED_BUILTIN = 2; // built-in LED pin on ESP32 (adjust if needed)
const int sensorPin = 34;: Defines the pin number connected to the analog sensor. This pin reads the sensor’s analog value. The specific pin number may need to be adjusted based on your ESP32 board.
const int LED_BUILTIN = 2;: Defines the pin number for the built-in LED. This pin controls the LED’s state.
2. Setup Function
void setup()
{
Serial.begin(9600);
pinMode(LED_BUILTIN, OUTPUT); // enable LED pin as output
}
Serial.begin(9600);: Initializes serial communication at a baud rate of 9600 bps for debugging.
pinMode(LED_BUILTIN, OUTPUT);: Configures the LED pin as an output to control the LED.
3. Loop Function
void loop()
{
while(analogRead(sensorPin) > 1000) // Adjust threshold value if needed
{
blink(); // call a function to turn an LED on and off
Serial.print(" More Than 1000: ");
Serial.println(analogRead(sensorPin)); // Print the sensor value
}
Serial.println(analogRead(sensorPin)); // this is not executed until after
// the while loop finishes!!!
}
while(analogRead(sensorPin) > 1000): Continuously reads the analog value from the sensor pin and checks if it is greater than 1000. Adjust the threshold value if necessary based on your sensor’s range.
blink();: Calls the blink() function to toggle the LED on and off.
Serial.print(“ More Than 1000: “);: Prints a message to indicate the value exceeds the threshold.
Serial.println(analogRead(sensorPin));: Prints the current sensor value to the Serial Monitor.
Serial.println(analogRead(sensorPin));: Once the while loop exits (sensor value is no longer greater than 1000), prints the sensor value again.
4. Blink Function
void blink()
{
digitalWrite(LED_BUILTIN, HIGH);
delay(100);
digitalWrite(LED_BUILTIN, LOW);
delay(100);
}
digitalWrite(LED_BUILTIN, HIGH);: Turns the LED on.
delay(100);: Waits for 100 milliseconds.
digitalWrite(LED_BUILTIN, LOW);: Turns the LED off.
delay(100);: Waits for another 100 milliseconds.
Code MicroPython:
from machine import Pin, ADC
import time
sensorPin = ADC(Pin(34)) # Analog input pin (change this to a valid ADC pin on ESP32)
sensorPin.width(ADC.WIDTH_12BIT) # Set the width of the ADC to 12 bits (0-4095)
sensorPin.atten(ADC.ATTN_11DB) # Set the attenuation to measure up to 3.3V
LED_BUILTIN = Pin(2, Pin.OUT) # Built-in LED pin on ESP32 (adjust if needed)
def setup():
print("Setup complete") # Initialization message
def loop():
while sensorPin.read() > 1000: # Adjust threshold value if needed
blink() # Call a function to turn an LED on and off
print("More Than 1000: ", sensorPin.read()) # Print the sensor value
print(sensorPin.read()) # This is not executed until after the while loop finishes!!!
def blink():
LED_BUILTIN.value(1)
time.sleep(0.1)
LED_BUILTIN.value(0)
time.sleep(0.1)
setup()
while True:
loop()
time.sleep(1) # Small delay to prevent overloading the CPU
Here's the explanation of the MicroPython code:
1. Import Statements
from machine import Pin, ADC
import time
from machine import Pin, ADC: Imports the Pin and ADC classes from the machine module to work with GPIO and Analog-to-Digital Conversion (ADC) pins.
import time: Imports the time module for delays.
2. Sensor and LED Pin Initialization
sensorPin = ADC(Pin(34)) # Analog input pin (change this to a valid ADC pin on ESP32)
sensorPin.width(ADC.WIDTH_12BIT) # Set the width of the ADC to 12 bits (0-4095)
sensorPin.atten(ADC.ATTN_11DB) # Set the attenuation to measure up to 3.3V
LED_BUILTIN = Pin(2, Pin.OUT) # Built-in LED pin on ESP32 (adjust if needed)
sensorPin = ADC(Pin(34)): Initializes pin 34 as an ADC input for reading analog signals. The ESP32 has specific pins that support ADC, and pin 34 is commonly used.
sensorPin.width(ADC.WIDTH_12BIT): Sets the ADC resolution to 12 bits, meaning the ADC values will range from 0 to 4095.
sensorPin.atten(ADC.ATTN_11DB): Sets the attenuation to allow the ADC to measure up to 3.3V.
LED_BUILTIN = Pin(2, Pin.OUT): Initializes pin 2 as an output for controlling the built-in LED on the ESP32.
3. Setup Function
def setup():
print("Setup complete") # Initialization message
def setup():: Defines the setup function, which is called once at the beginning to print a setup message.
4. Loop Function
def loop():
while sensorPin.read() > 1000: # Adjust threshold value if needed
blink() # Call a function to turn an LED on and off
print("More Than 1000: ", sensorPin.read()) # Print the sensor value
print(sensorPin.read()) # This is not executed until after the while loop finishes!!!
def loop():: Defines the loop function, which runs continuously.
while sensorPin.read() > 1000:: Continuously reads the sensor value. If the value is greater than 1000, it enters the loop to blink the LED.
blink(): Calls the blink function to turn the LED on and off.
print("More Than 1000: ", sensorPin.read()): Prints the sensor value while it's greater than 1000.
print(sensorPin.read()): This line prints the sensor value after the while loop finishes. It will only execute when the sensor value is no longer greater than 1000.
5. Blink Function
def blink():
LED_BUILTIN.value(1)
time.sleep(0.1)
LED_BUILTIN.value(0)
time.sleep(0.1)
def blink():: Defines a function to blink the LED.
LED_BUILTIN.value(1): Turns the LED on.
time.sleep(0.1): Waits for 100 milliseconds.
LED_BUILTIN.value(0): Turns the LED off.
time.sleep(0.1): Waits for another 100 milliseconds.
6. Running the Code
setup()
while True:
loop()
time.sleep(1) # Small delay to prevent overloading the CPU
setup(): Calls the setup function to print the initialization message.
while True:: Starts an infinite loop to continuously call the loop function.
time.sleep(1): Adds a small delay to avoid excessive CPU usage.
Summary:
Mastering loops such as while and do...while allows you to automate repetitive tasks efficiently in ESP32 programming. These constructs are vital for creating responsive applications that react to changing conditions or sensor inputs, enhancing the functionality and versatility of your ESP32 projects.
Understanding how to structure and utilize loops effectively empowers you to implement sophisticated behaviors and automation in your IoT and embedded systems applications.