from machine import Pin, time_pulse_us
import time
import tm1637
# Define pins connected to the HC-SR04 sensor
trigger_pin = Pin(4, Pin.OUT)
echo_pin = Pin(5, Pin.IN)
# Define pins connected to the TM1637 display
clk = Pin(1)
data = Pin(0)
display = tm1637.TM1637(clk, data)
red_led_pin = Pin(6,Pin.OUT)
yellow_led_pin = Pin(7, Pin.OUT)
green_led_pin = Pin(8, Pin.OUT)
buzzer_pin = Pin(9,Pin.OUT)
# Function to measure distance using HC-SR04 sensor
def measure_distance():
"""Measures the distance using the HC-SR04 ultrasonic sensor.
Returns:
float: The distance in centimeters, or None if an error occurs.
"""
# Send a 10us pulse on the trigger pin to start the measurement
trigger_pin.value(0) # Ensure initial low state
time.sleep_us(2)
trigger_pin.value(1)
time.sleep_us(10)
trigger_pin.value(0)
# Measure echo pulse duration with timeout
duration = time_pulse_us(echo_pin, 1, 30000) # Timeout of 30ms (adjustable)
if duration is None:
print("Error: Sensor timeout")
return None
# Calculate distance using speed of sound (343 m/s)
# Divide by 2 for round trip measurement
distance = duration * 0.0343 / 2
return distance
def bacaan_lampu (height):
red_led_pin.value(0)
yellow_led_pin.value(0)
green_led_pin.value(0)
if height >= 30:
red_led_pin.value(1)
elif height >= 20 :
yellow_led_pin.value(1)
else:
green_led_pin.value(1)
def control_buzzer(height):
if height >= 30:
buzzer_pin.value(1)
else:
buzzer_pin.value(0)
def display_height(height):
"""Displays a message on the TM1637 based on the height.
Args:
height (float): The distance in centimeters.
"""
# Convert height to integer string (adjust based on display limitations)
height_str = str(int(height)) if height < 100 else str(int(height / 10)) # Truncate for larger values
# Determine indicator message based on height thresholds
if height >= 30:
indicator_message = "BAhaya"
elif height >= 20:
indicator_message = "Waspada"
else:
indicator_message = "aman"
# Display message on the TM1637 (consider adding scrolling)
display.scroll(indicator_message) # Adjust display behavior as needed
def main():
"""Main program loop."""
while True:
# Measure distance and handle errors
distance = measure_distance()
if distance is None:
continue
# Convert distance to height (assuming sensor is horizontal)
height = distance
# Display height on TM1637 and potentially control LEDs or buzzer (add in separate functions as needed)
display_height(height)
bacaan_lampu (height)
# Print distance for debugging or logging purposes
print(f"Distance: {distance:.2f} cm")
# Wait for a short period before next measurement
time.sleep(1)
if __name__ == "__main__":
main()