Raspberry Pi Pico Servo Motor Control

Raspberry Pi Pico Servo Motor Control

Hello,

In this article we are going learn how to control Servo Motor using Raspberry Pi Pico. Here, we are going to control servo by rotating  potentiometer.

So, let’s make it.

Video

Here you can watch full video or continue to read the post

Require Components

Raspberry Pi Pico : https://amzn.to/3fIN7ZQ
Servo Motor : https://amzn.to/3rT8iuq
Potentiometer : https://amzn.to/2QYAY8A
Micro USB cable for programming

Schematic Diagram

To control Servo Motor using Raspberry Pi Pico please follow the circuit diagram below

Raspberry Pi Pico Servo Motor Control Schematic Diagram
  • Connect PWM pin of servo motor with GP0 pin of Raspberry Pi Pico
  • Connect Vcc pin of pico with 3.3 Volt of pico
  • Connect ground with ground
  • Connect terminal 1 of potentiometer with Ground
  • Connect output pin of pico with GP28
  • Connect terminal 2 of potentiometer with 3.3 volt

Now connect USB cable with Raspberry Pi Pico and open ThonnyIDE for coding.

Code

control Servo Motor using Raspberry Pi Pico

To write and upload code, Here i used ThonnyIDE and for coding i used micropython language.

Code Explanation:-

from machine import Pin, PWM

This will import Pin and PWM from machine library

analogvalue = machine.ADC(28)

Here, I defined object named as analogvalue and set analog to digital pin 28 as analogvalue

pwm = PWM(Pin(0))

Another object named pwm set PWM at pin 0 of raspberry pi pico, our servo motor will connect to the pin 0

pwm.freq(50)

This will define frequency

below is the while loop which run continuously it check the analog input from potentiometer and move servo accordingly.

while True:
    reading = analogvalue.read_u16()
    pwm.duty_u16(int(reading/6))

This is main command, it is written in while loop so in run continuously.

In a object named reading, analog read will value store then pwm signal given to same pin on which servo motor connected.

Here, We divide analog read signal by 6, because we get more value and our required value we can get by divide it by 6.

Full Code

from machine import Pin, PWM
analogvalue = machine.ADC(28)
pwm = PWM(Pin(0))
pwm.freq(50)
while True:
    reading = analogvalue.read_u16()
    pwm.duty_u16(int(reading/6))

Now, save this code in Raspberry Pi Pico and name it main.py

And rotate the knob of potentiometer to change the position of servo motor.