from machine import Pin
import utime
import math
# Sensor Connections
led = Pin(5, Pin.OUT)
button1 = Pin(6, Pin.IN, Pin.PULL_UP)
relay = Pin(7, Pin.OUT)
trigger = Pin(14, Pin.OUT)
echo = Pin(15, Pin.IN)
# LCD Connections
rs = Pin(8, Pin.OUT)
e = Pin(9, Pin.OUT)
d4 = Pin(10, Pin.OUT)
d5 = Pin(11, Pin.OUT)
d6 = Pin(12, Pin.OUT)
d7 = Pin(13, Pin.OUT)
def pulseE():
e.value(1)
utime.sleep_us(40)
e.value(0)
utime.sleep_us(40)
def send2LCD4(BinNum):
d4.value((BinNum & 0b00000001) >> 0)
d5.value((BinNum & 0b00000010) >> 1)
d6.value((BinNum & 0b00000100) >> 2)
d7.value((BinNum & 0b00001000) >> 3)
pulseE()
def send2LCD8(BinNum):
d4.value((BinNum & 0b00010000) >> 4)
d5.value((BinNum & 0b00100000) >> 5)
d6.value((BinNum & 0b01000000) >> 6)
d7.value((BinNum & 0b10000000) >> 7)
pulseE()
d4.value((BinNum & 0b00000001) >> 0)
d5.value((BinNum & 0b00000010) >> 1)
d6.value((BinNum & 0b00000100) >> 2)
d7.value((BinNum & 0b00001000) >> 3)
pulseE()
def setUpLCD():
rs.value(0)
send2LCD4(0b0011)
send2LCD4(0b0011)
send2LCD4(0b0011)
send2LCD4(0b0010)
send2LCD8(0b00101000)
send2LCD8(0b00001100)
send2LCD8(0b00000110)
send2LCD8(0b00000010)
utime.sleep_ms(2)
def send_string_to_lcd(string):
rs.value(1)
for char in string:
send2LCD8(ord(char))
def read_distance():
trigger.value(1)
utime.sleep_us(10)
trigger.value(0)
while echo.value() == 0:
pass
pulse_start = utime.ticks_us()
while echo.value() == 1:
pass
pulse_end = utime.ticks_us()
pulse_duration = pulse_end - pulse_start
distance = (pulse_duration * 0.0343) / 2
return distance
def control_relay(distance):
if distance < 30:
relay.value(1) # Turn on relay
else:
relay.value(0) # Turn off relay
# Add this function to clear the LCD screen and reposition the cursor
def clear_lcd():
rs.value(0)
send2LCD8(0b00000001) # Clear display
utime.sleep_ms(2)
send2LCD8(0b00000010) # Return home
utime.sleep_ms(2)
# Main loop
setUpLCD()
while True:
distance = read_distance()
control_relay(distance)
if button1.value() == 0: # Button pressed
led.toggle() # Toggle LED
#send_string_to_lcd("Distance: {:.2f} cm\n".format(distance))
send_string_to_lcd("Distance: {:.2f} cm\n".format(distance))
utime.sleep(1)
# Add this function to clear the LCD screen and reposition the cursor
def clear_lcd():
rs.value(0)
send2LCD8(0b00000001) # Clear display
utime.sleep_ms(2)
send2LCD8(0b00000010) # Return home
utime.sleep_ms(2)
# Main loop
setUpLCD()
while True:
distance = read_distance()
control_relay(distance)
if button1.value() == 0: # Button pressed
led.toggle() # Toggle LED
clear_lcd() # Clear the LCD screen
send_string_to_lcd("Distance: {:.2f} cm\n".format(distance)) # Update the distance value
utime.sleep(1)