from machine import Pin
import utime
# Initialize pins
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)
led = Pin(21, Pin.OUT)
on_off_button = Pin(4, Pin.IN, Pin.PULL_DOWN)
on_off_led = Pin(7, Pin.OUT)
separate_button = Pin(9, Pin.IN, Pin.PULL_DOWN)
separate_led = Pin(8, Pin.OUT)
def ultra():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = (timepassed * 0.0343) / 2
print("The distance from object is ", distance, "cm")
return distance
# Main loop
ultrasonic_active = False
on_off_state = False
on_off_led.off()
separate_led_state = False
while True:
# Check if On/Off button is pressed
if on_off_button.value() == 1: # Button is active-low, so 1 means it's not pressed
if not on_off_state: # Toggle the state when button is pressed
on_off_state = True
on_off_led.on() # Turn on On/Off LED
ultrasonic_active = True # Enable ultrasonic sensor
else:
on_off_state = False
on_off_led.off() # Turn off On/Off LED
ultrasonic_active = False # Disable ultrasonic sensor
separate_led.off() # Turn off separate LED if On/Off button is toggled off
# Check if separate button is pressed
if separate_button.value() == 1: # Button is active-low, so 1 means it's not pressed
if on_off_state: # Only control separate LED if On/Off button is on
separate_led_state = not separate_led_state # Toggle separate LED state
separate_led.value(separate_led_state) # Set separate LED state
# Run ultrasonic sensor if it's active
if ultrasonic_active:
distance = ultra()
if distance <= 30:
led.on() # Turn on main LED if object is close
else:
led.off() # Turn off main LED
utime.sleep(0.1) # Small delay to debounce buttons