from machine import Pin
from utime import sleep
import time
# 7-segment display layout
# A
# ---
# F | G | B
# ---
# E | | C
# ---
# D
#Serial.begin(9600)
pins1 = [
Pin(2, Pin.OUT), # A
Pin(3, Pin.OUT), # B
Pin(4, Pin.OUT), # C
Pin(5, Pin.OUT), # D
Pin(6, Pin.OUT), # E
Pin(8, Pin.OUT), # F
Pin(7, Pin.OUT), # G
Pin(0, Pin.OUT) # DP (not connected)
]
pins2 = [
Pin(9, Pin.OUT), # A
Pin(10, Pin.OUT), # B
Pin(11, Pin.OUT), # C
Pin(12, Pin.OUT), # D
Pin(13, Pin.OUT), # E
Pin(15, Pin.OUT), # F
Pin(14, Pin.OUT), # G
Pin(16, Pin.OUT) # DP (not connected)
]
# Common anode 7-segment display digit patterns
digits = [
[0, 0, 0, 0, 0, 0, 1, 1], # 0
[1, 0, 0, 1, 1, 1, 1, 1], # 1
[0, 0, 1, 0, 0, 1, 0, 1], # 2
[0, 0, 0, 0, 1, 1, 0, 1], # 3
[1, 0, 0, 1, 1, 0, 0, 1], # 4
[0, 1, 0, 0, 1, 0, 0, 1], # 5
[0, 1, 0, 0, 0, 0, 0, 1], # 6
[0, 0, 0, 1, 1, 1, 1, 1], # 7
[0, 0, 0, 0, 0, 0, 0, 1], # 8
[0, 0, 0, 1, 1, 0, 0, 1], # 9
]
def reset(pins):
"""Turns off all segments on the 7-segment display."""
for pin in pins:
pin.value(1)
reset(pins1)
reset(pins2)
# Define the pins for the HC-SR04 sensor
trig = Pin(17, Pin.OUT)
echo = Pin(18, Pin.IN)
def read_distance():
"""Reads the distance from the HC-SR04 sensor."""
trig.low()
sleep(0.000002) # Wait for 2 microseconds
trig.high()
sleep(0.000001) # Keep the trigger high for 10 microseconds
trig.low()
while echo.value() == 0:
pass
start = time.ticks_us() # Get the current time in microseconds
while echo.value() == 1:
pass
end = time.ticks_us() # Get the current time in microseconds
# Calculate the distance in centimeters
#print(f"End - start: {end-start}")
distance = ((end - start) / 58)
return distance
while True:
# Read the distance from the sensor
distance = read_distance()-0.5
if distance < 100:
# Display the distance on the 7-segment displays
tens = int(distance // 10) # Get the tens digit
ones = int(distance % 10) # Get the ones digit
print(distance)
# Display the tens digit
for j in range(len(pins1) - 1):
pins1[j].value(digits[tens][j])
# Display the ones digit
for j in range(len(pins2) - 1):
pins2[j].value(digits[ones][j])
sleep(0.5)
else:
print(distance)
# Display the tens digit
for j in range(len(pins1) - 1):
pins1[j].value(digits[0][j])
# Display the ones digit
for j in range(len(pins2) - 1):
pins2[j].value(digits[0][j])
sleep(0.5)