daily pastebin goal
62%
SHARE
TWEET

Untitled

a guest Dec 21st, 2017 116 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int speakerPin = 10, length = 26, tempo = 300, duration, distance;
  2. int beats[] = { 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2};
  3. char notes[] = "eeeeeeegcde";
  4. const int trigPin = 5;
  5. const int echoPin = 4;
  6. const int trigDistance = 100;
  7.  
  8. void playTone(int tone, int duration);
  9. void playNote(char note, int duration);
  10.  
  11. void setup() {
  12.   pinMode(speakerPin, OUTPUT);
  13.   pinMode(trigPin, OUTPUT);
  14.   pinMode(echoPin, INPUT);
  15. }
  16. void loop() {
  17.   digitalWrite(trigPin, LOW);
  18.   digitalWrite(trigPin, HIGH);
  19.   delay(1);
  20.   digitalWrite(trigPin, LOW);
  21.   duration = pulseIn(echoPin, HIGH);
  22.   distance = duration * 0.034 / 2;
  23.  
  24.   if (distance <= trigDistance) {
  25.    
  26.     for (int i = 0; i < length; i++) {
  27.       if (notes[i] == ' ') {
  28.         delay(beats[i] * tempo);
  29.       } else {
  30.         playNote(notes[i], beats[i] * tempo);
  31.       }
  32.       delay(tempo / 2);
  33.     }
  34.   }
  35.   delay(10000);
  36. }
  37.  
  38. void playTone(int tone, int duration) {
  39.   for (long i = 0; i < duration * 1000L; i += tone * 2) {
  40.     digitalWrite(speakerPin, HIGH);
  41.     delayMicroseconds(tone);
  42.     digitalWrite(speakerPin, LOW);
  43.     delayMicroseconds(tone);
  44.   }
  45. }
  46. void playNote(char note, int duration) {
  47.   char names[] = { 'c', 'd', 'e', 'f', 'g', 'a', 'b', 'C' };
  48.   int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014, 956 };
  49.   for (int i = 0; i < 8; i++) {
  50.     if (names[i] == note) {
  51.       playTone(tones[i], duration);
  52.     }
  53.   }
  54. }
RAW Paste Data
Top