40pin IO Development
Experiment 04 - PWM Output
Hardware Connection
Connect servo/motor/oscilloscope to IO33 (X5 mainboard supports IO32 and IO33 PWM output).
Software Operation
Enter the user home directory and run:
cd usersudo python3 ./PWM_out.py
Terminal as shown:
You can see: the initial duty cycle is 25%, then increases by 5% every 0.25 seconds, reaches 100%, then decreases by 5% every 0.25 seconds.
#!/usr/bin/env python3
import sys
import signal
import Hobot.GPIO as GPIO
import time
def signal_handler(signal, frame):
sys.exit(0)
# PWM capable pins: 32 and 33, ensure the pin is not used by other functions
output_pin = 33
GPIO.setwarnings(False)
def main():
# Pin Setup:
# Board pin-numbering scheme
GPIO.setmode(GPIO.BOARD)
# Supported frequency range: X3: 48KHz ~ 192MHz X5: 0.05HZ ~ 100MHZ
p = GPIO.PWM(output_pin, 48000)
# Initial duty cycle 25%, increase 5% every 0.25s, then decrease after 100%
val = 25
incr = 5
p.ChangeDutyCycle(val)
p.start(val)
print("PWM running. Press CTRL+C to exit.")
try:
while True:
time.sleep(0.25)
if val >= 100:
incr = -incr
if val <= 0:
incr = -incr
val += incr
p.ChangeDutyCycle(val)
finally:
p.stop()
GPIO.cleanup()
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal_handler)
main()