/* *@author James McKenzie *@lang C89 Based *@contact lunarised@outlook.com */ int mode; void setup() { pinMode(6, INPUT_PULLUP); pinMode (13, OUTPUT); pinMode(8, OUTPUT); pinMode (7, INPUT_PULLUP); Serial.begin (9600); //set up a serial connection with the computer pinMode(11, OUTPUT); //the trigger pin pinMode(12, INPUT); //echo pin } void loop() { if (digitalRead(6) ==HIGH){ mode = 0; }else{ mode = 1; } float note = 0; if (digitalRead(7) == LOW){ if (mode == 0){ note = tune(getNote()); } else{ note = getNote(); } digitalWrite(13, HIGH); Serial.print(note); //print units after the distance Serial.println(" hz"); //print units after the distance tone(8, note); } else{ noTone(8); } } float getNote() { float echoTime; float calculatedDistance; digitalWrite(11, HIGH); delayMicroseconds(20); digitalWrite(11, LOW); echoTime = pulseIn(12, HIGH); calculatedDistance = echoTime / 8; calculatedDistance += 110; if (calculatedDistance > 1760){ //git calculatedDistance = 1760; } return calculatedDistance; } float tune(float toTune){ if (toTune> 523.75){ //C5 return 523.75; } if (toTune> 493.88){ //B4 return 493.88; } if (toTune> 440){ //A4 return 440; } if (toTune> 392){ //G4 return 392; } if (toTune> 349.23){ //F4 return 349.23; } if (toTune> 329.63){ //E5 return 329.63; } if (toTune> 293.66){ //D4 return 293.66; } if (toTune> 261.63){ //C4 return 261.63; } if (toTune> 246.94){ //B3 return 246.94; } if (toTune> 220){ //A3 return 220; } if (toTune> 196){ //G3 return 196; } if (toTune> 174.61){ //F3 return 174.61; } }