Ultrasonic Distance Sensor

This project is a Distance Sensor using an ESP32, MicroPython, an ultrasonic sensor, and an OLED display. It measures the distance to nearby objects in real-time and displays the distance in inches on the screen. Perfect for students, this project demonstrates sensor integration, data processing, and real-time feedback.

from machine import Pin, I2C
import ssd1306
import time

# Setup Ultrasonic sensor pins
trig = Pin(5, Pin.OUT)
echo = Pin(18, Pin.IN)

# Setup OLED display
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)

def measure_distance():
    # Send a 10us pulse to trigger the ultrasonic sensor
    trig.off()
    time.sleep_us(2)
    trig.on()
    time.sleep_us(10)
    trig.off()

    # Wait for the echo to start
    pulse_start = 0
    pulse_end = 0

    # Measure the start time
    timeout_start = time.ticks_us()
    while echo.value() == 0:
        pulse_start = time.ticks_us()
        if time.ticks_diff(pulse_start, timeout_start) > 10000:  # Timeout after 10ms
            print("Echo signal not received.")
            return None

    # Measure the end time
    timeout_end = time.ticks_us()
    while echo.value() == 1:
        pulse_end = time.ticks_us()
        if time.ticks_diff(pulse_end, timeout_end) > 10000:  # Timeout after 10ms
            print("Echo signal too long.")
            return None

    # Calculate pulse duration
    pulse_duration = time.ticks_diff(pulse_end, pulse_start)
    
    # Calculate distance in cm, then convert to inches
    distance_cm = (pulse_duration / 2) / 29.1
    distance_in = distance_cm * 0.393701
    return distance_in

while True:
    # Get the measured distance in inches
    distance = measure_distance()
    
    if distance is None:
        print("Error: Distance not measured.")
        oled.fill(0)
        oled.text("Distance Sensor", 0, 0)
        oled.text("No signal!", 0, 20)
        oled.show()
    else:
        print("Distance: {:.2f} in".format(distance))
        # Clear the OLED display
        oled.fill(0)
        
        # Display the distance in inches on the OLED
        oled.text("Distance Sensor", 0, 0)
        oled.text("Distance: {:.2f} in".format(distance), 0, 20)  # Display distance in inches
        
        # If the object is too close, display a warning
        if distance < 4:  # Warning if distance is less than 4 inches
            oled.text("Warning: Too Close!", 0, 40)
        
        # Show the updated display
        oled.show()
    
    # Delay before taking the next measurement
    time.sleep(1)

Leave a Comment

Your email address will not be published. Required fields are marked *