You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.4KB

  1. /*
  2. *@author James McKenzie
  3. *@lang C89 Based
  4. *@contact lunarised@outlook.com
  5. */
  6. int mode;
  7. void setup() {
  8. pinMode(6, INPUT_PULLUP); //Mode Select Pin
  9. pinMode (13, OUTPUT); //LED Indicator Pin
  10. pinMode(8, OUTPUT); //Speaker Pin
  11. pinMode (7, INPUT_PULLUP); //Play Pin
  12. pinMode(5, INPUT_PULLUP); //+Octave Play Pin
  13. Serial.begin (9600); //Set up a Serial Connection
  14. pinMode(11, OUTPUT); //Trigger pin
  15. pinMode(12, INPUT); //Echo pin
  16. }
  17. void loop() {
  18. if (digitalRead(6) ==HIGH){
  19. mode = 0;
  20. }else{
  21. mode = 1;
  22. }
  23. float note = 0;
  24. if (digitalRead(7) == LOW || digitalRead(5) == LOW){
  25. if (mode == 0){
  26. note = tune(getNote());
  27. }
  28. else{
  29. note = getNote();
  30. }
  31. if (digitalRead(5)==LOW){ //if the octave button is pressed
  32. note *= 2;
  33. }
  34. digitalWrite(13, HIGH);
  35. Serial.print(note); //print frequency
  36. Serial.println(" hz"); //print units after frequency
  37. tone(8, note);
  38. }
  39. else{
  40. noTone(8);
  41. }
  42. }
  43. /*
  44. * Method that uses an UltraSonic sensor to calculate a frequency
  45. * @return A Frequency generated by a sensor
  46. */
  47. float getNote(){
  48. float echoTime;
  49. float calculatedDistance;
  50. digitalWrite(11, HIGH);
  51. delayMicroseconds(20);
  52. digitalWrite(11, LOW);
  53. echoTime = pulseIn(12, HIGH);
  54. calculatedDistance = echoTime / 8; //Change this value to decrease
  55. //the playing physical range
  56. calculatedDistance += 110; //Minimum value
  57. if (calculatedDistance > 1760){ //Prevent high pitched sounds
  58. calculatedDistance = 1760; //Maximum Value
  59. }
  60. return calculatedDistance;
  61. }
  62. /*
  63. * Method which takes a note, and brings the note down to a correct pitch
  64. * @param toTune The Note in which you are autotuning
  65. * @return The Note that has now been autotuned
  66. */
  67. float tune(float toTune){
  68. if (toTune> 523.75){ //C5
  69. return 523.75;
  70. }
  71. if (toTune> 493.88){ //B4
  72. return 493.88;
  73. }
  74. if (toTune> 440){ //A4
  75. return 440;
  76. }
  77. if (toTune> 392){ //G4
  78. return 392;
  79. }
  80. if (toTune> 349.23){ //F4
  81. return 349.23;
  82. }
  83. if (toTune> 329.63){ //E5
  84. return 329.63;
  85. }
  86. if (toTune> 293.66){ //D4
  87. return 293.66;
  88. }
  89. if (toTune> 261.63){ //C4
  90. return 261.63;
  91. }
  92. if (toTune> 246.94){ //B3
  93. return 246.94;
  94. }
  95. if (toTune> 220){ //A3
  96. return 220;
  97. }
  98. if (toTune> 196){ //G3
  99. return 196;
  100. }
  101. if (toTune> 174.61){ //F3
  102. return 174.61;
  103. }
  104. }