Buy from USA | Buy from UK | Buy from DE | Buy from IT | Buy from FR | Buy from ES | ここでご購入を! |
We have learned ADC analog input and PWM analog output concept in Lesson 3. This time, we use some new analog input device and PWM output device.
In this lesson, we will show you how to read analog signal from a potentiometer(adjustable resistor) through a Pico ADC pin(GP28) . We will also connect a Servo motor to GP16 which can generate PWM signal. The servo will rotate its arm when you rotate potentiometer.
In above circuit graph, you can see that:
Servo red wire connected to Pico Vbus pin(5V)
Servo brown wire connected to Pico GND
Servo yellow wire connected to Pico PWM pin(GP16)
Potentiometer GND connected to Pico GND
Potentiometer VCC connected to Pico 3.3V
Potentiometer middle pin connected to Pico ADC pin(GP28)
You can download the lesson 5 Python code from https://osoyoo.com/driver/pico/lesson5/pico-lesson5.py.
You can use Thonny to open pico-lesson5.py and load it to Pico later.
Here is the full code with comments:
from machine import Pin, PWM, ADC #import libraries for Pin, PWM, ADC from time import sleep adc = ADC(Pin(28)) #set Potentiometer analog input from GP28 pin servoPin = PWM(Pin(16)) #set servo pwm output to GP16 pin servoPin.freq(50) #set servo frequency 50 def servo(degrees): #rotate servo arm to degrees position # limit degrees beteen 0 and 180 if degrees > 180: degrees=180 if degrees < 0: degrees=0 # set max and min duty maxDuty=9000 minDuty=1000 # new duty is between min and max duty in proportion to its value newDuty=minDuty+(maxDuty-minDuty)*(degrees/180) # servo PWM value is set servoPin.duty_u16(int(newDuty)) while True: value=adc.read_u16() #read Potentiometer value print(value) degree=value*180/65500 #convert Potentiometer value to a servo position angle servo(degree) #rotate servo to that angle sleep(0.001)
Step 1: Connect the Pico board to one of the USB ports on your PC.
Step 2: If you haven't installed Thonny software or don't know how to use the Thonny IDE, please read lesson 1.
Step 3: Now open the Thonny Python IDE, click Run to select MicroPython for Raspberry Pi Pico as the interpreter.:
Also, please select the COM port to which your Pico board is connected:
After that, click OK to save the settings.
Step 4: Now copy the Python code to the Thonny window as follows:
Step 5: Click the little ► button, and the save dialog box will pop up as shown in the following photo.
Select Raspberry Pi Pico as the destination.
Step 6: Name the file as pico-lesson5.py, then click OK.
Step 7: Click the little ► button again to run the Python code.
Now you can rotate the potentiometer, and you will see the servo arm rotate accordingly.
After the operation is complete, press Ctrl+C to end the command.
DownLoad Url osoyoo.com