In the lesson there is a conversion to be able to convert the desired angle to the duty so the servo drives to the desired location. The function looks like this:
def servo_write(pin, angle):
pulse_width = interval_mapping(angle, 0, 180, 0.5, 2.5) # Calculate the pulse width
duty = int(interval_mapping(pulse_width, 0, 20, 0, 1023))# Calculate the duty cycle
print(pulse_width, duty)
pin.duty(duty) # Set the duty cycle of the PWM signal
This allows you to pump in the data of whatever open loop servo you may be trying to use. This is a 180 degree servo with a duty range of .5ms to 2.5ms.
You can reduce the math down and save yourself some complexity with this:
def servo_write(pin, angle):
duty = int((angle / 180) * (128 - 26) + 26)
pin.duty(duty)
180 number of degrees of travel.
128 is the maximum duty (2.5ms)
26 is the minimum duty (.5ms)
Depending on the 9G servo that you may find, the duty may be 1ms-2ms instead of .5ms-2.5ms. That would give you a duty range of 51-102ms instead of 26-128ms.
There are other considerations, but these are general. The lesson’s formula is spot on, it just isn’t yet optimized. Mine could be optimized further (such as the 128 - 26 could simply be replaced with 102, etc.), but this is about as far as it gets and is still easily understood.
It’s import to remember that this is not an accurate servo and is not designed for accuracy. But, if it’s steering a low speed rc or acting as an operator, it’s perfect. If you’re looking for accuracy, spinners, etc. there’s a whole world of servos out there waiting.