from machine import Pin, PWM, ADC
from time import sleep
class Servo:
# these defaults work for the standard TowerPro SG90
__servo_pwm_freq = 50
__min_u10_duty = 26 - 0 # offset for correction
__max_u10_duty = 123- 0 # offset for correction
min_angle = 0
max_angle = 180
current_angle = 0.001
def __init__(self, pin):
self.__initialise(pin)
def update_settings(self, servo_pwm_freq, min_u10_duty, max_u10_duty, min_angle, max_angle, pin):
self.__servo_pwm_freq = servo_pwm_freq
self.__min_u10_duty = min_u10_duty
self.__max_u10_duty = max_u10_duty
self.min_angle = min_angle
self.max_angle = max_angle
self.__initialise(pin)
# def move(self, angle):
# # round to 2 decimal places, so we have a chance of reducing unwanted servo adjustments
# angle = round(angle, 2)
# # do we need to move?
# if angle == self.current_angle:
# return
# self.current_angle = angle
# # calculate the new duty cycle and move the motor
# duty_u10 = self.__angle_to_u10_duty(angle)
# self.__motor.duty(duty_u10)
def move(self, angle):
# round to 2 decimal places, so we have a chance of reducing unwanted servo adjustments
angle = round(angle, 2)
# limit the angle within the defined range
angle = max(self.min_angle, min(self.max_angle, angle))
# do we need to move?
if angle == self.current_angle:
return
self.current_angle = angle
# calculate the new duty cycle and move the motor
duty_u10 = self.__angle_to_u10_duty(angle)
self.__motor.duty(duty_u10)
def __angle_to_u10_duty(self, angle):
return int((angle - self.min_angle) * self.__angle_conversion_factor) + self.__min_u10_duty
def __initialise(self, pin):
self.current_angle = -0.001
self.__angle_conversion_factor = (self.__max_u10_duty - self.__min_u10_duty) / (self.max_angle - self.min_angle)
self.__motor = PWM(Pin(pin))
self.__motor.freq(self.__servo_pwm_freq)
motor=Servo(pin=22) # A changer selon la broche utilisée
ldr1=ADC(Pin(14,Pin.IN))
ldr2=ADC(Pin(4,Pin.IN))
pos=90
# def map(x,inmin,inmax,outmin,outmax):
# return (x-inmin)*(outmax-outmin)//(inmax-inmin)+outmin
while 1:
reading1=ldr1.read()
reading2=ldr2.read()
sleep(0.5)
print(f"{reading1}\t {reading2}")
if reading1>reading2:
pos-=1
motor.move(pos)
if reading1<reading2:
pos+=1
motor.move(pos)
#
# else:
# if reading1>reading2