//Create and Define Global Variables
int dipPins[] = {2, 3, 4, 5}; //DIP Switch Pins
int transAddress, dur;
//pin which triggers ultrasonic sound
const int pingPin = 13;
//pin which delivers time to receive echo using pulseIn()
int inPin = 12;
void setup()
{
Serial.begin(9600);
int i;
for(i = 0; i<=3; i++){
pinMode(dipPins[i], INPUT); // sets the digital pin 2-5 as input
digitalWrite(dipPins[i], HIGH); //Set pullup resistor on
}
transAddress = address();
delay(100);
}
void loop()
{
transAddress = address();
Serial.println(transAddress);
if (transAddress == 1){
dur = 2;
}
else if (transAddress == 3) {
dur = 10;
}
else {
dur = 20;
}
long duration, cm;
//initializing the pin states
pinMode(pingPin, OUTPUT);
//sending the signal, starting with LOW for a clean signal
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
//setting up the input pin, and receiving the duration in
//microseconds for the sound to bounce off the object infront
pinMode(inPin, INPUT);
duration = pulseIn(inPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
float inches = cm*(.3937);
int sound = map(inches,0,48,500,2500);
tone(9,sound,dur);
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
//Create Address from DIP Switch (4 positions used)
byte address(){
int i,j=0;
//Get the switches state
for(i=0; i<=3; i++){
j = (j << 1) | digitalRead(dipPins[i]); // read the input pin
}
return j; //return address
}