Hi together,
since this is my first post on the arduino forum I want to introduce myself. My name is Stefan, I am from Austria and I am a newbie in programming arduino. I have some experience in programming actually it is even my occupation but I work with Siemens Step7 which is a different story to arduino.
Now my problem: I have an ultrasonic sensor hc-sr04 but the data I get back is totally wrong . For example: The display shows 26,7cm but if I measure it manuallly I have 31cm.
Also it´s range seems to be wrong, according to the datasheet should be 2cm-4500cm, but if I try to point the sensor in direction of a wall, which is approximately 3000cm away, the numbers go crazy. I never see a stable value and also it want exceed about 1800cm.
I think the numbers for conversion are wrong but theese are the only ones I could find according to my sensor.
Here is my sketch:
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int trigger = 7; //output trigger
int echo = 8; //input echo
long duration, cm, inches;
int cmdec, indec;
int cmconv = 59; // ratio between pulse width and cm
int inchconv = 147; // ratio between pulse width and inches
//the numbers 59 and 147 i got from the Internet not sure if
//they are right, the range of the sensor is 2cm-4500cm (1,2inch-177inch)
String s1, s2;
void setup()
{
lcd.begin(16, 2);
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
}
void loop()
{
//pulses for the input Trigger
digitalWrite(trigger, LOW);
delayMicroseconds(2);
digitalWrite(trigger, HIGH);
delayMicroseconds(10);
digitalWrite(trigger, LOW);
duration = pulseIn(echo, HIGH); //read return echo pulse lenght
// convert the time into the distances
cm = microsecondsToCentimeters(duration);
cmdec = (duration - cm * cmconv) * 10 / cmconv;
inches = microsecondsToInches(duration);
indec = (duration - inches * inchconv) * 10 / inchconv;
//printing data on LCD
s1 = String(cm) + "." + String(cmdec) + "cm" + " ";
s2 = String(inches) + "." + String(indec) + "inch" + " ";
lcd.setCursor(0, 0); // print cm on line 0
lcd.print(s1);
lcd.setCursor(0,1); // print inches on line 1
lcd.print(s2);
delay(100);
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / cmconv;
}
long microsecondsToInches(long microseconds)
{
return microseconds / inchconv;
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Thank´s for every help in advance and greetings
Stefan