Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. /*
  2. Melody
  3.  
  4. Plays a melody
  5.  
  6. circuit:
  7. - 8 ohm speaker on digital pin 8
  8.  
  9. created 21 Jan 2010
  10. modified 30 Aug 2011
  11. by Tom Igoe
  12.  
  13. This example code is in the public domain.
  14.  
  15. http://www.arduino.cc/en/Tutorial/Tone
  16. */
  17.  
  18. #include "pitches.h"
  19.  
  20. int melody[] = {
  21. NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4, NOTE_F4, NOTE_F4, NOTE_E4,
  22. NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4};
  23. // note durations: 4 = quarter note, 8 = eighth note, etc.:
  24. int noteDurations[] = {
  25. 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 4 };
  26.  
  27. int buzzerPin = 9;
  28. void setup() {
  29. }
  30.  
  31. void loop() {
  32.  
  33. // iterate over the notes of the melody:
  34. for (int thisNote = 0; thisNote < 8; thisNote++) {
  35. int sensorReading = analogRead(A0);
  36. int thisPitch = map(sensorReading, 400, 1000, 1800, 100);
  37.  
  38. // to calculate the note duration, take one second divided by the note type.
  39. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
  40. int noteDuration = thisPitch / noteDurations[thisNote];
  41.  
  42. // to distinguish the notes, set a minimum time between them.
  43. // the note's duration + 30% seems to work well:
  44. int pauseBetweenNotes = noteDuration / 1.30;
  45. tone(9, melody[thisNote], noteDuration);
  46. delay(pauseBetweenNotes);
  47.  
  48. Serial.println(sensorReading);
  49. Serial.println(thisPitch);
  50.  
  51. if (pauseBetweenNotes > 100) {
  52. noTone(9, melody[thisNote], noteDuration);
  53. }
  54. }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement