Real-World Examples

Learn how to use ESP32 GPIO Bridge with practical examples. From basic LED control to advanced sensor monitoring and servo control.

Basic I/O Operations

Beginner

Learn the fundamentals with digital input/output, analog reading, and basic GPIO control.

Hardware Required

  • • ESP32 development board
  • • LED with 220Ω resistor
  • • Push button
  • • Potentiometer (10kΩ)
  • • Breadboard and jumper wires

Wiring Connections

  • LED: GPIO 2 → LED anode → 220Ω resistor → LED cathode → GND
  • Button: GPIO 0 → Button pin 1, Button pin 2 → GND
  • Potentiometer: GPIO 34 → Potentiometer wiper, VCC → 3.3V, GND → GND
basic_io_example.py
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)
led_patterns_example.py (Knight Rider)
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})

LED Patterns & Effects

Intermediate

Create stunning visual effects with multiple LEDs using batch operations for synchronized control.

Knight Rider Effect: Classic scanner pattern
Chase Patterns: Multiple LED trails
Binary Counter: Display numbers in binary
Breathing Effect: PWM-based fading

Available Patterns

  • • Knight Rider / Cylon scanner
  • • Chase patterns with trails
  • • Wave patterns (build up/collapse)
  • • Alternating blink patterns
  • • Binary counter display
  • • Random sparkle effects
  • • Breathing effect with PWM

Servo Motor Control

Intermediate

Precise servo motor control with PWM, including smooth movements, preset positions, and synchronized multi-servo operations.

Servo Specifications

  • • 50Hz PWM frequency (standard servos)
  • • 1-2ms pulse width (0-180° range)
  • • 8-bit PWM resolution (0-255)
  • • Smooth angle transitions

Wiring Connections

  • Servo 1: Signal → GPIO 18, VCC → 5V, GND → GND
  • Servo 2: Signal → GPIO 19, VCC → 5V, GND → GND
  • Power: Use external 5V supply for multiple servos
pwm_servo_control.py
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)
sensor_monitoring.py
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")

Sensor Monitoring

Intermediate

Monitor multiple sensors simultaneously, log data, and create real-time monitoring dashboards.

Temperature Sensors: TMP36, DS18B20
Light Sensors: LDR, photoresistor
Motion Sensors: PIR, ultrasonic
Data Logging: JSON, CSV export

Sensor Types

  • • Analog sensors (potentiometer, LDR, TMP36)
  • • Digital sensors (button, switch, PIR)
  • • I2C sensors (accelerometer, gyroscope)
  • • Specialized sensors (ultrasonic, gas sensors)

Advanced Examples

Complex projects combining multiple features: I2C communication, EEPROM storage, and advanced control systems.

I2C Sensor Hub

Advanced

Connect multiple I2C sensors (accelerometer, gyroscope, magnetometer) and create a comprehensive sensor fusion system.

  • • Device scanning and detection
  • • Multi-sensor data fusion
  • • Real-time data processing
  • • Calibration and filtering

EEPROM Data Logger

Advanced

Store sensor data in EEPROM, implement circular buffers, and create persistent logging systems.

  • • Circular buffer implementation
  • • Data persistence across reboots
  • • Configuration storage
  • • Memory management

Arduino Arm Robot

Advanced

Control a multi-servo robotic arm with inverse kinematics, path planning, and real-time control.

  • • Multi-servo coordination
  • • Inverse kinematics
  • • Path planning algorithms
  • • Real-time control loops

DAC Waveform Generator

Intermediate

Generate various waveforms (sine, square, triangle, sawtooth) using the ESP32's DAC for audio and signal generation.

  • • Multiple waveform types
  • • Frequency control
  • • Amplitude modulation
  • • Audio tone generation

Ultrasonic Distance Meter

Intermediate

Measure distances using HC-SR04 ultrasonic sensor with visual indicators and proximity alerts.

  • • HC-SR04 sensor interface
  • • Visual zone indicators
  • • Proximity alarms
  • • Statistical analysis

Multi-Sensor Dashboard

Advanced

Create a comprehensive monitoring dashboard with multiple sensors, real-time display, and data visualization.

  • • Real-time sensor monitoring
  • • Data visualization
  • • Alert systems
  • • Historical data analysis

Ready to Build Your Own Projects?

Start with the basic examples and work your way up to advanced projects. All examples include complete code and wiring instructions.