Tarea de Sistemas Embebidos Avanzados
Sensor HC-SR04 Proyecto motor sensor de proximidad
from machine import Pin, PWM, I2C
import utime
from pico_i2c_lcd import I2cLcd
# Display
i2c = I2C(1, scl=Pin(27), sda=Pin(26), freq=100000) # Use I2C0, check pins
lcd = I2cLcd(i2c, 0x27, 2, 16)
# Sensor de distancia
trig = Pin(16, Pin.OUT)
echo = Pin(17, Pin.IN)
# Motor giro
pinE = Pin(5, Pin.OUT, value=0) # Enable pin
pinD = Pin(0, Pin.OUT) # Direction pin
pwm = PWM(Pin(4))
pwm.duty_u16(32768) # Initial duty cycle (50%)
pwm.freq(100)
speed = 50 # You might want to adjust this
# -------
def movx1(timet1, speed1):
pinE.on() # Enable motor
pinD.off() # Direction (right)
for _ in range(timet1): # Use _ for unused loop variable
pwm.freq(speed1) # Set PWM frequency
utime.sleep(0.1) # Sleep for 0.1 seconds
pinE.off() # Disable motor
# -------
# Combine the loops into a single loop
while True:
# Motor control (you might want to remove or adjust this)
movx1(1, speed)
utime.sleep_ms(5000)
# Distance measurement
trig.value(0)
utime.sleep_us(5)
trig.value(1)
utime.sleep_us(10)
trig.value(0)
while echo.value() == 0:
pass
Tmrinicio = utime.ticks_us()
while echo.value() == 1:
pass
Tmrfin = utime.ticks_us()
Duration = utime.ticks_diff(Tmrfin, Tmrinicio)
distancecm = Duration * 0.0171
lcd.clear()
lcd.move_to(0, 0) # Corrected position
lcd.putstr('Dist= {:.2f} cm'.format(distancecm)) # Format to 2 decimal places
print(distancecm)
# Conditional motor control based on distance
if distancecm <= 50:
pinE.off() # Motor enable OFF within range
pinD.on() # Move in left direction
utime.sleep(5) # Run for 5 second
else:
pinE.on() # Motor disable outside range
#pinD.off() # No need to change direction if motor is off
utime.sleep(1) # Wait before next measurement
utime.sleep(0.5) # Pause between measurements