Python Code 15.1.1 Sweep
First observe the project result, and then analyze the code.
1. Use cd command to enter 15.1.1_Sweep directory of Python code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/Python_Code/15.1.1_Sweep
2. Use python command to execute code "Sweep.py".
python Sweep.py
After the program is executed, the servo will rotate from 0 degrees to 180 degrees, and then from 180 degrees
to 0 degrees, circularly.
The following is the program code:
im port RPi. GPIO as GPIO
im port time
OFFSE_DUTY = 0.5 #define pulse offset of servo
SERVO_MIN_DUTY = 2.5+ OFFSE_DUTY #define pulse duty cycle for minimum angle of servo
SERVO_MAX_DUTY = 12.5+ OFFSE_DUTY #define pulse duty cycle for maximum angle of servo
servoPin = 12
def map( value, fromLow, fromHigh, toLow, toHigh):
r eturn (toHigh-toLow)*(value-fromLow) / (fromHigh-fromLow) + toLow
def setup():
g lobal p
GPIO. setmode(GPIO.BOARD) # Numbers GPIOs by physical location
GPIO. setup(servoPin, GPIO. OUT) # Set servoPin's mode is output
GPIO. output(servoPin, GPIO. LOW) # Set servoPin to low
p = GPIO. PWM(servoPin, 50) # set Frequece to 50Hz
p. start(0) # Duty Cycle = 0
def servoWrite(angle): # make the servo rotate to specific angle (0-180 degrees)
if(angle<0):
angle = 0
e lif(angle > 180):
angle = 180
p. ChangeDutyCycle(map(angle,0,180,SERVO_MIN_DUTY,SERVO_MAX_DUTY))#map the angle to
duty cycle and output it
def loop():
w hile Tr ue:
for dc in range( 0, 181, 1): #make servo rotate from 0 to 180 deg
servoWrite(dc) # Write to servo
time.sleep(0.001)
time.sleep(0.5)
for dc in range( 180, - 1, -1): #make servo rotate from 180 to 0 deg