0

我是微控制器编程的新手,并试图每 2 分钟从连接到我的 ESP8266 的 DHT11 读取温度和湿度读数。我最初的尝试是一个幼稚的 while 循环,每次迭代都会休眠……这会锁定设备,但确实按预期每 2 分钟读取一次。显然,这不是一个好方法,而且我感觉在如何使用 MicroPython 在 ESP8266 上对连续过程进行编程方面,我缺少一些基本的东西。任何帮助将不胜感激。

4

2 回答 2

1

有一个 Arduino 示例草图,它实现了一个类似问题的解决方案:“ BlinkWithoutDelay ”。尽管它是 C++ 而不是您的 python 问题,但想法仍然相同。

utime.sleep()我们可以重复检查当前时间,而不是轮询传感器数据和-ing 直到下一次读取。如果当前时间减去我们上次做某事的时间超过了某个间隔时间,我们就会做那件事并记住我们做的时间。否则,我们只是继续做不同的事情。

就像在micropython 博客文章中一样,我们可以这样做:

import dht
import machine
import utime

d = dht.DHT11(machine.Pin(4))

# keep track of the last time we did something
last_measurement_ms = 0
# define in what intervals we want to do something
INTERVAL = 5000 # do something every 5000 ms

# main "loop".
while True:
    # has enough time elapsed? we need to use ticks_diff here
    # as the documentation states. 
    #(https://docs.micropython.org/en/latest/pyboard/library/utime.html)
    if utime.ticks_diff(utime.ticks_ms(), last_measurement_ms) >= INTERVAL:
        # yes, do a measurement now.
        d.measure()
        temp = d.temperature() 
        print("Temperature is %d." % (temp)) 

        #save the current time.
        last_measurement_ms = utime.ticks_ms()
    # do the stuff you would do normally.
    # this will be spammed, as  there is nothing else to do 
    print("Normal loop") 

请注意,我没有带有 micropython 固件的实际 ESP8266 来验证这一点,但您应该了解大致的想法。

于 2018-02-11T10:50:18.530 回答
1

另一种方法是让机器在读数之间“深度睡眠”。

然后,如果您将 RST 引脚连接到引脚 16,它可以自动唤醒(并进行下一次测量)。

我一直在这样做,我main.py看起来像:

import wifi
import mqtt
import dht
import time    

# This function will wait for the wifi to connect, or timeout
# after 30 seconds.
wifi.connect()
# This import/function inits the sensor, and gets data from it
result = dht.sensor.measure()
# In my case, I'm pushing the data to an MQTT broker - this
# function connects to the broker and sends the relevant data.
mqtt.send(result)
# We need to sleep here, otherwise our push to the broker may not
# complete before we deepsleep below.
time.sleep(5)
# This function will stop all processing, and then try to wake
# after the given number of microseconds. This value should be 2
# minutes.
esp.deepsleep(1000000 * 60 * 2)

注意事项。

  • 您必须将引脚 16 连接到 RST 引脚。
  • 我省略了 wifi、dht 和 mqtt 模块——它们会根据您的要求而有所不同(例如凭据,或者实际上如果您使用的不是 MQTT)。
  • 您必须time.sleep()接听电话,否则 ESP8266 可能会在消息发送之前休眠。它还为Ctrl-C通过串行端口连接并停止重启循环提供了一些时间。

显然,如果您需要在设备上做其他事情(不仅仅是唤醒、读取和发送数据),那么您将想做其他事情。

于 2018-04-13T00:07:43.683 回答