In this demo the tone of the sound being output by the speaker changes depending on the user’s hand orientation using a tilt sensor.

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
//define constants
const int tiltsensor = A0;     // analog tilt sensor input pin
const int speakerPin = 2;      // speaker digital output pin
 
// define changing variables:
int tiltState = 0;         // variable for reading tilt orientation
 
void setup() {
  // tilt sensor set to input
  pinMode(tiltsensor, INPUT);
  // speaker set to output
  pinMode(speakerPin, OUTPUT);
}
 
void loop() {
  // read the orientation of the tilt sensor:
  tiltState = digitalRead(tiltsensor);
 
  if (tiltState == HIGH) {
    // make speaker tone low pitched: sensor oriented down
    tone(speakerPin, 300);
  }
  else {
    // make speaker tone high pitched: sensor oriented up
    tone(speakerPin, 700);
  }
}