Ultrasonic Example #1
This is example #1 for using the robot’s ultrasonic sensor. You can download the Arduino sketch (the .ino) file by clicking here.
Once downloaded, open the file in your Download folder, then save it to your “My Documents\Arduino” folder. It will create a folder in the Arduino with the same name as the filename and then it will save the file in the new folder.
Example:
Filename: “example.ino”
After saving in the Arduino folder the file will be located here:
“My Documents\Arduino\example\example.ino”
Code:
/*
NRG Ultrasonic Example
2019-09-24 R. Baas
This example uses the robot car's ultrasonic sensor to sense the distance
to a solid surface and to light the built-in LED on pin 13 when the
distance is less than 15 cm.
*/
// Pin definitions for ultrasonic sensor.
int Echo = A4;
int Trig = A5;
// Variable definitions.
int distance;
int trigger_distance = 15; // The distance below which the LED will light.
// Ultrasonic distance measurement function.
// Note this function starts with "int" and not "void" because
// it returns an integer value when called.
int Distance_test() {
digitalWrite(Trig, LOW); // This line and the next 4 tell the sensor to fire.
delayMicroseconds(10);
digitalWrite(Trig, HIGH);
delayMicroseconds(12);
digitalWrite(Trig, LOW);
float Fdistance = pulseIn(Echo, HIGH); // pulseIn gives the ammount of time
// it took to get the pulse back.
Fdistance = Fdistance/58; // Dividing by 58 converts the raw time into centemeters.
return (int)Fdistance; // Return an integer value of the distance.
}
void setup(){
// Start serial port (used for testing).
Serial.begin(9600);
// Tell the Arduino what pins are used for the ultrasonic sensor.
pinMode(Echo, INPUT);
pinMode(Trig, OUTPUT);
// initialize digital pin LED_BUILTIN (pin 13) as an output.
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
distance = Distance_test(); // Call the distance measuring function.
Serial.print("Distance= ");
Serial.println(distance);
// See if the distance to the surface is less than or equal to the trigger
// distance. If so, light the LED, if not, turn the LED off.
if (distance <= trigger_distance) {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
}
else {
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
}
// wait 1/2 of a second so as not to send massive amounts of data to the serial port.
delay(500);
}