Friday, May 11, 2018

Ultrasonic Sensor Code

This was developed by Washington-Lee (Drexel) intern Sam Muscovitz:

//defining the output and input pins
#define echoPin 7 //for reciving the sound waves from the ultrasound sensor
#define trigPin 8 //for outputting sound waves from the ultrasound sensor
#define LEDPin 11 //for turning on the LED

int maximumRange = 200;  //if the ultrasound sensor detects an object within the range of these two variables, it will display the object's distance
int minimumRange = 0;
long duration, distance;
void setup() {
 Serial.begin(9600);
 pinMode(trigPin, OUTPUT); //sets the trig pin to output
 pinMode(echoPin, INPUT); //sets the echopin to input signals
 pinMode(LEDPin, OUTPUT);
}
void loop() {
 digitalWrite(trigPin, LOW); //outputs a voltage of 0V to the trig pin
 delayMicroseconds(2); //delays the arduino for 2 microseconds
 digitalWrite(trigPin, HIGH); //outputs a voltage of 5V to the trig pin
 delayMicroseconds(10);
 digitalWrite(trigPin, LOW); //outputs a voltage of 0V to the trig pin
 duration = pulseIn(echoPin, HIGH); //Takes in the voltage from the echo pin
 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;
 if(distance >= maximumRange || distance <= minimumRange){ //checks the range that is returned from the ultrasound sensor
Serial.println("-1");
digitalWrite(LEDPin, LOW); //turns off the LED
 }
 else{
Serial.print(distance);
Serial.print(" cm");
Serial.println();
digitalWrite(LEDPin, HIGH); //turns on the LED
 }
 delay(50);
 }



Pictures of Arduino




Description of Wiring
Connect the Vcc pin on the ultrasound sensor to the 5.0V power on the arduino board
Connect the Trig pin on the ultrasound sensor to the Digital 8 pin on the arduino board
Connect the Echo pin on the ultrasound sensor to the Digital 7 pin on the arduino board
Connect the GND pin on the ultrasound sensor to the GND pin on the arduino board

Connect the positive end of the LED (the longer end) to Digital 11 pin on the arduino board
Connect the negative end of the LED (the shorter end) to GND pin on the arduino board

3 comments: