Getting Distance in Inches and Cm from Ultrasonic Sensor in Arduino - arduino

I am tinkering with a simple Arduino sketch that detects distances using an ultrasonic sensor. From what I've understood, the trigger sends a ping. The echo listens for an echo that comes back to calculate the distance. This is measured in microseconds.
If that is correct, the question is, how can one determine inches and cm from that ping (that is given in microseconds)? Is this just basic math/physics, and is there just a basic formula for this?
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
This is the part that I'm having issues with. I want to divide ping time from microseconds to inches and then cm:
distance_in = duration ????;
distance_cm = duration ????;
Serial.print(distance_in);
Serial.print(" in, ");
Serial.print(distance_cm);
Serial.print(" cm");
Serial.println();
delay(1500);
}
Any help, with as much explanation as possible would be appreciated. I'm a newbie to Arduino (and not a heavy-lifter in math)

distance_cm = ( duration / 29 ) / 2;
distance_in = distance_cm * 0,393701;
1 m/s = 100/1000000 = 0.0001 cm/μs
343 m/s = 0.0001 * 343 = 0.0343 cm/μs
0.0343 cm/μs = 1 / 0.0343 = 29.155 μs/cm
Sound travels at 343 meters per second, which means it needs 29.155 microseconds per centimeter. So, we have to divide the duration by 29 and then by 2, because the sound has to travel the distance twice. It travels to the object and then back to the sensor.
1 cm = 0,393701 in

The best article I have found on this subject is actually at Arduino. https://www.arduino.cc/en/Tutorial/Ping
/* Ping))) Sensor
This sketch reads a PING))) 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:
* +V connection of the PING))) attached to +5V
* GND connection of the PING))) attached to ground
* SIG connection of the PING))) attached to digital pin 7
http://www.arduino.cc/en/Tutorial/Ping
created 3 Nov 2008
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
*/
// this constant won't change. It's the pin number
// of the sensor's output:
const int pingPin = 7;
void setup() {
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, inches, cm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// The same pin is used to read the signal from the PING))): 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(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in, ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
delay(100);
}
long microsecondsToInches(long microseconds) {
// According to Parallax's datasheet for the PING))), there are
// 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
// second). This gives the distance travelled by the ping, outbound
// and return, so we divide by 2 to get the distance of the obstacle.
// See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
return microseconds / 74 / 2;
}
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;
}

Related

Pulsein() function blocks other tasks from running silmultaneously

