from machine import Pin, PWM, I2C
import utime
import lcd_api
import i2c_lcd
class Servo:
MAX_DUTY_CYCLE = 2**16 - 1 # largest unsigned int (65535)
SLEEP_PERIOD_IN_SECONDS = 2
MILLISECONDS_PER_SECOND = 1000
SERVO_PERIOD_IN_MILLISECONDS = 20
SERVO_FREQUENCY = int(MILLISECONDS_PER_SECOND / SERVO_PERIOD_IN_MILLISECONDS)
SERVO_RIGHT_TURN_DUTY = 0.5 # Set duty to 0.5 milliseconds
SERVO_GO_STRAIGHT_DUTY = 1.5 # Set duty to 1.5 milliseconds
SERVO_LEFT_TURN_DUTY = 2.5 # Set duty to 2.5 milliseconds
SERVO_0_ANGLE = 0 # servo angle for 0 degrees
SERVO_90_ANGLE = 90 # servo angle for 90 degrees
SERVO_180_ANGLE = 180 # servo angle for 180 degrees
def __init__(self, pin, frequency=50):
self.pwm_pin = PWM(pin) # initialize PWM pin for servo control
self.pwm_pin.freq(frequency) # set PWM frequency
self.duty_cycle = 0 # initialize duty cycle value to 0
def set_position_by_angle(self, angle):
self.angle = angle # angle is set
# calculate the duty cycle percentage by the angle
self.duty_cycle_percentage = (
((angle / 180.0) * (Servo.SERVO_LEFT_TURN_DUTY - Servo.SERVO_RIGHT_TURN_DUTY) + Servo.SERVO_RIGHT_TURN_DUTY)
/ Servo.SERVO_PERIOD_IN_MILLISECONDS
* 100
)
# calculate duty value
self.duty_cycle = Servo.MAX_DUTY_CYCLE * (self.duty_cycle_percentage / 100)
# set PWM duty cycle
self.pwm_pin.duty_u16(int(self.duty_cycle))
def print_settings(self):
# print the servo settings
print("Servo PWM Frequency: " + str(Servo.SERVO_FREQUENCY))
print("Servo PWM Period (milliseconds): " + str(Servo.SERVO_PERIOD_IN_MILLISECONDS))
print("Duty/Period percentage: " + str(self.duty_cycle_percentage))
print("Duty value (1:65535): " + str(self.duty_cycle))
print("\n")
utime.sleep(Servo.SLEEP_PERIOD_IN_SECONDS)
# Setup for the I2C LCD
i2c = I2C(0, sda=Pin(4), scl=Pin(5), freq=400000)
lcd = i2c_lcd.I2cLcd(i2c, 0x27, 2, 16)
# servo is set to pin 1
servo = Servo(Pin(1), Servo.SERVO_FREQUENCY)
def save_values(file_path):
with open(file_path, 'r') as file: # reads the file
for line in file:
direction, time_in_seconds = line.strip().split(',') # splits the direction and time in seconds with a comma
direction = int(direction)
time_in_seconds = int(time_in_seconds)
print(direction, ",", time_in_seconds) # prints the direction and time in seconds
servo.set_position_by_angle(direction) # set position to its proper angle
servo.print_settings()
# Display on LCD
lcd.clear()
lcd.putstr(f"Dir: {direction}\nTime: {time_in_seconds}")
utime.sleep(time_in_seconds)
file.close() # closes the file
# File path to your records
file_path = "values.txt" # saves the code to the file path
save_values(file_path)