from machine import Pin, PWM, ADC
import time
# Pines del puente H
pinIN1 = Pin(13, Pin.OUT)
pinIN2 = Pin(12, Pin.OUT)
pwmENA = PWM(Pin(14), freq=100, duty=0)
# Potenciómetro para velocidad
potVelocidad = ADC(Pin(34))
potVelocidad.atten(ADC.ATTN_11DB)
potVelocidad.width(ADC.WIDTH_12BIT)
# Botón para cambiar dirección
boton = Pin(32, Pin.IN, Pin.PULL_UP)
# Estado del giro
sentido = True # True: adelante, False: atrás
ultimo_estado_boton = 1
def map_value(x, in_min, in_max, out_min, out_max):
return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
while True:
# Leer potenciómetro de velocidad
valorVelocidad = potVelocidad.read()
velocidadPWM = map_value(valorVelocidad, 0, 4095, 0, 255)
# Leer botón (pulso)
estado_boton = boton.value()
if estado_boton == 0 and ultimo_estado_boton == 1:
sentido = not sentido # Cambia de sentido al presionar
time.sleep(0.2) # Anti-rebote básico
ultimo_estado_boton = estado_boton
# Establecer dirección del motor
if sentido:
pinIN1.on()
pinIN2.off()
else:
pinIN1.off()
pinIN2.on()
# Aplicar PWM
pwmENA.duty(velocidadPWM)
print(f"Sentido: {'adelante' if sentido else 'atrás'}, Velocidad: {velocidadPWM}")
time.sleep(0.05)