/***************************************************************************************/
//Arduino Proficiency 00
//Use an ultrasonic sensor to control the output of 4 LEDs based on detected range
/***************************************************************************************/
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int redLed = 2;
const int blueLed = 3;
const int greenLed = 4;
const int yellowLed = 5;
// defines variables
const int buffersize = 10;
int buffer[buffersize] ;
int index;
long duration;
int distance;
int distance_in;
//function declarations
int average();
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(redLed,OUTPUT);
pinMode(blueLed,OUTPUT);
pinMode(greenLed,OUTPUT);
pinMode(yellowLed,OUTPUT);
Serial.begin(9600); // Starts the serial communication
}
void loop() {
int sensorAvg;
//Clear all LEDs
digitalWrite(redLed,LOW);
digitalWrite(blueLed,LOW);
digitalWrite(greenLed,LOW);
digitalWrite(yellowLed,LOW);
// 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
distance = duration * 0.034 / 2; //distance = speed of sound * time/2 |(speed of sound = 340 m/s =.034cm/microsecond)
//read average sensor value
sensorAvg = average();
// Prints the distance on the Serial Monitor
Serial.print("Distance in cm: ");
Serial.println(sensorAvg);
delayMicroseconds(10);
distance_in = sensorAvg * 0.393701; // 1cm = 0.393701 inch
// Prints the distance on the Serial Monitor
Serial.print("Distance in Inch: ");
Serial.println(distance_in);
if(distance_in>=4 && distance_in<=8)
{
digitalWrite(redLed,HIGH);
Serial.print("Range is 4-8 inches\n");
delay(1000);
}
else if(distance_in>=8 && distance_in<=12)
{
digitalWrite(blueLed,HIGH);
Serial.print("Range is 8-12 inches\n");
delay(1000);
}
else if(distance_in>=12 && distance_in<=16)
{
digitalWrite(greenLed,HIGH);
Serial.print("Range is 12-16 inches\n");
delay(1000);
}
else if(distance_in>=16 && distance_in<=20)
{
digitalWrite(yellowLed,HIGH);
Serial.print("Range is 16-20 inches\n");
delay(1000);
}
else
{
digitalWrite(redLed,LOW);
digitalWrite(blueLed,LOW);
digitalWrite(greenLed,LOW);
digitalWrite(yellowLed,LOW);
delay(1000);
Serial.print(" Not in range \n");
}
//update average buffer
buffer[index]=distance;
index++;
if(index>=buffersize)
{
index=0;
}
}
//sensor reading averaging function
int average()
{
long sum = 0;
int i;
int avg;
for(i=0;i<buffersize;i++)
{
sum += buffer[i] ;
}
avg = (sum/buffersize);
return avg;
}