I am using a zumo bot with a reflectance sensor used to follow a black line. I want to use an arduino to make the zumo bot stop once it gets a certain distance from an obstacle.
I have an ultrasonic sensor (HC-SR04) which ive connected to the bot.
Both of these tasks work independently but once i merge the code together(so it follows the line aswell as stoping when it detects an object using the ultrasonic sensor), it doesn't work properly.. (the zumo bot no longer follows the line)
I THINK it is to do with the pulsein() function blocking any other tasks but not sure.
My code is below. Can anyone help please?
#include <ZumoShield.h>
ZumoBuzzer buzzer;
ZumoReflectanceSensorArray reflectanceSensors;
ZumoMotors motors;
Pushbutton button(ZUMO_BUTTON);
int lastError = 0;
// This is the maximum speed the motors will be allowed to turn.
// (400 lets the motors go at top speed; decrease to impose a speed limit)
const int MAX_SPEED = 400;
#define echoPin A4
#define trigPin A5
// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
void setup()
{
reflectanceSensors.init();
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
// Initialize the reflectance sensors module
// Wait for the user button to be pressed and released
button.waitForButton();
// Turn on LED to indicate we are in calibration mode
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
// Wait 1 second and then begin automatic sensor calibration
// by rotating in place to sweep the sensors over the line
delay(1000);
int i;
for(i = 0; i < 80; i++)
{
if ((i > 10 && i <= 30) || (i > 50 && i <= 70))
motors.setSpeeds(-200, 200);
else
motors.setSpeeds(200, -200);
reflectanceSensors.calibrate();
// Since our counter runs to 80, the total delay will be
// 80*20 = 1600 ms.
delay(20);
}
motors.setSpeeds(0,0);
// Turn off LED to indicate we are through with calibration
digitalWrite(13, LOW);
// Wait for the user button to be pressed and released
button.waitForButton();
Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
Serial.println("with Arduino UNO R3");
}
void loop()
{
unsigned int sensors[6];
// Get the position of the line. Note that we *must* provide the "sensors"
// argument to readLine() here, even though we are not interested in the
// individual sensor readings
int position = reflectanceSensors.readLine(sensors);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Our "error" is how far we are away from the center of the line, which
// corresponds to position 2500.
int error = position - 2500;
// Get motor speed difference using proportional and derivative PID terms
// (the integral term is generally not very useful for line following).
// Here we are using a proportional constant of 1/4 and a derivative
// constant of 6, which should work decently for many Zumo motor choices.
int speedDifference = error / 4 + 6 * (error - lastError);
lastError = error;
// Get individual motor speeds. The sign of speedDifference
// determines if the robot turns left or right.
int m1Speed = MAX_SPEED + speedDifference;
int m2Speed = MAX_SPEED - speedDifference;
if (m1Speed < 0)
m1Speed = 0;
if (m2Speed < 0)
m2Speed = 0;
if (m1Speed > MAX_SPEED)
m1Speed = MAX_SPEED;
if (m2Speed > MAX_SPEED)
m2Speed = MAX_SPEED;
motors.setSpeeds(m1Speed, m2Speed);
//if (distance <20){
// motors.setSpeeds(0,0);
// }
////////////////////////////////////////////
// Calculating the distance
distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
// Displays the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
} ```
Of course pulseIn is blocking function. Arduino project is open source, you can easily check source code
Here is C equivalent countPulseASM function which does measurement.
unsigned long pulseInSimpl(volatile uint8_t *port, uint8_t bit, uint8_t stateMask, unsigned long maxloops)
{
unsigned long width = 0;
// wait for any previous pulse to end
while ((*port & bit) == stateMask)
if (--maxloops == 0)
return 0;
// wait for the pulse to start
while ((*port & bit) != stateMask)
if (--maxloops == 0)
return 0;
// wait for the pulse to stop
while ((*port & bit) == stateMask) {
if (++width == maxloops)
return 0;
}
return width;
}
If you need measure pulse length in non blocking way, use hw counters.

Arduino Serial.print() if Weight is Steady

I have a code in Arduino that runs a height and weight sensor combination with an ultrasonic sensor and load cells. I need the weights and heights to print to the serial monitor only when the weight has been steady on the scale for three seconds and the same for the height. What I mean by steady is that the weight or height would have to be the same for three seconds. Is this possible?
The code that I have for the circuit is as follows:
#include <LiquidCrystal.h>
#define calibration_factor -13180.00
//This value is obtained using the SparkFun_HX711_Calibration sketch
#define DOUT 7
#define CLK 6
HX711 scale(DOUT, CLK);
LiquidCrystal LCD(10, 9, 5, 4, 3, 2); //Create Liquid Crystal Object
called LCD
int trigPin=13; //Sensor Trip pin connected to Arduino pin 13
int echoPin=11; //Sensor Echo pin connected to Arduino pin 11
int myCounter=0; //declare your variable myCounter and set to 0
int servoControlPin=6; //Servo control line is connected to pin 6
float pingTime; //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in inches
float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees.
void setup() {
Serial.begin(9600);
Serial.println("HX711 scale demo");
scale.set_scale(calibration_factor); //This value is obtained by
using the SparkFun_HX711_Calibration sketch
scale.tare(); //Assuming there is no weight on the scale at start up, reset the scale to 0
Serial.println("Readings:");
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
LCD.begin(16,2); //Tell Arduino to start your 16 column 2 row LCD
LCD.setCursor(0,0); //Set LCD cursor to upper left corner, column 0, row 0
LCD.print("Target Distance:");
}
void loop() {
Serial.println("Reading: ");
Serial.print(scale.get_units(), 1); //scale.get_units() returns a float
Serial.print(" lbs"); //You can change this to kg but you'll need to refactor the calibration_factor
Serial.println();
digitalWrite(trigPin, LOW); //Set trigger pin low
delayMicroseconds(2000); //Let signal settle
digitalWrite(trigPin, HIGH); //Set trigPin high
delayMicroseconds(15); //Delay in high state
digitalWrite(trigPin, LOW); //ping has now been sent
delayMicroseconds(10); //Delay in high state
pingTime = pulseIn(echoPin, HIGH); //pingTime is presented in microceconds
pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
targetDistance= speedOfSound * pingTime; //This will be in miles, since speed of sound was miles per hour
targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
targetDistance= targetDistance*63360; //Convert miles to inches by multipling by 63360 (inches per mile)
LCD.setCursor(0,1); //Set cursor to first column of second row
LCD.print(" "); //Print blanks to clear the row
LCD.setCursor(0,1); //Set Cursor again to first column of second row
LCD.print(targetDistance); //Print measured distance
LCD.print(" inches"); //Print your units.
delay(250); //pause to let things settle
Serial.print(targetDistance);
Serial.println();
Serial.print(" inches ");
delay(250);
}

IR sensor with Arduino for restaurant parking

I have problem in the code logic, I did not find any solution.
My doubt is I'm using two IR sensor interface with Arduino, so when car is passing 1st sensor and 2nd sensor then I'm sending the data that car is passed. That is fine but whenever car1 is passing 1st sensor and another car, say car2 is in 2nd sensor, then also flag is becoming 1, that is true but I don't want that.
How to code this so that car should pass two sensors? If car 1 is in sensor 1 and car 2 is in sensor 2 than flag should not be 1.
Please find the code below:
#include<avr/wdt.h>
#define DISTANCE 100
const int trigPin1 = 7;
const int echoPin1 = 6;
const int trigPin2 = 5;
const int echoPin2 = 4;
int MOVE_FLAG = 0;
void setup() {
// initialize serial communication:
Serial.begin(9600);
MOVE_FLAG = 0;
wdt_enable(WDTO_8S);
}
void loop()
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration1, duration2, inches1, inches2, cm1, cm2;
// The sensor is triggered by a HIGH pulse of 10 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(trigPin1, OUTPUT);
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
// Read the signal from the sensor: 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(echoPin1, INPUT);
duration1 = pulseIn(echoPin1, HIGH);
inches1 = microsecondsToInches(duration1);
cm1 = microsecondsToCentimeters(duration1);
delay(10);
pinMode(trigPin2, OUTPUT);
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
pinMode(echoPin2, INPUT);
duration2 = pulseIn(echoPin2, HIGH);
// convert the time into a distance
inches2 = microsecondsToInches(duration2);
cm2 = microsecondsToCentimeters(duration2);
if(cm1 <= DISTANCE && cm2 <= DISTANCE && MOVE_FLAG == 0)
{
Serial.println("3");
MOVE_FLAG = 1;
}
if (cm1 > DISTANCE && cm2 > DISTANCE && MOVE_FLAG == 1)
{
MOVE_FLAG = 0;
delay(500);
}
delay(50);
wdt_reset();
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
Two motion sensors are inadequate to accomplish what you described. Without video or something similar, there's no way for you to know whether Car 1 triggered the sensor or Car 2 triggered the sensor.
I suggest you re-think your approach to solving the problem. You might want to look at other parking lot projects people have created and posted on the Internet. Do a Google search for "Arduino Parking Lot" or something similar.

Arduino/ESP8266 Using interrupts to take samples

I'm trying to measure the discharge time of a capacitor using a NodeMCU board. See complete sketch below. This code works fine, however I want to improve it to get to better time scales, by using the ESP.getCycleCount() function and interrupts for the timing. The part of interest is this:
startTime = micros();
while (digitalRead(capPos) == HIGH) {
delayMicroseconds (1);
}
endTime = micros();
The while loop I want to rewrite into some form of interrupt based function, listening to a falling edge of the capPos pin, replacing the above function with something like this:
startTime = micros();
attachInterrupt(digitalPinToInterrupt(capPos), dischargeInterrupt, FALLING);
}
void dischargeInterrupt() {
endTime = micros();
detachInterrupt(digitalPinToInterrupt(capPos));
After that the original code continues.
Te problem I have is how to take the required 100 samples. When setting the interrupt after the startTime is taken, this routine will finish and do the next of the 100 iterations. Instead it should wait: for the interrupt to come, then for the rest of the routine to finish, as per original sketch. Being rather new to interrupts, I have no idea where to start with that part.
So what has to be done:
- loop() calls getEC()
getEC() takes 100 samples:
charge the cap, set the pins for discharge, set interrupt to measure discharge time.
interrupt comes, time passed is measured. Negative cap cycle is performed and one sampling round complete.
The main purpose of this change is to make the timing more accurate: react instantly on pin dropping to LOW and use a much higher resolution for time. The current microsecond resolution does the job but it's a serious limitation.
Here my complete, working, sketch:
// capacitor based TDS measurement
// pin D5 C+ - 330 ohm resistor----------|------------|
// | |
// cap EC probe or
// | resistor (for simulation)
// pin D6 C- ----------------------------| |
// |
// pin A0 EC -----------------------------------------|
#include <Average.h>
int capPos = D5; //C+
int capNeg = D6; //C-
int EC = D7; //EC
float CAP = 47; // capacity in nF
#define calibration 150 // a calibration factor to link time with EC.
void setup() {
Serial.begin(9600);
}
void loop () {
float EC = getEC(); // get the EC as mS/cm.
Serial.println (", EC: " + String(EC) + " mS/cm");
delay(100);
}
float getEC() {
int samples = 100; // number of EC samples to take and average.
unsigned long startTime; // the time stamp (in microseconds) the measurement starts.
unsigned long endTime; // the time stamp (in microseconds) the measurement is finished.
unsigned int dischargeTime; // the time it took for the capacitor to discharge.
Average<unsigned int> discharge(samples); // Take measurements on both the positive and negative cycles.
unsigned int chargeDelay = 500; // The time (in microseconds) given to the cap to fully charge/discharge - about 10x RC is a good value.
int startLevel; // analog level of the pin.
int endLevel;
pinMode(A0, INPUT);
for(int i=0; i<samples; i++) { // take <samples> measurements of the EC.
// Stage 1: fully charge capacitor for positive cycle.
// C+ high, C- low, EC disconnected.
pinMode (EC, INPUT);
pinMode (capPos,OUTPUT);
digitalWrite (capPos, HIGH);
pinMode (capNeg, OUTPUT);
digitalWrite (capNeg, LOW);
delayMicroseconds(chargeDelay);
// Stage 2: positive side discharge; measure time it takes.
// C+ disconnected, C- low, EC low.
pinMode (capPos,INPUT); //set C+ to input to keep voltage from grounding a discharging thru this output pin
pinMode (EC, OUTPUT);
digitalWrite (EC, LOW);
// Measure time until capPos goes LOW. Can't use pulseIn() here as the pin will be high already.
startTime = micros();
while (digitalRead(capPos) == HIGH) {
delayMicroseconds (1);
}
endTime = micros();
// handle potential overflow of micros() just as we measure, this happens every 70 minutes.
if (endTime < startTime) dischargeTime = 4294967295 - startTime + endTime;
else dischargeTime = endTime - startTime;
discharge.push(dischargeTime);
// Stage 3: fully charge capacitor for negative cycle. C+ low, C- high, EC disconnected.
pinMode (EC, INPUT);
pinMode (capPos,OUTPUT);
digitalWrite (capPos, LOW);
pinMode (capNeg, OUTPUT);
digitalWrite (capNeg, HIGH);
delayMicroseconds(chargeDelay);
// Stage 4: negative side charge; don't measure as we just want to balance it the directions.
// C+ disconnected, C- low, EC low.
pinMode (capPos,INPUT); //set C+ to input to keep voltage from grounding a discharging thru this output pin
pinMode (EC, OUTPUT);
digitalWrite (EC, HIGH);
delayMicroseconds(dischargeTime);
}
float dischargeAverage = discharge.mean();
Serial.print("Discharge time: ");
Serial.print(dischargeAverage);
// Calculate EC from the discharge time.
return dischargeAverage;
}
So, got this answered myself.
For the time resolution: you can get a much more exact time by using ESP.getCycleCount() which counts processor cycles - on my 80 MHz NodeMCU board that's 12.5 ns per cycle or 80 cycles per microsecond. I should have mentioned that in the first part.
Interrupts: this is something I misunderstood. Now I solved it by having the main function wait in a loop until a timeout is reached (set to 1 millisecond, normal expected times are in the 1-100 microseconds range), or until a global variable is set by the interrupt function. So now I'm measuring in the 12.5 nanosecond resolution!
One thing that's missing from this sketch is a correction for program time taken to deal with the timing: the time it takes from dropping the value on the EC pin to starting to count, and the time it takes from receiving the interrupt to stopping the count. If that overhead is say 100 cycles, that would be 1.25 microseconds, which is well within my measurement time.
// capacitor based TDS measurement
// pin D5 C+ - 330 ohm resistor----------|------------|
// | |
// cap EC probe or
// | resistor (for simulation)
// pin D6 C- ----------------------------| |
// |
// pin A0 EC -----------------------------------------|
#include <Average.h>
int capPos = D5; //C+
int capNeg = D6; //C-
int EC = D7; //EC
unsigned long startCycle;
unsigned long endCycle;
#define CYCLETIME 12.5 // the time it takes in nanoseconds to complete one CPU cycle (12.5 ns on a 80 MHz processor)
float CAP = 47; // capacity in nF
#define calibration 150 // a calibration factor to link time with EC.
void setup() {
Serial.begin(9600);
}
void loop () {
float EC = getEC(); // get the EC as mS/cm.
Serial.println (", EC: " + String(EC) + " mS/cm");
delay(500);
}
float getEC() {
int samples = 100; // number of EC samples to take and average.
unsigned long startTime; // the time stamp (in microseconds) the measurement starts.
unsigned long endTime; // the time stamp (in microseconds) the measurement is finished.
unsigned int dischargeTime; // the time it took for the capacitor to discharge.
Average<unsigned int> discharge(samples); // The sampling results.
unsigned int chargeDelay = 500; // The time (in microseconds) given to the cap to fully charge/discharge - about 10x RC is a good value.
unsigned int timeout = 1; // discharge timeout in milliseconds - if not triggered within this time, the EC probe is probably not there.
int startLevel; // analog level of the pin.
int endLevel;
pinMode(A0, INPUT);
for(int i=0; i<samples; i++) { // take <samples> measurements of the EC.
// Stage 1: fully charge capacitor for positive cycle.
// C+ high, C- low, EC disconnected.
pinMode (EC, INPUT);
pinMode (capPos,OUTPUT);
digitalWrite (capPos, HIGH);
pinMode (capNeg, OUTPUT);
digitalWrite (capNeg, LOW);
delayMicroseconds(chargeDelay);
// Stage 2: positive side discharge; measure time it takes.
// C+ disconnected, C- low, EC low.
startCycle = ESP.getCycleCount();
pinMode (capPos,INPUT); //set C+ to input to keep voltage from grounding a discharging thru this output pin
pinMode (EC, OUTPUT);
digitalWrite (EC, LOW);
// Use cycle counts and an interrupt to get a much more precise time measurement, especially for high-EC situations.
endCycle = 0;
startTime = millis();
attachInterrupt(digitalPinToInterrupt(capPos), capDischarged, FALLING);
while (endCycle == 0) {
if (millis() > (startTime + timeout)) break;
}
detachInterrupt(digitalPinToInterrupt(capPos));
if (endCycle == 0) dischargeTime = 0;
else {
// Handle potential overflow of micros() just as we measure, this happens about every 54 seconds
// on a 80-MHz board.
if (endCycle < startCycle) dischargeTime = (4294967295 - startCycle + endCycle) * CYCLETIME;
else dischargeTime = (endCycle - startCycle) * CYCLETIME;
discharge.push(dischargeTime);
}
// Stage 3: fully charge capacitor for negative cycle. C+ low, C- high, EC disconnected.
pinMode (EC, INPUT);
pinMode (capPos,OUTPUT);
digitalWrite (capPos, LOW);
pinMode (capNeg, OUTPUT);
digitalWrite (capNeg, HIGH);
delayMicroseconds(chargeDelay);
// Stage 4: negative side charge; don't measure as we just want to balance it the directions.
// C+ disconnected, C- high, EC high.
pinMode (capPos,INPUT); //set C+ to input to keep voltage from grounding a discharging thru this output pin
pinMode (EC, OUTPUT);
digitalWrite (EC, HIGH);
delayMicroseconds(dischargeTime/1000);
}
float dischargeAverage = discharge.mean();
Serial.print("Discharge time: ");
Serial.print(dischargeAverage);
// Calculate EC from the discharge time.
return dischargeAverage;
}
// Upon interrupt: register the cycle count of when the cap has discharged.
void capDischarged() {
endCycle = ESP.getCycleCount();
detachInterrupt(digitalPinToInterrupt(capPos));
}

arduino Ultrasound srf05 wrong value

My Arduino board is Arduino Due ATmega328p. My Ultrasound is srf05.
I measure the distance is 5cm but my serial show me "531".Serial Monitor show the int of distance which value is always be 531.Why?
Here are the codes.
#define ECHOPIN 2 // Pin to receive echo pulse
#define TRIGPIN 3 // Pin to send trigger pulse
void setup(){
Serial.begin(9600);
pinMode(ECHOPIN, INPUT);
pinMode(TRIGPIN, OUTPUT);
}
void loop(){
digitalWrite(TRIGPIN, LOW); // Set the trigger pin to low for 2uS
delayMicroseconds(2);
digitalWrite(TRIGPIN, HIGH); // Send a 10uS high to trigger ranging
delayMicroseconds(10);
digitalWrite(TRIGPIN, LOW); // Send pin low again
int distance = pulseIn(ECHOPIN, HIGH); // Read in times pulse
distance = distance/58; // Calculate distance from time of pulse
Serial.println(distance);
delay(50); // Wait 50mS before next ranging
}
The srf05 times out if it doesn't receive the echo pulse. The width of the pulse is 30 ms.
30,000 / 58 is 517, which is close to 531. It looks like your device is not receiving an echo from the object. This makes your problem a hardware issue, and not a programming issue. (The code looks correct.)

Resources