# from machine import Pin , PWM
# import time
# servo = PWM(Pin(5) , freq = 50)
# potpin = PWM(Pin(34))
# while True :
# pinvalue = map(potpin , 0 , 1023 , 20 , 120)
# servo.duty(pinvalue)
# def map(x , in_min , in_max , out_min , out_max):
# return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
'''
from machine import Pin, PWM, ADC
from time import sleep
# Define pins
servo_pin = 5 # GPIO pin to which the servo is connected
potentiometer_pin = 34 # ADC pin to which the potentiometer is connected
# Set up PWM for servo
frequency = 50 # Frequency in Hz (50Hz for standard servo motors)
servo_pwm = PWM(Pin(servo_pin), freq=frequency)
# Set up ADC for potentiometer
adc = ADC(Pin(potentiometer_pin))
adc.atten(ADC.ATTN_11DB) # Full range: 3.3V
adc.width(ADC.WIDTH_10BIT) # 10-bit resolution
def set_servo_angle(pwm, angle):
min_duty = 20
max_duty = 120
duty = min_duty + (max_duty - min_duty) * (angle / 180)
pwm.duty(int(duty))
def map_value(x, in_min, in_max, out_min, out_max):
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
try:
while True:
# Read the potentiometer value (0-4095)
pot_value = adc.read()
# Map the potentiometer value to an angle (0-180 degrees)
angle = map_value(pot_value, 0, 1023, 0, 180)
# Set the servo angle
set_servo_angle(servo_pwm, angle)
# Small delay to avoid flooding the servo with commands
sleep(0.05)
except KeyboardInterrupt:
# Deinitialize the PWM to turn off the servo
servo_pwm.deinit()
'''
from machine import Pin, PWM, ADC
from time import sleep
# Define pins
servo_pin = 5 # GPIO pin to which the servo is connected
potentiometer_pin = 34 # ADC pin to which the potentiometer is connected
# Set up PWM for servo
frequency = 50 # Frequency in Hz (50Hz for standard servo motors)
servo_pwm = PWM(Pin(servo_pin), freq=frequency)
# Set up ADC for potentiometer
adc = ADC(Pin(potentiometer_pin))
adc.atten(ADC.ATTN_11DB) # Full range: 3.3V
adc.width(ADC.WIDTH_10BIT) # 10-bit resolution
def command(pwm, x, in_min, in_max, out_min, out_max):
angle = (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
min_duty = 20
max_duty = 120
duty = min_duty + (max_duty - min_duty) * (angle / 180)
pwm.duty(int(duty))
try:
while True:
# Read the potentiometer value (0-4095)
pot_value = adc.read()
# Map the potentiometer value to an angle (0-180 degrees)
command(servo_pwm, pot_value, 0, 1023, 0, 180)
# Set the servo angle
# Small delay to avoid flooding the servo with commands
sleep(0.05)
except KeyboardInterrupt:
# Deinitialize the PWM to turn off the servo
servo_pwm.deinit()