SoundDemo Arduino Sketch

This sketch is used by Exercise: Multichannel Bipolar Transistor Driver.

Full Source Code

The full code is all in one file SoundDemo.ino.

 1// SoundDemo - generate sound using a speaker and pager motor
 2//
 3// Copyright (c) 2016, Garth Zeglin.  All rights reserved. Licensed under the
 4// terms of the BSD 3-clause license as included in LICENSE.
 5//
 6// This program assumes that:
 7//
 8//  1. A speaker is connected to pin 5 via a suitable driver.
 9//  2. A vibratory motor is connected to pin 6 via a suitable driver.
10//  3. The serial console on the Arduino IDE is set to 9600 baud communications speed.
11
12// ================================================================================
13// Define constant values.
14
15// The wiring assignment.
16const int SPEAKER_PIN = 5;
17const int MOTOR_PIN = 6;
18
19// ================================================================================
20// Configure the hardware once after booting up.  This runs once after pressing
21// reset or powering up the board.
22
23void setup()
24{
25  // Initialize the serial UART at 9600 bits per second.
26  Serial.begin(9600);
27
28  // Initialize the outputs.
29  pinMode(SPEAKER_PIN, OUTPUT);
30  digitalWrite(SPEAKER_PIN, LOW);
31  pinMode(MOTOR_PIN, OUTPUT);
32  digitalWrite(MOTOR_PIN, LOW);
33}
34// ================================================================================
35// Run one iteration of the main event loop.  The Arduino system will call this
36// function over and over forever.
37void loop()
38{
39  // play a siren tone
40  for(int i = 0; i < 4; i++) {
41    tone(SPEAKER_PIN, 622);
42    delay(500);
43    tone(SPEAKER_PIN, 440);
44    delay(500);
45  }
46  noTone(SPEAKER_PIN);
47  
48  // buzz a simple rhythm
49  for(int i = 0; i < 4; i++) {
50    digitalWrite(MOTOR_PIN, HIGH);
51    delay(450);
52    digitalWrite(MOTOR_PIN, LOW);
53    delay(50);
54    digitalWrite(MOTOR_PIN, HIGH);
55    delay(450);
56    digitalWrite(MOTOR_PIN, LOW);
57    delay(50);
58    digitalWrite(MOTOR_PIN, HIGH);
59    delay(200);
60    digitalWrite(MOTOR_PIN, LOW);
61    delay(50);
62    digitalWrite(MOTOR_PIN, HIGH);
63    delay(200);
64    digitalWrite(MOTOR_PIN, LOW);
65    delay(50);
66  }
67
68  // Play a simple melody, using a pitch table for more concise code.
69  // The following line declares an immutable table of integers.
70  const int pitches[] = { 262, 330, 392, 523, 494, 440, 392, 349, 330, 294, 262, -1 };
71
72  // Loop through the table.  The break statement will exit this loop, so the
73  // continuation test is empty, which will be treated as 'true'.
74  for(int i = 0; /* note: empty */ ; i++) {
75    int pitch = pitches[i];
76
77    // Once the end marker is seen (an invalid pitch), exit the loop.
78    if (pitch < 0) break;
79
80    // Otherwise, play the tone
81    tone(SPEAKER_PIN, pitch);
82    delay(250);
83  }
84  noTone(SPEAKER_PIN);
85  
86  // blissful silence
87  delay(2000);
88}