import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 100) pwm.start(0) while True: for dc in range(0, 101, 5): pwm.ChangeDutyCycle(dc) time.sleep(0.1) for dc in range(100, -1, -5): pwm.ChangeDutyCycle(dc) time.sleep(0.1)
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) pwm = GPIO.PWM(18, 100) pwm.start(0) while True: for dc in range(0, 101, 5): pwm.ChangeDutyCycle(dc) time.sleep(0.1) for dc in range(100, -1, -5): pwm.ChangeDutyCycle(dc) time.sleep(0.1)In this example, we are using PWM to control the speed of a motor connected to GPIO pin 18. The `pwm` object is created with a frequency of 100 Hz and is started at a duty cycle of 0. The duty cycle is changed in increments of 5 from 0 to 100 and then from 100 to 0 in a loop, resulting in a smooth acceleration and deceleration of the motor. The package library used for these examples is `RPi.GPIO`, which provides access to the GPIO pins on a Raspberry Pi using Python.