Code
/*
HC-SR04 for Arduino
Original project from http://www.swanrobotics.com
This project demonstrates the HC-SR
The distance presented in the code is in mm, but you can uncomment the line
for distance in inches.
The schematics for this project can be found on http://www.swanrobotics.com
This example code is in the public domain.
*/
const int TriggerPin = 8;
const int EchoPin = 9;
long Duration = 0;
void setup(){
pinMode(TriggerPin,OUTPUT);
pinMode(EchoPin,INPUT);
Serial.begin(9600);
}
void loop(){
digitalWrite(TriggerPin, LOW);
delayMicroseconds(2);
digitalWrite(TriggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(TriggerPin, LOW);
Duration = pulseIn(EchoPin,HIGH);
high
microseconds
long Distance_mm = Distance(Duration);
distance
Serial.print("Distance = ");
Serial.print(Distance_mm);
Serial.println(" mm");
delay(1000);
}
long Distance(long time)
{
// Calculates the Distance in mm
// ((time)*(Speed of sound))/ toward and backward of object) * 10
long DistanceCalc;
DistanceCalc = ((time /2.9) / 2);
//DistanceCalc = time / 74 / 2;
return DistanceCalc;
}
oddWires
//Trig pin
//Echo pin
// Trigger is an output pin
// Echo is an input pin
// Serial Output
// Trigger pin to HIGH
// 10us high
// Trigger pin to HIGH
// Waits for the echo pin to get
// returns the Duration in
// Use function to calculate the
// Output to serial
// Wait to do next measurement
// Calculation variable
// Actual calculation in mm
// Actual calculation in inches
// return calculated value
13
Arduino Robotics Kit
Need help?
Do you have a question about the Arduino Robotics Kit With Motor Shield and is the answer not in the manual?