Skip to content

Instantly share code, notes, and snippets.

@lbussy
Last active July 20, 2024 05:33
Show Gist options
  • Save lbussy/3bff534e12976f08d890f7be573dd071 to your computer and use it in GitHub Desktop.
Save lbussy/3bff534e12976f08d890f7be573dd071 to your computer and use it in GitHub Desktop.
PWM Generator for Raspberry Pi

Raspberry Pi PWM

This Python3 script was created to generate a square wave pattern from the GPIO of the Raspberry Pi. This signal was used to inject a signal into an electronics project, but could be used as the basis for any PWM needs.

pic_6_1

The script is configured to output the signal on pin 12 (GPIO18). Other pins which may be used are pin 32 (GPIO12) and pin 33 (GPIO13). Standard pin numbers (GPIO.BOARD) are used, Broadcom numbering (GPIO.BCM) may be used if desired by editing the appropriate line.

Configuration:

  • pwmPin: Board Pin (change GPIO.BOARD to GPIO.BCM to use Broadcom numbering)
  • dutyCycle: Duty cycle in percent
  • freq: Pulse frequency in Hz
#!/usr/bin/python3
import RPi.GPIO as GPIO
import sys
from time import sleep
pwmPin = 12 # GPIO18 (PWM0)
dutyCycle = 10.0 # 10% duty cycle
freq = 190 # 190 Hz (190 times/second)
def spinning_cursor():
while True:
for cursor in '|/-\\':
yield cursor
def main():
spinner = spinning_cursor()
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pwmPin,GPIO.OUT)
pwm = GPIO.PWM(pwmPin,freq)
pwm.start(dutyCycle)
print("\nOutputting a {}% duty cycle PWM at {}hz on pin {}.".format(dutyCycle, freq, pwmPin))
print("Ctrl-C to quit.")
try:
while (True):
sys.stdout.write(next(spinner))
sys.stdout.flush()
sys.stdout.write('\b')
sleep(0.1)
except KeyboardInterrupt:
print('\n\nKeyboard interrupt.')
finally:
spinner = None
pwm.stop()
GPIO.cleanup()
return
if __name__ == "__main__":
main()
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment