from machine import Pin, ADC
from utime import sleep
# Pin configuration for 7-segment display
seg7a = [Pin(i, Pin.OUT) for i in range(8)] # abcdefgh
seg7b = [Pin(i, Pin.OUT) for i in range(8, 16)] # abcdefgh
# Segment patterns for numbers 0-9
pattern = [
[1, 1, 1, 1, 1, 1, 0, 0], # 0
[0, 1, 1, 0, 0, 0, 0, 0], # 1
[1, 1, 0, 1, 1, 0, 1, 0], # 2
[1, 1, 1, 1, 0, 0, 1, 1], # 3
[0, 1, 1, 0, 0, 1, 1, 0], # 4
[1, 0, 1, 1, 0, 1, 1, 0], # 5
[1, 0, 1, 1, 1, 1, 1, 0], # 6
[1, 1, 1, 0, 0, 0, 0, 0], # 7
[1, 1, 1, 1, 1, 1, 1, 0], # 8
[1, 1, 1, 1, 0, 1, 1, 0] # 9
]
# Ultrasonic sensor pins (example pins, adjust based on your connections)
TRIGGER_PIN = 21 # Pin for trigger
ECHO_PIN = 20 # Pin for echo
trigger = Pin(TRIGGER_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
def read_distance():
# Send a 10us pulse on the trigger pin
trigger.value(1)
sleep(0.00001)
trigger.value(0)
# Measure the duration of the pulse on the echo pin
pulse_duration = 0
while echo.value() == 0:
pass
start_time = utime.ticks_us()
while echo.value() == 1:
pass
end_time = utime.ticks_us()
# Calculate distance in centimeters
pulse_duration = end_time - start_time
distance = (pulse_duration * 0.0343) / 2 # Speed of sound is approximately 343 m/s
return distance
while True:
distance = read_distance()
# Convert distance to a value suitable for display (0-99)
display_value = int(distance) if distance < 100 else 99
a = display_value % 10
b = display_value // 10
for i in range(8):
seg7a[i].value(pattern[a][i])
seg7b[i].value(pattern[b][i])
sleep(0.5) # Adjust the delay as needed