Hello, I want to connect a raspberry pi 3 b+ hc-sr04 sensor and I have a 2x16 LCD screen. I leave the code I wrote and I also leave the error given in the code.
import RPi.GPIO as GPIO
import smbus
import time
I2C_ADDR = 2
LCD_WIDTH = 16
TRIG_PIN = 17
ECHO_PIN = 18
bus = smbus.SMBus(1)
def setup_gpio():
GPIO.setmode(GPIO.BCM)
GPIO.setup(TRIG_PIN, GPIO.OUT)
GPIO.setup(ECHO_PIN, GPIO.IN)
def send_trigger_pulse():
GPIO.output(TRIG_PIN, GPIO.HIGH)
time.sleep(0.00001)
GPIO.output(TRIG_PIN, GPIO.LOW)
def wait_for_echo():
start = time.time()
while GPIO.input(ECHO_PIN) == GPIO.LOW:
pass
return time.time() - start
def measure_distance():
send_trigger_pulse()
duration = wait_for_echo()
distance = duration * 340 / 2
return distance
def display_distance(distance):
message = "Mesafe: {:.2f} cm".format(distance)
bus.write_i2c_block_data(I2C_ADDR, 0x00, [ord(c) for c in message])
try:
while True:
setup_gpio()
distance = measure_distance()
display_distance(distance)
time.sleep(1)
finally:
GPIO.cleanup()