Learn how to use ESP32 GPIO Bridge with practical examples. From basic LED control to advanced sensor monitoring and servo control.
Learn the fundamentals with digital input/output, analog reading, and basic GPIO control.
from esp32_gpio_bridge import ESP32GPIO, find_esp32_port
import time
# Auto-detect ESP32 port
port = find_esp32_port()
with ESP32GPIO(port) as esp:
print(f"Firmware version: {esp.get_version()}")
# Digital output - LED control
led_pin = 2
esp.set_pin_mode(led_pin, "OUT")
# Blink LED 5 times
for i in range(5):
esp.digital_write(led_pin, 1) # LED ON
time.sleep(0.5)
esp.digital_write(led_pin, 0) # LED OFF
time.sleep(0.5)
# Digital input - Button reading
button_pin = 0
esp.set_pin_mode(button_pin, "IN_PULLUP")
for i in range(5):
button_state = esp.digital_read(button_pin)
print(f"Button: {'PRESSED' if button_state == 0 else 'RELEASED'}")
time.sleep(0.5)
# Analog input - Potentiometer
pot_pin = 34
for i in range(10):
raw_value = esp.analog_read(pot_pin)
voltage = (raw_value / 4095.0) * 3.3
print(f"Potentiometer: {voltage:.2f}V")
time.sleep(0.5)
from esp32_gpio_bridge import ESP32GPIO, find_esp32_port
import time
# LED configuration
LED_PINS = [2, 4, 5, 12, 13, 14, 15, 16]
def knight_rider(esp, pins, cycles=3):
"""Classic Knight Rider / Cylon scanner effect."""
for cycle in range(cycles):
# Sweep forward
for i in range(len(pins)):
states = {pin: (1 if idx == i else 0)
for idx, pin in enumerate(pins)}
esp.batch_digital_write(states)
time.sleep(0.05)
# Sweep backward
for i in range(len(pins) - 2, 0, -1):
states = {pin: (1 if idx == i else 0)
for idx, pin in enumerate(pins)}
esp.batch_digital_write(states)
time.sleep(0.05)
with ESP32GPIO(find_esp32_port()) as esp:
# Configure all LEDs as outputs
for pin in LED_PINS:
esp.set_pin_mode(pin, "OUT")
# Run Knight Rider pattern
knight_rider(esp, LED_PINS, cycles=5)
# Turn all LEDs off
esp.batch_digital_write({pin: 0 for pin in LED_PINS})
Create stunning visual effects with multiple LEDs using batch operations for synchronized control.
Precise servo motor control with PWM, including smooth movements, preset positions, and synchronized multi-servo operations.
from esp32_gpio_bridge import ESP32GPIO, find_esp32_port
import time
# Servo configuration
SERVO_PINS = {'servo1': 18, 'servo2': 19}
SERVO_FREQ = 50 # 50Hz for standard servos
def angle_to_duty(angle):
"""Convert angle (0-180) to PWM duty cycle."""
if angle < 0: angle = 0
elif angle > 180: angle = 180
return int(26 + (angle / 180.0) * 102) # 26-128 range
def smooth_move(esp, pin, start_angle, end_angle, duration=1.0):
"""Smoothly move servo from start to end angle."""
steps = 20
delay = duration / steps
for i in range(steps + 1):
progress = i / steps
angle = start_angle + (end_angle - start_angle) * progress
duty = angle_to_duty(angle)
esp.pwm_write(pin, duty)
time.sleep(delay)
with ESP32GPIO(find_esp32_port()) as esp:
# Initialize servo with PWM
servo_pin = SERVO_PINS['servo1']
channel = esp.pwm_init(servo_pin, frequency=SERVO_FREQ, resolution=8)
# Center servo
esp.pwm_write(servo_pin, angle_to_duty(90))
time.sleep(1)
# Sweep demo
for i in range(3):
smooth_move(esp, servo_pin, 0, 180, duration=1.5)
smooth_move(esp, servo_pin, 180, 0, duration=1.5)
# Preset positions
positions = [0, 45, 90, 135, 180, 90]
for angle in positions:
smooth_move(esp, servo_pin, 90, angle, duration=0.8)
time.sleep(1)
# Stop PWM
esp.pwm_stop(servo_pin)
from esp32_gpio_bridge import ESP32GPIO, find_esp32_port
import time
import json
def read_temperature_sensor(esp, pin):
"""Read TMP36 temperature sensor."""
raw_value = esp.analog_read(pin)
voltage = (raw_value / 4095.0) * 3.3
# TMP36: 10mV/°C, 0.5V offset at 0°C
temperature = (voltage - 0.5) * 100
return temperature
def read_light_sensor(esp, pin):
"""Read light-dependent resistor (LDR)."""
raw_value = esp.analog_read(pin)
voltage = (raw_value / 4095.0) * 3.3
# Convert to percentage (higher voltage = more light)
percentage = (voltage / 3.3) * 100
return percentage
def monitor_sensors(esp, duration=60):
"""Monitor multiple sensors and log data."""
sensors = {
'temperature': 34, # TMP36 on GPIO 34
'light': 35, # LDR on GPIO 35
'potentiometer': 36 # Potentiometer on GPIO 36
}
data_log = []
start_time = time.time()
while time.time() - start_time < duration:
timestamp = time.time() - start_time
readings = {'timestamp': timestamp}
# Read temperature
readings['temperature'] = read_temperature_sensor(esp, sensors['temperature'])
# Read light level
readings['light'] = read_light_sensor(esp, sensors['light'])
# Read potentiometer
pot_value = esp.analog_read(sensors['potentiometer'])
readings['potentiometer'] = (pot_value / 4095.0) * 100
data_log.append(readings)
# Display readings
print(f"T: {readings['temperature']:.1f}°C, "
f"L: {readings['light']:.1f}%, "
f"P: {readings['potentiometer']:.1f}%")
time.sleep(1)
# Save data to file
with open('sensor_data.json', 'w') as f:
json.dump(data_log, f, indent=2)
return data_log
with ESP32GPIO(find_esp32_port()) as esp:
print("Starting sensor monitoring...")
data = monitor_sensors(esp, duration=30)
print(f"Collected {len(data)} data points")
Monitor multiple sensors simultaneously, log data, and create real-time monitoring dashboards.
Complex projects combining multiple features: I2C communication, EEPROM storage, and advanced control systems.
Connect multiple I2C sensors (accelerometer, gyroscope, magnetometer) and create a comprehensive sensor fusion system.
Store sensor data in EEPROM, implement circular buffers, and create persistent logging systems.
Control a multi-servo robotic arm with inverse kinematics, path planning, and real-time control.
Generate various waveforms (sine, square, triangle, sawtooth) using the ESP32's DAC for audio and signal generation.
Measure distances using HC-SR04 ultrasonic sensor with visual indicators and proximity alerts.
Create a comprehensive monitoring dashboard with multiple sensors, real-time display, and data visualization.
Start with the basic examples and work your way up to advanced projects. All examples include complete code and wiring instructions.