I am trying to create an accurate PWM output using a raspberry pi, model 4b, and hope you can help.

At this stage I am wanting to; change the Duty cycle and frequency, run the code, and see these outputs on an oscilloscope. However, the frequency is proving to be unreliable.

Within the code we state 300Hz (frequency), shown on line 24 at BCM pin 12. However, once running the code, the oscilloscope provides a reading of around 210Hz.

Why is the oscilloscope reading nearly 100Hz off what it should be and how do I make this more reliable?

Note: Lines 18 - 21, do not effect the outcome. These will be used later. And the oscilloscope probes are connected to BCM pin 12, and ground on the raspberry pi.

Thank you in advance :)

Python code Oscilloscope reading

  • 1
    If you actually posted the code you are using (rather than a picture of if it) we might be able to try your code.
    – Milliways
    Oct 20, 2023 at 10:12
  • Have you made sure your CPU isn't being throttled due to power or temperature? Since you are using software PWM, CPU throttling could cause the slower frequency. vcgencmd get_throttled
    – mattexx
    Oct 20, 2023 at 16:39

1 Answer 1


I don't know why software PWM is quite so far off. I'd expect jitter but I'd expect the frequency to be closer.

Perhaps try pigpio.

Hardware PWM will be most accurate (but you must use one of GPIO 12/13/18/19).

General PWM if a frequency of 313 or 320 Hz will do (this will work on any GPIO).

For Python use the following command for a 300 Hz square wave on GPIO 12.

pi.hardware_PWM(12, 300, 500000) # 300Hz 50% dutycycle

See hardware_PWM.

  • Hi Joan, thank you for your response. What would the code look like for hardware PWM? I need to use BCM_12 (pin32) .
    – Ben
    Oct 20, 2023 at 12:09
  • Thanks Joan. I have now used hardware PWM and works perfectly!
    – Ben
    Nov 2, 2023 at 10:38

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.