Day 5: (Wed Sep 11) Switch Sensors

Notes for 2019-09-11. See also the Fall 2019 Calendar.

Notes from Day 4

Agenda

  1. Administrative

  2. Assignments

  3. In-class

Lecture code samples

(See also Lecture Sample Code).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 1. read a switch input on pin 9
// 2. generate tones on a speaker on pin 5
// 3. demonstrate a simple state machine
// 4. demonstrate Serial debugging

const int SWITCH_PIN  = 9;
const int SPEAKER_PIN = 5;

void setup()
{
  Serial.begin(115200);
  Serial.println("Hello!");
}

const float note_table[] = { 440.0, 523.25, 659.26, 523.25, 659.26, 523.25/2, 440.0, 659.26, 659.26*2, 523.25, -1 };

int nextnote = 0;

/// The loop function is called repeatedly by the Arduino system.  In this
/// example, it executes once per cycle of the switch input.
void loop()
{
  while(digitalRead(SWITCH_PIN) != 0) {
    // Busywait for the switch to be pressed.  Note that the body of the while
    // is empty, this just loops reading the switch input until it goes low.
  }

  // The following is executed once per switch cycle, right after the switch is pressed.
  float freq = note_table[nextnote];
  Serial.print("Note: ");
  Serial.println(freq);
  tone(SPEAKER_PIN, freq);

  // advance to the next note, looping at the end
  nextnote = nextnote + 1;
  if (note_table[nextnote] < 0) nextnote = 0;

  // Busywait for the switch to be released: loop until the switch input goes high.  
  while(digitalRead(SWITCH_PIN) == 0) {  }

  // The following is executed once, right after the switch is released.
  noTone(SPEAKER_PIN);
}