Build an intelligent distance measurement system using Raspberry Pi Pico and HC-SR04 ultrasonic sensor. Measure distances from 2cm to 400cm with real-time display on a 16x2 LCD screen and visual LED indicators. Perfect for learning sensor interfacing and distance measurement without buying physical components - test everything in Wokwi simulator first!
Key Features
Real-time distance measurement (displays in cm and inches)
Range detection: 2cm to 400cm (0.8" to 157")
Visual LED indicators: Green (Far), Yellow (Medium), Red (Close)
Continuous LCD display updates every 500ms
HC-SR04 sensor simulation in Wokwi (no hardware needed to start)
Buzzer alerts for objects too close (optional)
Error handling for out-of-range readings
Customizable distance thresholds for alerts
Components Required
Diagram.json:
{
"version": 1,
"author": "Ultrasonic Distance Sensor",
"editor": "wokwi",
"parts": [
{ "type": "wokwi-pi-pico", "id": "pico", "top": 0, "left": 0, "attrs": {} },
{
"type": "wokwi-hc-sr04",
"id": "ultrasonic1",
"top": -100,
"left": 250,
"attrs": { "distance": "100" }
},
{ "type": "wokwi-lcd1602", "id": "lcd1", "top": 100, "left": 250, "attrs": { "pins": "i2c" } },
{
"type": "wokwi-led",
"id": "led_red",
"top": -80,
"left": 450,
"attrs": { "color": "red", "label": "Red" }
},
{
"type": "wokwi-led",
"id": "led_green",
"top": -20,
"left": 450,
"attrs": { "color": "green", "label": "Green" }
},
{
"type": "wokwi-led",
"id": "led_blue",
"top": 40,
"left": 450,
"attrs": { "color": "blue", "label": "Blue" }
},
{ "type": "wokwi-buzzer", "id": "bz1", "top": 280.8, "left": 289.8, "attrs": {} },
{
"type": "wokwi-resistor",
"id": "r1",
"top": -80,
"left": 500,
"rotate": 90,
"attrs": { "value": "220" }
},
{
"type": "wokwi-resistor",
"id": "r2",
"top": -20,
"left": 500,
"rotate": 90,
"attrs": { "value": "220" }
},
{
"type": "wokwi-resistor",
"id": "r3",
"top": 40,
"left": 500,
"rotate": 90,
"attrs": { "value": "220" }
}
],
"connections": [
[ "pico:GP0", "lcd1:SDA", "green", [ "h0" ] ],
[ "pico:GP1", "lcd1:SCL", "blue", [ "h0" ] ],
[ "pico:3V3", "lcd1:VCC", "red", [ "h0" ] ],
[ "pico:GND.1", "lcd1:GND", "black", [ "h0" ] ],
[ "pico:GP2", "ultrasonic1:TRIG", "yellow", [ "h0" ] ],
[ "pico:GP3", "ultrasonic1:ECHO", "orange", [ "h0" ] ],
[ "pico:3V3", "ultrasonic1:VCC", "red", [ "h0" ] ],
[ "pico:GND.2", "ultrasonic1:GND", "black", [ "h0" ] ],
[ "pico:GP13", "r1:1", "red", [ "h0" ] ],
[ "r1:2", "led_red:A", "red", [ "v0" ] ],
[ "led_red:C", "pico:GND.3", "black", [ "h0" ] ],
[ "pico:GP14", "r2:1", "green", [ "h0" ] ],
[ "r2:2", "led_green:A", "green", [ "v0" ] ],
[ "led_green:C", "pico:GND.3", "black", [ "h0" ] ],
[ "pico:GP15", "r3:1", "blue", [ "h0" ] ],
[ "r3:2", "led_blue:A", "blue", [ "v0" ] ],
[ "led_blue:C", "pico:GND.3", "black", [ "h0" ] ],
[ "pico:GP16", "bz1:1", "purple", [ "h0" ] ],
[ "bz1:2", "pico:GND.4", "black", [ "h0" ] ]
],
"dependencies": {}
}
Raspberry Pi Pico (simulated in Wokwi)
HC-SR04 Ultrasonic Distance Sensor
16x2 LCD Display (I2C connection)
Green LED (object far - safe zone)
Yellow LED (object medium distance - caution)
Red LED (object close - warning)
Buzzer (optional - for proximity alert)
3x 220Ω Resistors (for LEDs)
Breadboard and jumper wires
MicroPython firmware on Pico
Circuit Connections
HC-SR04 Ultrasonic Sensor:
VCC → 5V (VBUS Pin 40)
GND → GND
TRIG → GPIO14 (Trigger pin)
ECHO → GPIO15 (Echo pin)
LCD Display (I2C):
SDA → GPIO0 (I2C0 SDA)
SCL → GPIO1 (I2C0 SCL)
VCC → 5V (VBUS)
GND → GND
LED Indicators:
Code:
main.py:
"""
ULTRASONIC DISTANCE SENSOR WITH RASPBERRY PI PICO
==================================================
Hardware:
- Raspberry Pi Pico
- HC-SR04 Ultrasonic Sensor
- 16x2 I2C LCD Display
- RGB LED (Common Cathode)
- Active Buzzer
- 3x 220Ω Resistors
Features:
- Real-time distance measurement (2-400 cm)
- LCD display showing distance in cm and inches
- RGB LED color changes based on distance
- Buzzer alerts for proximity
- Serial monitor data logging
- Auto-ranging display
Author: IoT Project Tutorial
Date: 2024
Version: 1.0
"""
from machine import Pin, I2C, PWM
import utime
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
# ============================================
# PIN CONFIGURATION
# ============================================
TRIG_PIN = 2 # Ultrasonic trigger pin
ECHO_PIN = 3 # Ultrasonic echo pin
RGB_RED = 13 # RGB LED Red pin
RGB_GREEN = 14 # RGB LED Green pin
RGB_BLUE = 15 # RGB LED Blue pin
BUZZER_PIN = 16 # Buzzer pin
LCD_SDA = 0 # I2C SDA pin
LCD_SCL = 1 # I2C SCL pin
# ============================================
# DISTANCE THRESHOLDS (in cm)
# ============================================
VERY_CLOSE = 10 # < 10cm - Critical proximity
CLOSE = 30 # < 30cm - Warning zone
MEDIUM = 100 # < 100cm - Caution zone
FAR = 200 # < 200cm - Safe zone
# ============================================
# LCD CONFIGURATION
# ============================================
I2C_ADDR = 0x27 # I2C address (try 0x3F if this doesn't work)
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16
# ============================================
# INITIALIZE HARDWARE
# ============================================
# Ultrasonic sensor pins
trigger = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
# RGB LED pins (PWM for brightness control)
red_led = PWM(Pin(RGB_RED))
green_led = PWM(Pin(RGB_GREEN))
blue_led = PWM(Pin(RGB_BLUE))
# Set PWM frequency
red_led.freq(1000)
green_led.freq(1000)
blue_led.freq(1000)
# Buzzer pin
buzzer = Pin(BUZZER_PIN, Pin.OUT)
# I2C for LCD
i2c = I2C(0, sda=Pin(LCD_SDA), scl=Pin(LCD_SCL), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
# ============================================
# GLOBAL VARIABLES
# ============================================
distance_cm = 0
distance_inch = 0
measurement_count = 0
# ============================================
# FUNCTION: SET RGB LED COLOR
# ============================================
def set_rgb_color(r, g, b):
"""
Set RGB LED color using PWM
Parameters: r, g, b (0-65535 for PWM duty cycle)
"""
red_led.duty_u16(r)
green_led.duty_u16(g)
blue_led.duty_u16(b)
# ============================================
# FUNCTION: PLAY BUZZER PATTERN
# ============================================
def play_buzzer(beeps, duration=100):
"""
Play buzzer alert
Parameters:
beeps: number of beeps
duration: beep duration in ms
"""
for i in range(beeps):
buzzer.value(1)
utime.sleep_ms(duration)
buzzer.value(0)
utime.sleep_ms(duration)
# ============================================
# FUNCTION: MEASURE DISTANCE
# ============================================
def measure_distance():
"""
Measure distance using HC-SR04 ultrasonic sensor
Returns: distance in centimeters
"""
# Ensure trigger is low
trigger.low()
utime.sleep_us(2)
# Send 10us pulse to trigger
trigger.high()
utime.sleep_us(10)
trigger.low()
# Wait for echo to go high (start of pulse)
timeout_start = utime.ticks_us()
while echo.value() == 0:
signal_off = utime.ticks_us()
# Timeout after 30ms
if utime.ticks_diff(signal_off, timeout_start) > 30000:
return -1 # Timeout error
# Measure pulse width (echo high time)
timeout_start = utime.ticks_us()
while echo.value() == 1:
signal_on = utime.ticks_us()
# Timeout after 30ms
if utime.ticks_diff(signal_on, timeout_start) > 30000:
return -1 # Timeout error
# Calculate time difference
time_passed = utime.ticks_diff(signal_on, signal_off)
# Calculate distance in cm
# Speed of sound = 343 m/s = 0.0343 cm/us
# Distance = (Time * Speed) / 2 (round trip)
distance = (time_passed * 0.0343) / 2
return distance
# ============================================
# FUNCTION: UPDATE LCD DISPLAY
# ============================================
def update_lcd(distance_cm, distance_inch):
"""
Update LCD with distance measurements
"""
lcd.clear()
if distance_cm < 0:
# Error condition
lcd.putstr(" SENSOR ERROR ")
lcd.move_to(0, 1)
lcd.putstr(" Out of Range ")
elif distance_cm > 400:
# Out of range
lcd.putstr("Distance: OUT ")
lcd.move_to(0, 1)
lcd.putstr("OF RANGE (>4m) ")
else:
# Normal reading
lcd.putstr(f"Dist: {distance_cm:.1f} cm")
lcd.move_to(0, 1)
lcd.putstr(f" {distance_inch:.1f} in")
# ============================================
# FUNCTION: PROCESS DISTANCE ALERTS
# ============================================
def process_alerts(distance):
"""
Set LED color and buzzer based on distance
"""
if distance < 0:
# Error - Red LED, 3 beeps
set_rgb_color(65535, 0, 0)
play_buzzer(3, 50)
elif distance < VERY_CLOSE:
# Very close - Red LED, rapid beeping
set_rgb_color(65535, 0, 0) # Red
play_buzzer(3, 100)
print("⚠️ CRITICAL: Object very close!")
elif distance < CLOSE:
# Close - Orange LED, 2 beeps
set_rgb_color(65535, 16384, 0) # Orange
play_buzzer(2, 150)
print("⚠️ WARNING: Object close!")
elif distance < MEDIUM:
# Medium distance - Yellow LED, 1 beep
set_rgb_color(65535, 65535, 0) # Yellow
play_buzzer(1, 100)
print("⚠️ CAUTION: Object in range")
elif distance < FAR:
# Far - Green LED, no beep
set_rgb_color(0, 65535, 0) # Green
print("✅ SAFE: Object detected at safe distance")
else:
# Very far or no object - Blue LED
set_rgb_color(0, 0, 65535) # Blue
print("🔵 CLEAR: No object in range")
# ============================================
# FUNCTION: PRINT SERIAL DATA
# ============================================
def print_serial_data(distance_cm, distance_inch, count):
"""
Print formatted data to serial monitor
"""
print(f"#{count:04d} | {distance_cm:6.2f} cm | {distance_inch:6.2f} in | ", end="")
# ============================================
# STARTUP SEQUENCE
# ============================================
def startup_sequence():
"""
Display startup animation and test components
"""
print("\n╔═══════════════════════════════════════════════╗")
print("║ RASPBERRY PI PICO - ULTRASONIC DISTANCE ║")
print("║ MEASUREMENT SYSTEM ║")
print("╚═══════════════════════════════════════════════╝\n")
# Welcome message on LCD
lcd.clear()
lcd.putstr(" ULTRASONIC RNG ")
lcd.move_to(0, 1)
lcd.putstr(" SYSTEM v1.0 ")
# LED test sequence
print("🔧 Testing components...")
print(" - Red LED...", end="")
set_rgb_color(65535, 0, 0)
utime.sleep_ms(300)
print(" OK")
print(" - Green LED...", end="")
set_rgb_color(0, 65535, 0)
utime.sleep_ms(300)
print(" OK")
print(" - Blue LED...", end="")
set_rgb_color(0, 0, 65535)
utime.sleep_ms(300)
print(" OK")
set_rgb_color(0, 0, 0)
# Buzzer test
print(" - Buzzer...", end="")
play_buzzer(2, 100)
print(" OK")
utime.sleep(1)
lcd.clear()
lcd.putstr(" SYSTEM READY ")
lcd.move_to(0, 1)
lcd.putstr(" Starting... ")
print("\n✅ All systems operational!")
print("📊 Beginning measurements...\n")
print("Count | Distance (cm) | Distance (in) | Status")
print("─" * 60)
utime.sleep(2)
# ============================================
# MAIN PROGRAM
# ============================================
def main():
"""
Main program loop
"""
global distance_cm, distance_inch, measurement_count
# Run startup sequence
startup_sequence()
# Main measurement loop
while True:
try:
# Measure distance
distance_cm = measure_distance()
# Convert to inches (1 inch = 2.54 cm)
distance_inch = distance_cm / 2.54
# Increment counter
measurement_count += 1
# Update LCD display
update_lcd(distance_cm, distance_inch)
# Print to serial
print_serial_data(distance_cm, distance_inch, measurement_count)
# Process alerts (LED and buzzer)
process_alerts(distance_cm)
# Delay between measurements (adjust as needed)
utime.sleep_ms(500)
except KeyboardInterrupt:
print("\n\n⛔ Program stopped by user")
lcd.clear()
lcd.putstr(" STOPPED! ")
set_rgb_color(0, 0, 0)
buzzer.value(0)
break
except Exception as e:
print(f"\n❌ Error: {e}")
lcd.clear()
lcd.putstr(" SYSTEM ERROR ")
lcd.move_to(0, 1)
lcd.putstr(" Check Serial ")
set_rgb_color(65535, 0, 0)
play_buzzer(5, 100)
utime.sleep(5)
# ============================================
# RUN MAIN PROGRAM
# ============================================
if __name__ == "__main__":
main()
Green LED → GPIO16 (through 220Ω resistor)
Yellow LED → GPIO17 (through 220Ω resistor)
Red LED → GPIO18 (through 220Ω resistor)
All LED cathodes → GND
Buzzer (Optional):
Positive → GPIO19
Negative → GND
lcd_api.py:
"""
LCD API - Base class for LCD displays
Provides common interface for different LCD implementations
"""
class LcdApi:
"""
Implements the API for talking with HD44780 compatible character LCDs.
This class only knows what commands to send to the LCD, and not how to send
them (that's the job of the derived class).
"""
# Commands
LCD_CLR = 0x01 # DB0: clear display
LCD_HOME = 0x02 # DB1: return to home position
LCD_ENTRY_MODE = 0x04 # DB2: set entry mode
LCD_ENTRY_INC = 0x02 # --DB1: increment
LCD_ENTRY_SHIFT = 0x01 # --DB0: shift
LCD_ON_CTRL = 0x08 # DB3: turn lcd/cursor on
LCD_ON_DISPLAY = 0x04 # --DB2: turn display on
LCD_ON_CURSOR = 0x02 # --DB1: turn cursor on
LCD_ON_BLINK = 0x01 # --DB0: blinking cursor
LCD_MOVE = 0x10 # DB4: move cursor/display
LCD_MOVE_DISP = 0x08 # --DB3: move display (0-> move cursor)
LCD_MOVE_RIGHT = 0x04 # --DB2: move right (0-> left)
LCD_FUNCTION = 0x20 # DB5: function set
LCD_FUNCTION_8BIT = 0x10 # --DB4: set 8BIT mode (0->4BIT mode)
LCD_FUNCTION_2LINES = 0x08 # --DB3: two lines (0->one line)
LCD_FUNCTION_10DOTS = 0x04 # --DB2: 5x10 font (0->5x7 font)
LCD_CGRAM = 0x40 # DB6: set CG RAM address
LCD_DDRAM = 0x80 # DB7: set DD RAM address
LCD_RS_CMD = 0
LCD_RS_DATA = 1
LCD_RW_WRITE = 0
LCD_RW_READ = 1
def __init__(self, num_lines, num_columns):
self.num_lines = num_lines
self.num_columns = num_columns
self.cursor_x = 0
self.cursor_y = 0
self.backlight = True
self.display_off()
self.backlight_on()
self.clear()
self.hal_write_command(self.LCD_ENTRY_MODE | self.LCD_ENTRY_INC)
self.hide_cursor()
self.display_on()
def clear(self):
"""Clears the LCD display and moves the cursor to the top left corner."""
self.hal_write_command(self.LCD_CLR)
self.hal_write_command(self.LCD_HOME)
self.cursor_x = 0
self.cursor_y = 0
def show_cursor(self):
"""Causes the cursor to be made visible."""
self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY |
self.LCD_ON_CURSOR)
def hide_cursor(self):
"""Causes the cursor to be hidden."""
self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY)
def blink_cursor_on(self):
"""Turns on the cursor, and makes it blink."""
self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY |
self.LCD_ON_CURSOR | self.LCD_ON_BLINK)
def blink_cursor_off(self):
"""Turns on the cursor, and makes it no blink (i.e. be solid)."""
self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY |
self.LCD_ON_CURSOR)
def display_on(self):
"""Turns on (i.e. unblanks) the LCD."""
self.hal_write_command(self.LCD_ON_CTRL | self.LCD_ON_DISPLAY)
def display_off(self):
"""Turns off (i.e. blanks) the LCD."""
self.hal_write_command(self.LCD_ON_CTRL)
def backlight_on(self):
"""Turns the backlight on."""
self.backlight = True
self.hal_backlight_on()
def backlight_off(self):
"""Turns the backlight off."""
self.backlight = False
self.hal_backlight_off()
def move_to(self, cursor_x, cursor_y):
"""Moves the cursor position to the indicated position."""
self.cursor_x = cursor_x
self.cursor_y = cursor_y
addr = cursor_x & 0x3f
if cursor_y & 1:
addr += 0x40 # Lines 1 & 3 add 0x40
if cursor_y & 2: # Lines 2 & 3 add number of columns
addr += self.num_columns
self.hal_write_command(self.LCD_DDRAM | addr)
def putchar(self, char):
"""Writes the indicated character to the LCD at the current cursor position."""
if char != '\n':
self.hal_write_data(ord(char))
self.cursor_x += 1
if self.cursor_x >= self.num_columns or char == '\n':
self.cursor_x = 0
self.cursor_y += 1
if self.cursor_y >= self.num_lines:
self.cursor_y = 0
self.move_to(self.cursor_x, self.cursor_y)
def putstr(self, string):
"""Write the indicated string to the LCD at the current cursor position."""
for char in string:
self.putchar(char)
def custom_char(self, location, charmap):
"""Write a character to one of the 8 CGRAM locations, available as chr(0) through chr(7)."""
location &= 0x7
self.hal_write_command(self.LCD_CGRAM | (location << 3))
self.hal_sleep_us(40)
for i in range(8):
self.hal_write_data(charmap[i])
self.hal_sleep_us(40)
self.move_to(self.cursor_x, self.cursor_y)
def hal_backlight_on(self):
"""Allows the hal layer to turn the backlight on."""
pass
def hal_backlight_off(self):
"""Allows the hal layer to turn the backlight off."""
pass
def hal_write_command(self, cmd):
"""Write a command to the LCD. Must be implemented in derived class."""
raise NotImplementedError
def hal_write_data(self, data):
"""Write data to the LCD. Must be implemented in derived class."""
raise NotImplementedError
def hal_sleep_us(self, usecs):
"""Sleep for given microseconds. Must be implemented in derived class."""
raise NotImplementedError
Applications
Parking Assist Systems: Help drivers park by measuring distance to obstacles
Obstacle Avoidance Robots: Detect and avoid objects in robotic applications
Liquid Level Monitoring: Measure tank fill levels without contact
Smart Trash Bins: Detect when bins are full and need emptying
Security Systems: Detect intruders by motion/presence detection
Automatic Door Openers: Trigger doors when people approach
Industrial Automation: Object detection on conveyor belts
Water Level Sensors: Monitor well or reservoir levels
Smart Agriculture: Measure crop height or soil levels
pic_i2c_api.py
"""
I2C LCD Driver for Raspberry Pi Pico
Supports PCF8574-based I2C LCD adapters
"""
import utime
from lcd_api import LcdApi
# PCF8574 pin definitions
MASK_RS = 0x01 # P0
MASK_RW = 0x02 # P1
MASK_E = 0x04 # P2
MASK_BACKLIGHT = 0x08 # P3
SHIFT_DATA = 4 # P4-P7
class I2cLcd(LcdApi):
"""
Implements a HD44780 character LCD connected via PCF8574 on I2C.
"""
def __init__(self, i2c, i2c_addr, num_lines, num_columns):
self.i2c = i2c
self.i2c_addr = i2c_addr
self.i2c.writeto(self.i2c_addr, bytearray([0]))
utime.sleep_ms(20) # Allow LCD time to powerup
# Send reset 3 times
self.hal_write_init_nibble(self.LCD_FUNCTION | self.LCD_FUNCTION_8BIT)
utime.sleep_ms(5) # need to delay at least 4.1 msec
self.hal_write_init_nibble(self.LCD_FUNCTION | self.LCD_FUNCTION_8BIT)
utime.sleep_ms(1)
self.hal_write_init_nibble(self.LCD_FUNCTION | self.LCD_FUNCTION_8BIT)
utime.sleep_ms(1)
# Put LCD into 4 bit mode
self.hal_write_init_nibble(self.LCD_FUNCTION)
utime.sleep_ms(1)
LcdApi.__init__(self, num_lines, num_columns)
cmd = self.LCD_FUNCTION
if num_lines > 1:
cmd |= self.LCD_FUNCTION_2LINES
self.hal_write_command(cmd)
def hal_write_init_nibble(self, nibble):
"""Writes an initialization nibble to the LCD.
This particular function is only used during initialization.
"""
byte = ((nibble >> 4) & 0x0f) << SHIFT_DATA
self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytearray([byte]))
def hal_backlight_on(self):
"""Allows the hal layer to turn the backlight on."""
self.i2c.writeto(self.i2c_addr, bytearray([1 << 3]))
def hal_backlight_off(self):
"""Allows the hal layer to turn the backlight off."""
self.i2c.writeto(self.i2c_addr, bytearray([0]))
def hal_write_command(self, cmd):
"""Writes a command to the LCD.
Data is latched on the falling edge of E.
"""
byte = ((self.backlight << 3) |
(((cmd >> 4) & 0x0f) << SHIFT_DATA))
self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytearray([byte]))
byte = ((self.backlight << 3) |
((cmd & 0x0f) << SHIFT_DATA))
self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytearray([byte]))
if cmd <= 3:
# The home and clear commands require a worst case delay of 4.1 msec
utime.sleep_ms(5)
def hal_write_data(self, data):
"""Write data to the LCD."""
byte = (MASK_RS |
(self.backlight << 3) |
(((data >> 4) & 0x0f) << SHIFT_DATA))
self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytearray([byte]))
byte = (MASK_RS |
(self.backlight << 3) |
((data & 0x0f) << SHIFT_DATA))
self.i2c.writeto(self.i2c_addr, bytearray([byte | MASK_E]))
self.i2c.writeto(self.i2c_addr, bytearray([byte]))
def hal_sleep_us(self, usecs):
"""Sleep for some time (in microseconds)."""
utime.sleep_us(usecs)
How It Works:
Ultrasonic Distance Measurement Principle:
Trigger Phase: Pico sends 10µs HIGH pulse to TRIG pin
Ultrasonic Burst: Sensor emits 8 pulses at 40kHz frequency
Echo Wait: Sound waves travel to object and bounce back
Echo Received: ECHO pin goes HIGH when reflected waves return
Time Measurement: Duration of ECHO HIGH = round-trip time
Distance Calculation:
Distance (cm) = (Echo Time in µs × 0.0343 cm/µs) / 2
Distance (cm) = (Echo Time in µs × 34300 cm/s) / 2000000
Why divide by 2?
Sound travels to the object AND back, so total distance is twice the actual object distance.
Comments
Post a Comment