import machine
import utime
# GPIO pins for 7-segment display segments (a-g)
segments = [
machine.Pin(0, machine.Pin.OUT), # Segment a
machine.Pin(1, machine.Pin.OUT), # Segment b
machine.Pin(2, machine.Pin.OUT), # Segment c
machine.Pin(3, machine.Pin.OUT), # Segment d
machine.Pin(4, machine.Pin.OUT), # Segment e
machine.Pin(5, machine.Pin.OUT), # Segment f
machine.Pin(6, machine.Pin.OUT) # Segment g
]
# Pin states for each digit to display numbers 0-9 (corrected for typical 7-segment display)
number_map = [
[1, 1, 1, 1, 0, 1, 1], # 9
[1, 1, 1, 1, 1, 1, 1], # 8
[1, 1, 1, 0, 0, 0, 0], # 7
[1, 0, 1, 1, 1, 1, 1], # 6
[1, 0, 1, 1, 0, 1, 1], # 5
[0, 1, 1, 1, 0, 1, 1], # 4
[1, 1, 1, 1, 0, 0, 1], # 3
[1, 1, 0, 1, 1, 0, 1], # 2
[0, 1, 1, 0, 0, 0, 0], # 1
[1, 1, 1, 1, 1, 1, 0], # 0
]
# Function to display a specific number on the 7-segment display
def display_number(number):
if 0 <= number <= 9: # Ensure the number is between 0 and 9
segments_values = number_map[number]
for i in range(len(segments)):
segments[i].value(segments_values[i])
# HC-SR04 Sensor setup
SOUND_SPEED = 340 # Speed of sound in air (cm/s)
TRIG_PULSE_DURATION_US = 10 # Duration of the trigger pulse (10 µs)
trig_pin = machine.Pin(15, machine.Pin.OUT) # GPIO 15 for Trig
echo_pin = machine.Pin(14, machine.Pin.IN) # GPIO 14 for Echo
# Function to measure distance using HC-SR04
def measure_distance():
# Prepare the signal
trig_pin.value(0)
utime.sleep_us(5)
# Create a 10 µs pulse
trig_pin.value(1)
utime.sleep_us(TRIG_PULSE_DURATION_US)
trig_pin.value(0)
# Measure the duration of the echo pulse
ultrasonic_duration = machine.time_pulse_us(echo_pin, 1, 30000) # Timeout 30ms
# Calculate the distance (in cm)
distance_cm = SOUND_SPEED * ultrasonic_duration / 20000
return distance_cm
# Main loop
current_display_value = 0 # Start with 0
while True:
distance = measure_distance()
print(f"Distance: {distance:.2f} cm") # Print the distance to console
# Calculate the number of steps based on the distance divided by 40
steps = int(distance // 40) # Every 40 cm increase or decrease the number by 1
# Adjust the display value based on the distance
display_value = max(0, min(9, steps)) # Ensure the value stays between 0 and 9
# Display the current number on the 7-segment display
display_number(display_value)
# Wait a short time before the next measurement
utime.sleep(0.2) # Adjusted sleep time for gradual transitions