I have an ioe-sr05 ultrasonic sensor.
When I place an object in front of it, the sensor correctly measures its distance.
But when there is no object in front of the sensor, the distance is 160mm.
How can i solve this problem?
Thank you
code:
#define DistanceEn_Pin 2
int i = 0;
long unsigned distance = 0;
uint8_t distanceValue[4] = {0,0,0,0};
void setup()
{
Serial.begin(9600);
pinMode(DistanceEn_Pin,OUTPUT);
digitalWrite(DistanceEn_Pin,1);
}
void Distance()
{
while( Serial.read() >= 0 ); //Empty the serial buffer
digitalWrite(DistanceEn_Pin,0); //Ultrasound can open
while(Serial.available() <= 4) //Waiting for the ultrasonic data window
{
}
distanceValue[0] = Serial.read(); //Extract the data
if( distanceValue[0] == 0xff ) //Determine if data for ultrasonic module
{
for(i = 1;i <= 3;i ++)
{
distanceValue[i] = Serial.read();
}
}
digitalWrite(DistanceEn_Pin,1); //Ultrasound can make
distance = distanceValue[1] * 256 + distanceValue[2]; //Data processing, calculating distance
if((distanceValue[3] == distanceValue[1] + distanceValue[2] - 1)) //Data and check, can be removed
{
Serial.print("The distance is : ");
Serial.print(distance);
Serial.println(" mm");
}
}
/* Example code for HC-SR04 ultrasonic distance sensor with Arduino. No library required. More info: https://www.makerguides.com */
// Define Trig and Echo pin:
#define trigPin 2
#define echoPin 3
// Define variables:
long duration;
int distance;
void setup() {
// Define inputs and outputs:
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
//Begin Serial communication at a baudrate of 9600:
Serial.begin(9600);
}
void loop() {
// Clear the trigPin by setting it LOW:
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
// Trigger the sensor by setting the trigPin high for 10 microseconds:
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the echoPin, pulseIn() returns the duration (length of the pulse) in microseconds:
duration = pulseIn(echoPin, HIGH);
// Calculate the distance:
distance = duration * 0.034 / 2;
// Print the distance on the Serial Monitor (Ctrl+Shift+M):
Serial.print("Distance = ");
Serial.print(distance);
Serial.println(" cm");
delay(500);
}
while( Serial.read() >= 0 ); //Empty the serial buffer
digitalWrite(DistanceEn_Pin,0); //Ultrasound can open
while(Serial.available() <= 4) //Waiting for the ultrasonic data window
{
}
distanceValue[0] = Serial.read(); //Extract the data
if( distanceValue[0] == 0xff ) //Determine if data for ultrasonic module
{
for(i = 1;i <= 3;i ++)
{
distanceValue[i] = Serial.read();
}
}
What code should I add so that an LED turns on when there is an object in front of the sensor, and it turns off when there is no objects in front of the sensor?