1

I have my pi hooked up to a shaking device, and I'm looking to drive it at relatively low frequencies. My code looks like this:

# Import the necessary header modules
import RPi.GPIO as GPIO
from time import sleep

## Setup the GPIO for PWM on pin12 {GPIO18}
Hz = 1
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
p = GPIO.PWM(12, Hz)
p.start(50)
raw_input("Press Enter key to Stop")
GPIO.cleanup()

But when I tested it out at 1 Hz, the frequency that was coming out of the shaker was too quick (I'd say closer to 2 Hz). I'm only testing it by ear, so can't really test it at higher frequency, but I'm confident I can discern a 1 Hz beat, and the Pi seems to be putting out a beat that is too quick. Any thoughts on how to fix this?

Vinterwoo
  • 113
  • 3
  • 1
    read this https://raspberrypi.stackexchange.com/questions/4906/control-hardware-pwm-frequency – jsotola Jun 25 '18 at 01:25

2 Answers2

3

Use hardware PWM. There are two channels on the Pi. One channel is available from GPIO 12 and/or 18, the other channel is available from GPIO 13 and/or 19.

pigpio and wiringPi both support hardware PWM. pigpio only supports an integral number of Hz (1, 2, 3, ...).

pigpio also supports other forms of hardware timed PWM (not so flexible as fully hardware PWM), but which still may be suitable.

joan
  • 71,024
  • 5
  • 73
  • 106
2

Pulse width modulation (PWM) is designed to send information at a fixed frequency. Information is sent by modulating (i.e., changing or setting) the pulse width. In PWM, the modulation is the duty cycle. In your code, you specify the frequency as 1HZ. And you specify the duty cycle as 50%. This means that something changes every half second:

ON ...0.5s... OFF ...0.5s... ON ... etc.

If your thumper makes sound when turned on AND when turned off, you will hear a 2Hz frequency because...something is changing every half second. Given this behavior, you can: 1) halve the frequency GPIO.PWM(12,0.5*Hz), or 2) change the duty cycle to make either the on or off pulse shorter (e.g., p.start(1))

OyaMist
  • 1,119
  • 6
  • 8
  • So hardware pwm aside, if I set my duty cycle to 1 AKA p.start(1) I should get my 1x per sec beat with the above code. Is there a default where I can just enter the frequency in Hz without having to also enter a duty cycle? Say if I wanted a 20 Hz signal? – Vinterwoo Jun 26 '18 at 05:01
  • @Vinterwoo Edited answer with two solutions including one suggested by you. – OyaMist Jun 26 '18 at 15:16