Hello.I have an arduino mega and an ultrasonic sensor.
I have found many codes in internet about millis AND ultrasonic sensors,but nothing worked.
I tried a code of mine ,but I get 0.00 in serial monitor
CODE:
const int Trig_pin_front = 42;
const int Echo_pin_front = 43;
long duration_front;
float distance_front;
boolean first = true;
boolean second_ = false;
unsigned long prev = 0;
void setup()
{
Serial.begin(9600);
pinMode(Echo_pin_front , INPUT);
pinMode(Trig_pin_front , OUTPUT);
}
void ultrasonic_sensor_forward()
{
unsigned long cur = millis();
if (first)
{
if (cur - prev >= 2)
{
digitalWrite(Trig_pin_front , HIGH);
first = false;
second_ = true;
prev = cur;
}
}
if (second_)
{
if (cur - prev >= 2)
{
digitalWrite(Trig_pin_front , LOW);
duration_front = pulseIn(Echo_pin_front , HIGH);
distance_front = duration_front * 0.034 / 2;
Serial.println(distance_front);
second_ = false;
first = true;
prev = cur;
}
}
}
void loop()
{
ultrasonic_sensor_forward();
}
Any advices?What wrong my code has?
Thanks...
250 pings per second?
About 15 times too many.
Also, a trigger pulse is normally of the order of 10 microseconds, not 2 milliseconds.
It didn't work.
I changed it to 20 milliseconds and after to 10 milliseconds ,but I get 0.00 distance again....
void ultrasonic_sensor_forward()
{
static unsigned long prev;
unsigned long cur = millis();
if (cur - prev >= 50) // no more than 20 pings per second
{
digitalWrite(Trig_pin_front, HIGH);
delayMicrosceonds (10);
digitalWrite(Trig_pin_front, LOW);
duration_front = pulseIn(Echo_pin_front , HIGH);
distance_front = duration_front * 0.034 / 2;
Serial.println(distance_front);
prev += 50;
}
}
Uncompiled, untested.
Better still, use the NewPing library
I do not want to use delay() or delayMicroseconds().
Only millis() function.
Is this possible?
arduiNICK:
I do not want to use delay() or delayMicroseconds().
Only millis() function.
Is this possible?
Yes, of course.
My version doesn't use delay, and pulseIn blocks longer than the delayMicroseconds I used, but hey, knock yourself out.
I don't understand.
Can I use ultrasonic sensor with only millis (no delay no delayMicroseconds) ?
Yes, I think you can - the out-going pulse train isn't sent until the falling edge of the trigger pulse (at least, that's how it should be), so I guess it shouldn't matter how long the trigger pulse is.
Can't see why you'd want to, though.
Like I said, if you're worried about blocking, then get rid of pulseIn.
Ok ,thank you.
Do you know how to do it or does anyone know about it?
Yes - use the NewPing library.