1 /*
 2  * Beeper/booper via a controllable piezo.
 3  * Mahlon E. Smith <mahlon@martini.nu>
 4  * http://www.youtube.com/watch?v=HFU3PNuQn_k
 4  *
 5 */
 6 
 7 const int BUTTON_PIN  = 12;
 8 const int LED_PIN     = 13;
 9 const int SPEAKER_PIN = 5;
10 const int TONE_PIN    = 1;
11 const int TEMPO_PIN   = 0;
12 
13 // Tone boundaries, in Hz.
14 const int TONE_MIN = 0;
15 const int TONE_MAX = 3300;
16 
17 // Tempo speed, in milliseconds.
18 // Higher number == slower speed
19 const int TEMPO_MIN = 2000;
20 const int TEMPO_MAX = 10;
21 
22 int state = 0;
23 int buttonIs, buttonWas = 1;
24 
25 void setup()
26 {
27     randomSeed( analogRead(5) ); // unused analog port == noise
28 
29     pinMode( BUTTON_PIN, INPUT );
30     pinMode( LED_PIN, OUTPUT );
31     pinMode( SPEAKER_PIN, OUTPUT );
32 
33     startup();
34 }
35 
36 
37 void loop()
38 {
39     int tone_hz = constrain(
40             map( analogRead(TONE_PIN), 0, 1023, TONE_MIN, TONE_MAX ), TONE_MIN, TONE_MAX );
41     int tempo = constrain(
42             map( analogRead(TEMPO_PIN), 0, 1023, TEMPO_MIN, TEMPO_MAX ), TEMPO_MAX, TEMPO_MIN );
43 
44     // Button was pressed, bump the state.
45     // Need to do it in this fashion so if the button is held
46     // through 2 loop cycles, the state is only incremented once.
47     //
48     checkButton();
49     if ( buttonIs == 0 && buttonWas == 1 ) {
50         digitalWrite( LED_PIN, HIGH );
51         delay( 50 );
52         digitalWrite( LED_PIN, LOW );
53         state++;
54     }
55 
56     // Cycle the state back to the beginning (0 == off.)
57     if ( state > 2 ) state = 0;
58 
59     switch( state ) {
60         case 1:
61             tone( SPEAKER_PIN, tone_hz, tempo );
62             delay( tempo );
63             break;
64         case 2: // non stop random action
65             tone( SPEAKER_PIN, random( TONE_MIN, TONE_MAX ), tempo );
66             delay( tempo );
67             break;
68         // ... add more pre-programmed patterns and rhythms!
69         // case 3:
70         //  break;
71     }
72 }
73 
74 
75 /*
76  * Signal that we're ready, in state 0, by beeping/flashing thrice.
77  */
78 static void startup()
79 {
80     for ( int i = 0; i < 3; i ++ ) {
81         digitalWrite( LED_PIN, HIGH );
82         tone( SPEAKER_PIN, random( TONE_MIN, TONE_MAX ), 100 );
83         delay( 100 );
84         digitalWrite( LED_PIN, LOW );
85         delay( 100 );
86     }
87 }
88 
89 
90 /*
91  * Set the current state of the state-changing button.
92  */
93 static void checkButton()
94 {
95     buttonWas = buttonIs;
96     buttonIs  = digitalRead( BUTTON_PIN );
97 }
98