Introduction to Python and Microcontrollers

Servo Knob

Control a servo’s angle directly with a potentiometer — turn the knob, the servo follows.

New Concepts

Component List

Components

Circuit

Servos need a clean 5V supply — double-check polarity before connecting power.

Wiring Diagram

Disconnect all power before building the circuit. Reconnect once verified.

Wiring Diagram

Connections:

Schematic Diagram

Schematic Diagram

Code

File: 04_output/code/Servo_Knop.py Module: 04_output/code/myservo.py

from myservo import myServo
from machine import ADC,Pin
import time

servo=myServo(21)

adc=ADC(Pin(14))
adc.atten(ADC.ATTN_11DB)
adc.width(ADC.WIDTH_12BIT)

try:
    while True:
        adcValue=adc.read()
        angle=(adcValue*180)/4096
        servo.myServoWriteAngle(int(angle))
        time.sleep_ms(50)
except:
    adc.deinit()
    servo.deinit()

How to Run

Online

  1. Open Thonny → 04_output/code/.
  2. Right-click myservo.pyUpload to / if it isn’t already on the device.
  3. Double-click Servo_Knop.py.
  4. Click Run current script. Turn the potentiometer — the servo rotates to match its position.

Code Explanation

Scale the ADC range onto the servo’s angle range

adcValue=adc.read()
angle=(adcValue*180)/4096
servo.myServoWriteAngle(int(angle))

The ADC returns 0–4095 (12-bit); multiplying by 180 and dividing by 4096 rescales that range onto 0–180°, the servo’s full range of motion — the same range-remapping idea as Soft Light’s remap(), just written inline as one expression instead of a separate function.


Key Concepts

See class myServo for the full API reference.

Further Exploration

Back to Module

Adapted from Python_Tutorial.pdf Project 18.2