Hello,
I keep getting error of this program. The program is, if I push the button, the Ultrasonic Sensor will start to work and the Arduino will calculate the distance. I found this program in internet, but it won't work. Can someone help me? I'm new on this, thank you so much and sorry for my bad English.
/* HC-SR04 Ultrasonic Sensor
This sketch reads a HC-SR04 ultrasonic rangefinder and returns the
distance to the closest object in range. To do this, it sends a pulse
to the sensor to initiate a reading, then listens for a pulse
to return. The length of the returning pulse is proportional to
the distance of the object from the sensor.
The circuit:
* Vcc connection of the HC-SR04 attached to +5V
* GND connection of the HC-SR04 attached to ground
* Echo connection of the HC-SR04 attached to digital pin 3
* Trig connection of the HC-SR04 attached to digital pin 2
*/
// this constant won't change. It's the pin number
// of the sensor's output:
const int TrigPin = 2;
const int EchoPin = 3;
const int buttonPin = 2; // the number of the pushbutton pin
int buttonState = 0; // variable for reading the pushbutton status
long startTime ;
long elapsedTime ; // elapsed time for stop watch
int fractional; // variable used to store fractional part of time
long microsecondsToCentimeters;
long microseconds;
void setup() {
// initialize serial communication:
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
void loop()
{
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
}
else{
// establish variables for duration of the ping,
// and the distance result in centimeters:
long duration, cm;
// The HC-SR04 is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(TrigPin, OUTPUT);
digitalWrite(TrigPin, LOW);
delayMicroseconds(2);
digitalWrite(TrigPin, HIGH);
delayMicroseconds(5);
digitalWrite(TrigPin, LOW);
// The same pin is used to read the signal from the HC-SR04: a HIGH
// pulse whose duration is the time (in microseconds) from the sending
// of the ping to the reception of its echo off of an object.
pinMode(EchoPin, INPUT);
duration = pulseIn(EchoPin, HIGH);
// convert the time into a distance
cm = microsecondsToCentimeters(duration);
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
}