Micropython HC-SR04 - ESP8266

时间:2017-02-23 12:49:05

标签: python iot esp8266 nodemcu micropython

我正在努力让NodeMCU ESP8266开发板与HC SR04超声波传感器配合使用。我不断读到“0”,这不是现实。

我将传感器的地和5v引脚连接到5v源,GPIO引脚4和5上的Echo和Trigger引脚。理论上,一切都应该工作,但我只是保持“0”。也许我的代码出了问题?见下文:

import machine
import sys
import time
time.sleep(1) #Just for everything to settle down

while 1:

    pinTrigger = machine.Pin(5, machine.Pin.OUT) #defining the pins
    pinEcho = machine.Pin(4, machine.Pin.IN) #defining the pins

    pinTrigger.high()
    time.sleep(0.00001)
    pinTrigger.low()

    time.sleep(0.5)

    start = time.time()
    stop = time.time()

    while pinEcho ==0:
        start = time.time() #Starting the time when sending out the signal

    while pinTrigger ==1:
        stop = time.time() #Stopping the time when the signal comes back

    elapsed = stop-start #working out the time.

    distance = elapsed * 34000 #multiply by speed of sound to get distance

    distance = distance / 2 #divide by 2 becuase it was there and back

    print ("Distance : %.1f" % distance) 

    sys.exit()

请帮忙。

2 个答案:

答案 0 :(得分:1)

以下是解决问题的方法:

import machine
import utime


while True:
  trig=machine.Pin(5, machine.Pin.OUT)
  trig.off()//stop reading
  utime.sleep_us(2)
  trig.on()
  utime.sleep_us(10)
  trig.off()
  echo=machine.Pin(4, machine.Pin.IN)
  while echo.value() == 0:
    pass
  t1 = utime.ticks_us()
  while echo.value() == 1:
    pass
  t2 = utime.ticks_us()
  cm = (t2 - t1) / 58.0
  print(cm)
  utime.sleep(2)

在互联网的其他地方,他们建议你在回波和NodeMCU板上的引脚(ESP8266)之间放一个电阻,这使得测量结果非常糟糕。所以现在我用它连接到我的RPi GPIO的5v和接地(连接到HC-SR04)100%工作,并且触发器和回声连接到NodeMCU板引脚。

另一件值得注意的事情是我在1s读取数据(代码的最后一行),将其改为2秒使代码更准确。

希望这有助于某人。

这是图表:

Working Diagram

答案 1 :(得分:0)

看看this library,以便更轻松地在micropython中使用HC-SR04传感器驱动程序。