I want my Raspberry Pi B+ Model to generate a triangle wave and output a PWM signal from one of the GPIO pins, but I'm not sure how to go about doing this. All I want it to do is add some small length to every next pulse until it hits 100%, then it subtracts some amount from every pulse width. So if the triangle wave is at its high peak the PWM is at 100% duty cycle, and if it's at its low peak the PWM is at 0% duty cycle. Any ideas or suggestions? Thank you in advance!

New note: For 6.28 seconds from 0% to 100% at 500 Hz

  • You need to clarify your requirements. As a minimum the length of the maximum pulse, the number of steps between 0 and maximum pulse, the time spent at each step.
    – joan
    Commented Oct 21, 2014 at 6:10
  • 6.28 seconds from 0% to 100% at 500 Hz
    – ashlyk321
    Commented Oct 21, 2014 at 23:05

1 Answer 1


There may be many ways of doing what you want. You still need to tighten up your requirements. There are many variables which are not clear.

Here is a possible solution using my pigpio library.

webm video

#!/usr/bin/env python

# 2014-10-22
# sweep-pwm.py
# Public Domain

import time

import pigpio


pi = pigpio.pi() # Connect to local Pi.

f = pi.set_PWM_frequency(GPIO, FREQUENCY)

if f != FREQUENCY:
   print("Can't set frequency {}.".format(FREQUENCY))

# Find real number of steps from min to max
# and use this value in the loop.

r = pi.get_PWM_real_range(GPIO)

pi.set_PWM_range(GPIO, r)

for i in range(LOOPS):

   for s in range(r+1):
      pi.set_PWM_dutycycle(GPIO, s)

pi.set_PWM_dutycycle(GPIO, s) # Stop PWM on gpio.
pi.stop() # Close connection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.