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.

106 lines
1.9KB

  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);
  9. pinMode (13, OUTPUT);
  10. pinMode(8, OUTPUT);
  11. pinMode (7, INPUT_PULLUP);
  12. pinMode(5, INPUT_PULLUP);
  13. Serial.begin (9600); //set up a serial connection with the computer
  14. pinMode(11, OUTPUT); //the 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. float getNote()
  44. {
  45. float echoTime;
  46. float calculatedDistance;
  47. digitalWrite(11, HIGH);
  48. delayMicroseconds(20);
  49. digitalWrite(11, LOW);
  50. echoTime = pulseIn(12, HIGH);
  51. calculatedDistance = echoTime / 8;
  52. calculatedDistance += 110;
  53. if (calculatedDistance > 1760){ //git
  54. calculatedDistance = 1760;
  55. }
  56. return calculatedDistance;
  57. }
  58. float tune(float toTune){
  59. if (toTune> 523.75){ //C5
  60. return 523.75;
  61. }
  62. if (toTune> 493.88){ //B4
  63. return 493.88;
  64. }
  65. if (toTune> 440){ //A4
  66. return 440;
  67. }
  68. if (toTune> 392){ //G4
  69. return 392;
  70. }
  71. if (toTune> 349.23){ //F4
  72. return 349.23;
  73. }
  74. if (toTune> 329.63){ //E5
  75. return 329.63;
  76. }
  77. if (toTune> 293.66){ //D4
  78. return 293.66;
  79. }
  80. if (toTune> 261.63){ //C4
  81. return 261.63;
  82. }
  83. if (toTune> 246.94){ //B3
  84. return 246.94;
  85. }
  86. if (toTune> 220){ //A3
  87. return 220;
  88. }
  89. if (toTune> 196){ //G3
  90. return 196;
  91. }
  92. if (toTune> 174.61){ //F3
  93. return 174.61;
  94. }
  95. }