Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Exercise for Chapter 8
- * When a button is pressed, it plays 4 tones
- * The Potentiometer can be used to control the duration that each note is played.
- * Author: James Wilkinson
- **/
- int speakerPin = 9;
- int sensorPin = 0; // select the input pin for the potentiometer
- int sensorValue = 0; // variable to store the value coming from the sensor
- // Button pins
- int inputPin1 = 2; // button 1
- int inputPin2 = 3; // button 2
- void playTone(int tone, int duration)
- {
- for (long i = 0; i < duration * 1000L; i += tone * 2)
- {
- digitalWrite(speakerPin, HIGH);
- delayMicroseconds(tone);
- digitalWrite(speakerPin, LOW);
- delayMicroseconds(tone);
- }
- }
- void playNote(char note, int duration) {
- char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
- int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
- // play the tone corresponding to the note name
- for (int i = 0; i < 8; i++) {
- if (names[i] == note) {
- playTone(tones[i], duration);
- }
- }
- }
- void setup() {
- pinMode(speakerPin, OUTPUT);
- pinMode(inputPin1, INPUT); // make button 1 an input
- pinMode(inputPin2, INPUT); // make button 2 an input
- }
- void loop()
- {
- // read the value from the Potentiometer sensor:
- sensorValue = analogRead(sensorPin);
- if (digitalRead(inputPin1) == LOW && digitalRead(inputPin1) == LOW)
- {
- playNote('c', sensorValue);
- }
- else if(digitalRead(inputPin1) == HIGH && digitalRead(inputPin2) == LOW)
- {
- playNote('g', sensorValue);
- }
- else if (digitalRead(inputPin1) == HIGH && digitalRead(inputPin2) == HIGH)
- {
- playNote('e', sensorValue);
- }
- else
- {
- playNote('b', sensorValue);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment