2
votes

I have a simple Python program running on a Pi 2. I can't seem to figure out why the output frequency is way off. I have it programmed for 2000hz. I measure the output two ways and both yield 1530 Hz.

Since I use pin 18, I believe I should be using the hardware PWM. Any suggestions, what am I missing.

Here's the code

 import time
import sys
import datetime
import RPi.GPIO as GPIO


def tonet(hz,s):
    pt = GPIO.PWM(tone,hz)
    pt.start(50)        # duty cycle
    time.sleep(s)
    pt.stop
    GPIO.output(tone, GPIO.LOW)  # good house keeping
    return


# Pin Definitons:
tone = 18 #

# Pin Setup:
GPIO.setmode(GPIO.BCM) # Broadcom pin-numbering scheme
GPIO.setup(tone, GPIO.OUT) #  pin set as output
GPIO.output(tone, GPIO.HIGH)
pause = raw_input('high   press a key')
GPIO.output(tone, GPIO.LOW)
pause = raw_input('low  press a key....')

print 'start pwm'


tonet(2000, 20)

GPIO.cleanup()
2

2 Answers

0
votes

I think the pins 12 and 24 (BOARD numberingscheme) are hardware PWM capable, hence more accurate.

0
votes

Broadcom pin #18 is a PWM hardware pin on Raspberry Pi 2 and 3. However the question is how does the interface library you are using support the PWM hardware on the Pi 2.

Reading this Raspberry Pi StackExchange posting's answer, it appears that the RPIO library may have some PWM inaccuracy, at least at the time of the answer in 2012.

Can I use the GPIO for pulse width modulation (PWM)?

As suggested by Alex Chamberlain, the WiringPi library appears to support both hardware PWM output on one GPIO pin and software PWM on any of the other GPIO pins. Meanwhile the RPIO.PWM library does PWM by DMA on any GPIO pin. Effectively this is a halfway house between hardware and software PWM, providing a 1 µs timing resolution compared to 100 µs with WiringPi's Software PWM[1].

Which of these is suitable for your applications depends on how many PWM outputs you need and what performance you want out of those outputs.

If your application is tolerant of low-timing resolution and high jitter then you could use a software or DMA assisted timing loop. If you want higher precision / lower jitter PWM then you may need hardware assistance.

Also see this Raspberrypi.org forum discussion from 2013. RPIO.PWM: Precise PWM via DMA for servos and more (1µs res)

Also I seem to remember that the headphone jack audio can interfere with PWM usage as the circuitry is shared between the two. This should only be a problem if you are using the jack.