Two LED projects for light and sound
Line 17-28 – The Rumble Function
The rumble function creates multiple smaller flashes. Here, lightning1
and lightning2
are the same PWM objects from the strike
function, and brightness
and cycles
are passed through from the strike
function as well. This is how bright and how long to create smaller strikes.
On line 18, I set up a loop for the number of cycles requested. Lines 19 and 20 generate two random numbers between 0
and brightness
. Lines 22 and 24 set the lightning panels to this random brightness with a 0.03-second pause in between (line 23); then, after a second 0.03-second pause (line 25), the loop begins again. When the number of cycles has been completed (the loop completes), lines 27 and 28 shut off the lightning panels by setting the PWM duty cycle to 0
.
Lines 31-47 – Program Setup
On line 31, I define the GPIO mode as BCM
. The GPIO on the Raspberry Pi can be set up in two ways: either by the numbering on the processor chip itself or by the numbering on the Raspberry Pi silkscreen; BCM
selects the chip numbering.
Lines 33 and 34 define two GPIO output pins. Although GPIO pins 8 and 25 are well apart in the pin count, they are next to each other on the Pi itself (pins 22 and 24). Line 36 defines pin 7 as an input. This is where the beam break sensor connects. The pull_up_down=GPIO.PUD_UP
statement says to pull the GPIO up to HIGH. This provides a physical default value for the GPIO pin.
Lines 38 and 39 set up the PWM generator for the two output pins. GPIO.PWM ( 8 , 500 )
says to set up PWM on pin 8 with a cycle time of 500Hz (500 cycles per second). The "PWM" box has more details on what a PWM signal actually looks like.
Lines 41 and 42 start generating the PWM signal. Until this function is called, the output pins will remain LOW. Passing a 0
to this function says the initial output state is off. This could be a value up to 100
, which is the duty cycle – or the percentage of time the pin is in a HIGH state.
Lines 44 and 45 initialize the PyGame mixer object. I call it twice because of a problem I experienced some time ago when the mixer object didn't initialize the first time. I researched the problem online and found that the recommended fix was just to initialize it again, so now it's become a programming habit for me, even if it's not strictly necessary.
Line 47 creates a sound object and loads the .wav
file that has the thunder sound effect.
Buy this article as PDF
Pages: 5
(incl. VAT)