Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Implementing a 2-mode "Audiobutton" on the Raspberry Pi

by cavac (Curate)
on Oct 25, 2018 at 10:40 UTC ( #1224652=CUFP: print w/replies, xml ) Need Help??

Some time ago, i saw those fake "emergency stop" buttons on Amazon that play a funny audio sample when you press them. But they were too expensive and - much more important - you can't change the sound on them. So i implemented my own.

First i hooked up a real (non-latching) emergency button to a Raspberry Pi GPIO pin and a set of rather ancient and crappy Desktop speakers to the analog out of the Pi. I also prepared some audio files in raw format: Decoding MP3 costs performance, so it is not as instantaneous as playing a raw file, also the Pi runs some other performance critical stuff and using raw files instead of wav/mp3 fixed some timing issues.

List of audio files (not uploading them here due to copyright):

  • bullshit1.raw
  • bullshit2.raw
  • bullshit3.raw
  • jeopardy.raw

And here is the script that ties it all together:

#!/usr/bin/env perl #---AUTOPRAGMASTART--- use 5.012; use strict; use warnings; use diagnostics; use mro 'c3'; use English qw( -no_match_vars ); use Carp; our $VERSION = 1.5; no if $] >= 5.017011, warnings => 'experimental::smartmatch'; #---AUTOPRAGMAEND--- no utf8; use Device::BCM2835; use Time::HiRes qw[sleep alarm time]; use Data::Dumper; # Make sure the process name is maplat_failbutton $0 = 'maplat_failbutton'; my $SHUTDOWN = 0; $SIG{INT} = sub{print "GOT SIGINT, exiting...\n"; $SHUTDOWN=1;}; $SIG{TERM} = sub{print "GOT SIGTERM, exiting...\n"; $SHUTDOWN=1;}; if(!Device::BCM2835::init()) { die("Can't open device!"); } my $testpinnumber = 13; # BCM internal pin number; 21 = GPIO Pin 40 my $sndidx = 1; # Select as input device Device::BCM2835::gpio_fsel($testpinnumber, &Device::BCM2835::BCM2835_G +PIO_FSEL_INPT); # Select Pull up resistor mode Device::BCM2835::gpio_set_pud($testpinnumber, &Device::BCM2835::BCM283 +5_GPIO_PUD_UP); my $lastswitch = -1; # "Unknown" my $lastswitchtime = time; while(!$SHUTDOWN) { my $switch = Device::BCM2835::gpio_lev($testpinnumber); if($switch != $lastswitch) { my $now = time; print "SWITCH SET TO $switch\n"; if($lastswitch == -1) { $lastswitch = $switch; sleep(0.5); next; } $lastswitch = $switch; if($switch) { print "Switch pressed...\n"; $lastswitchtime = $now; } else { my $cmd; my $presslength = $now - $lastswitchtime; print "PL: $presslength\n"; if($presslength < 0.8) { print " short click\n"; $cmd = '/usr/bin/aplay -r 44100 -f S16_LE /home/cavac/ +src/maplat_failalert/bullshit' . $sndidx . '.raw'; $sndidx++; if($sndidx == 4) { $sndidx = 1; } } else { print " long click\n"; $cmd = '/usr/bin/aplay -r 44100 -f S16_LE /home/cavac/ +src/maplat_failalert/jeopardy.raw'; } print "Running $cmd\n"; `$cmd`; print "...done.\n"; } } sleep(0.1); }

A short button press plays one of the 3 "bullshit detected" samples. Holding the button for about 1 second before releasing plays the 30 second jeopardy "thinking" music.

Note: This is actually the "dumb" version of the script. My local implementation also triggers some LED display for the bullshit alerts and runs an analog meter (via an Arduino) from 100% to 0% while the jeopardy music ticks down the seconds.

perl -e 'use MIME::Base64; print decode_base64("4pmsIE5ldmVyIGdvbm5hIGdpdmUgeW91IHVwCiAgTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duLi4uIOKZqwo=");'

Replies are listed 'Best First'.
Re: Implementing a 2-mode "Audiobutton" on the Raspberry Pi
by holli (Abbot) on Oct 26, 2018 at 08:17 UTC
    if($lastswitch == -1) {

    Magic numbers are bad. Here's why.


    You can lead your users to water, but alas, you cannot drown them.

      In many cases, yes, you are right. But in this case, at least in my opinion, the usage is quite clear. The switch could either be on (1) or off(0) or we don't know yet (-1 = number that could never happen otherwise). And i even bothered to document it:

      my $lastswitch = -1;

      The whole $lastswitch thing could just be set to 0 on startup in theory (guessing the button isn't pressed on startup). Or i could just replicate the Device::BCM2835::gpio_lev($testpinnumber) call at the beginning.

      I just kept this one-off script for my one-off device to my usual style guide of 15+ years of Perl coding. If i see that construct, i instantly know i'm dealing with an uninitialized boolean. Same goes for other "magic" numbers. 3600 is seconds per hour, 86400 is seconds per day and 365.25 is (average) days per year.

      Those kinds of magic numbers i wouldn't call "bad", it's more of a grey area.

      I can completely understand your point of view, and in most cases i'd support you all the way, but i hereby invoke my right of TIMTOWTDI 😉

      perl -e 'use MIME::Base64; print decode_base64("4pmsIE5ldmVyIGdvbm5hIGdpdmUgeW91IHVwCiAgTmV2ZXIgZ29ubmEgbGV0IHlvdSBkb3duLi4uIOKZqwo=");'
        3600 is seconds per hour, 86400 is seconds per day

        Yesterday in the UK we had 90,000 seconds. In the hour from 1am to 2am we had 7200 seconds. Magic numbers will get you in the end.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: CUFP [id://1224652]
Approved by marto
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (6)
As of 2021-04-19 09:08 GMT
Find Nodes?
    Voting Booth?

    No recent polls found