Jay_

Arduino Chapter 8

Mar 8th, 2013
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.70 KB | None | 0 0
  1. /**
  2. * Exercise for Chapter 8
  3. * When a button is pressed, it plays 4 tones
  4. * The Potentiometer can be used to control the duration that each note is played.
  5. * Author: James Wilkinson
  6. **/
  7.  
  8. int speakerPin = 9;
  9.  
  10. int sensorPin = 0;    // select the input pin for the potentiometer
  11. int sensorValue = 0;  // variable to store the value coming from the sensor
  12.  
  13.  
  14. // Button pins
  15. int inputPin1 = 2; // button 1
  16. int inputPin2 = 3; // button 2
  17.  
  18. void playTone(int tone, int duration)
  19. {
  20.   for (long i = 0; i < duration * 1000L; i += tone * 2)
  21.   {
  22.     digitalWrite(speakerPin, HIGH);
  23.     delayMicroseconds(tone);
  24.     digitalWrite(speakerPin, LOW);
  25.     delayMicroseconds(tone);
  26.   }
  27. }
  28.  
  29. void playNote(char note, int duration) {
  30.   char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  31.   int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
  32.  
  33.   // play the tone corresponding to the note name
  34.   for (int i = 0; i < 8; i++) {
  35.     if (names[i] == note) {
  36.       playTone(tones[i], duration);
  37.     }
  38.   }
  39. }
  40.  
  41. void setup() {
  42.   pinMode(speakerPin, OUTPUT);
  43.   pinMode(inputPin1, INPUT); // make button 1 an input
  44.   pinMode(inputPin2, INPUT); // make button 2 an input
  45.  
  46. }
  47.  
  48. void loop()
  49. {
  50.  
  51.   // read the value from the Potentiometer sensor:
  52.   sensorValue = analogRead(sensorPin);    
  53.  
  54.   if (digitalRead(inputPin1) == LOW && digitalRead(inputPin1) == LOW)
  55.   {
  56.     playNote('c', sensorValue);
  57.   }
  58.   else if(digitalRead(inputPin1) == HIGH && digitalRead(inputPin2) == LOW)
  59.   {
  60.     playNote('g', sensorValue);
  61.   }
  62.   else if (digitalRead(inputPin1) == HIGH && digitalRead(inputPin2) == HIGH)
  63.   {
  64.     playNote('e', sensorValue);
  65.   }
  66.   else
  67.   {
  68.     playNote('b', sensorValue);
  69.   }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment