Page 1 of 1

HC-SR504 on esp8266

Posted: Thu Nov 10, 2016 12:26 am
by sequel
Hi list,

I have been running an ultrasonic sensor on a raspberry pi for a while, with quite some good results.

I wanted to port this on an esp8266 and, it looks like the result are a bit less accurate than on the pi.

Here is the graphs usage of each one :


pi :
pi_hc-sr504.png
pi_hc-sr504.png (18.99 KiB) Viewed 6635 times

esp8266 :
esp8266_hc-sr504.png
esp8266_hc-sr504.png (19.69 KiB) Viewed 6635 times

The line is quite smoother on the pi.

Here is the code i use on the esp8266 to get the values :

Code: Select all

import time
import machine

trigger_pin=5
echo_pin=4

trigger=machine.Pin(trigger_pin, machine.Pin.OUT)
echo=machine.Pin(echo_pin, machine.Pin.IN)


def get_distance():
    trigger.low()
    time.sleep_us(5)
    trigger.high()
    time.sleep_us(10)
    trigger.low()

    while echo.value()==0:
        start=time.ticks_us()

    while echo.value()==1:
        delta=time.ticks_diff(time.ticks_us(), start)

    distance=(delta/2)/29

    return distance

I suspect that the tick is less reliable on the esp8266 than on the pi. For example, in an other project, using a timer of 90000 milliseconds yield in a run of 82 seconds.

Any idea on how the code could be getting better result out of this sensor on esp8266?


Cheers!

Re: HC-SR504 on esp8266

Posted: Thu Nov 10, 2016 1:57 am
by dwight.hubbard
I recall seeing behavior similar to this when the trigger pin was running at less than 5 volts.

Sent from my SM-G920T using Tapatalk

Re: HC-SR504 on esp8266

Posted: Thu Nov 10, 2016 8:30 am
by deshipu
You will probably get much more accuracy by using machine.time_pulse_us instead of an explicit loop:

http://micropython.org/resources/docs/e ... e_pulse_us

Re: HC-SR504 on esp8266

Posted: Thu Nov 10, 2016 6:41 pm
by sequel
@ dwight.hubbard

Thanks for the pointer but I am already running the trigger on 5 volts.

@ deshipu

Thanks a lot for the suggestion.

I have tried using :

Code: Select all

time=time_pulse_us(echo_pin, 1, 29000)
...
distance=(time/2)/29

But it gives me exactly the same results.



Thanks again!

Re: HC-SR504 on esp8266

Posted: Fri Nov 11, 2016 2:46 am
by alpha_pi
RazPi focuses on sys kernel priority. During a Python pgm exec on the Pi, the kernel will always focus on what attention is needed during such an event. Resource management. MicroPy, only focuses on what instructions are running in your pgm. Simple PWM on the RazPi to a servo motor will cause a jittering due to process interruptions in the bckgrnd. Reason for a separate controller board off the GPIO's are necessary to more accurately control them.

Sent from my Z832 using Tapatalk

Re: HC-SR504 on esp8266

Posted: Tue Nov 15, 2016 3:00 pm
by platforma
Moved to Hardware Projects.