import sys
import select
from machine import Pin
import time

step_pin = Pin(2, Pin.OUT)
dir_pin = Pin(1, Pin.OUT)
en_pin = Pin(28, Pin.OUT)

en_pin.value(0) # Motor Enable

current_pos: int = 0
dial_value: int = 0

def map_value(x: int, in_min: int, in_max: int, out_min: int, out_max:int) -> float:
    return (x - in_min) * (out_max - out_min) // (in_max - in_min) + out_min

# Serial Port Config
poll_obj = select.poll()
poll_obj.register(sys.stdin, select.POLLIN)

def main():
    global current_pos, dial_value
    
    while True:
        # Checks for data in the serial buffer
        poll_results = poll_obj.poll(0)
        
        if poll_results:
            # Reads incomming message
            mensaje = sys.stdin.readline().strip()
            
            if mensaje:
                try:
                    # Convert message to string
                    dial_value = int(mensaje)
                except ValueError:
                    # Ingore unrecognized values
                    pass
                
        # Moves the motor acordingly
        target_pos = map_value(dial_value, 0, 99, 0, 200)
        
        while target_pos != current_pos:
            print("moviendo...")
            if target_pos > current_pos:
                dir_pin.value(1)
            
                step_pin.value(1)
                time.sleep_us(1000)
                step_pin.value(0)
                time.sleep_us(1000)
            
                current_pos += 1
            
            elif target_pos < current_pos:
                dir_pin.value(0)
                
                step_pin.value(1)
                time.sleep_us(1000)
                step_pin.value(0)
                time.sleep_us(1000)
            
                current_pos -= 1
        time.sleep_us(1000)

if __name__ == "__main__":
    main()