#include <toneAC.h>
// defines pins numbers
const int trigPin = 6;
const int echoPin = 5;
int toneFreq = 0;
int toneMin = 400;
int toneMax = 4000;
// defines variables
long delayTime;
long minDelay = 50;
long maxDelay = 1000;
int distanceDelay;
int volume = 10;
// Distance (current and previous) along with error checking so it doesn't change constantly
int distance = 0;
int prevDistance = 0;
int errorDistance = 3;
int duration = 0;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
prevDistance = distance;
distance = duration * 0.034 / 2;
toneFreq = map(distance, 2, 200, toneMax, toneMin);
toneFreq = constrain(toneFreq, toneMin, toneMax);
delayTime = map(distance, 2, 200, minDelay, maxDelay);
delayTime = constrain(delayTime, minDelay, maxDelay);
// Prints the distance on the Serial Monitor
if(distance > 1 && distance < 400) {
toneFreq = map(distance, 10, 400, 2000, 400);
Serial.println(toneFreq);
toneAC(toneFreq, volume);
}
delay(delayTime);
noToneAC();
delay(delayTime);
if(distance != prevDistance) {
Serial.print("Distance: ");
Serial.println(distance);
}
delay(1000);
}