/*
 * DistanceHat by Ashemah Harrison
 * 
 * Reads a sharp distance sensor
 * and turns the value into light and sound
 *
 * Originally based off:
 *
 * AnalogInput
 * by DojoDave <http://www.0j0.org>
 * http://www.arduino.cc/en/Tutorial/AnalogInput
 *
 * Use anything below for anything -Ash
 */

int speakerPin = 8;	   // buzzer pin
int potPin     = 0;    // select the input pin for the potentiometer
int ledPin     = 13;   // select the pin for the LED
int val        = 0;    // variable to store the value coming from the sensor
int count      = 0;    // loop count
int mappedVal  = 0;    // converted value
int lastVal    = 0;    // the last value we stored

void setup() {
  pinMode(ledPin,   OUTPUT);
  pinMode(speakerPin, OUTPUT);
  
  Serial.begin(19200);
  count = 0;
}

// Stuff taken from the arduino playground playtone code
void playTone(int val) {
  digitalWrite(ledPin, HIGH);
  digitalWrite(speakerPin, LOW);     
  for (count=0;count<=8;count++) 
  {
      digitalWrite(speakerPin, HIGH);
      delayMicroseconds(val);
      digitalWrite(speakerPin, LOW);
      delayMicroseconds(val);
  }  
  digitalWrite(ledPin, LOW);
}

// The looooop

void loop() {
  val = analogRead(potPin);    // read the value from the sensor
  
  if(val <= 3) val = 4;
  
  mappedVal = (6787 / (val - 3)) - 4;	// this converts the normally non-linear value into a more linear value
  /*
	This value was directly taken from here:
	http://www.acroname.com/robotics/info/articles/irlinear/irlinear.html  
	
	Ideally you would calc one that makes sense for your sensor but I just copied this one for speed
  */
  
  mappedVal = mappedVal * 100;			// This multiplies the value to make it slower 
  
  // If the loop count if big enough OR the distance is shorter than it was before
  if(count > lastVal || mappedVal < count)
  {
    playTone(2000); 			// play the tone
    Serial.println(mappedVal);	// also output the value to the serial port
    lastVal = mappedVal;		// store the new value - slightly misleading name sorry :)
    count = 0;					// reset the count
    delay(10);					// slight delay
  }
  
  count++;						// increment the count
}


