【问题标题】:Separating time.sleep for different actions为不同的动作分开时间.sleep
【发布时间】:2017-05-09 15:44:58
【问题描述】:

这里是 python 的新手,并试图将 time.sleep 函数分离出来进行多次阅读。

while True:
#read from a analog sensor on input 1
d= grovepi.analogRead(1)
#read from an analog sensor on input 2
a= grovepi.analogRead(2)
#read from an digital sensor on input 3
(t,h)=grovepi.dht(3,0)


#output the data
#print (datetime,time)
print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print ("Noise:",d,"dB")
print ("Light:",a,"lux")
print ("Temperature:",t,"C")
print ("Humidity:",h,"rH")
grovelcd.setText("T:" + str(t) + " H:" + str(h) + " N:" + str(d)+ " L:" + str(a))

time.sleep(5)

我希望读数以不同的频率打印,但仍同时运行。

例如

print ("Noise:",d,"dB")
time.sleep(3)

print ("Light:",a,"lux")
time.sleep(5)

我知道这可能是一个简单的语法问题,但我还没有找到一个简单的解决方案。

非常感谢

【问题讨论】:

  • dath 来自哪里?
  • while True: ' #read from an analog sensor on input 1 d= grovepi.analogRead(1) #read from an analog sensor on input 2 a= grovepi.analogRead(2) #read from an输入 3 上的数字传感器 (t,h)=grovepi.dht(3,0) '
  • 请编辑您的问题以包含该代码。您的问题正下方有一个edit 链接。
  • 应该更新,谢谢。它们是来自传感器温度、湿度、噪音等的读数

标签: python time grovepi+


【解决方案1】:

这是使用线程的部分解决方案:

import threading
import time
import grovepi

def take_analog_measurement(stop, lock, name, pin, units, period):
    while not stop.is_set():
        with lock:
            val = grovepi.analogRead(pin)
        print(name, ': ', val, units, sep='')
        time.sleep(period)

def take_dht_measurement(stop, lock, pin, mtype, period):
    while not stop.is_set():
        with lock:
            temp, hum = grovepi.dht(pin, mtype)
        print('Temperature: ', temp, ' C\nHumidity: ', hum, ' rH', sep='')
        time.sleep(period)

stop = threading.Event()
grovepilock = threading.Lock()
threads = []
threads.append(threading.Thread(target=take_analog_measurement, args=(stop, grovepilock, 'Noise', 1, 'dB', 3)))
threads.append(threading.Thread(target=take_analog_measurement, args=(stop, grovepilock, 'Light', 2, 'lux', 5)))
threads.append(threading.Thread(target=take_dht_measurement, args=(stop, grovepilock, 3, 0, 7)))
for thread in threads:
    thread.start()

for thread in threads:
    try:
        thread.join()
    except KeyboardInterrupt:
        stop.set()
        thread.join()

print('done')

我没有 GrovePi,所以无法用硬件测试它,但我做了一些模拟测试。

这将以给定的频率读取每个传感器并输出值。该锁用于保护grovepi,因为我不确定它是否是线程安全的。该事件用于通知所有线程停止(尽管它们必须等到它们醒来才能真正停止)。

当每个变量以不同的频率变化时,我不知道你想如何处理grovelcd.setText。一种可能的解决方案可能是使用与所有传感器线程共享的字典(和锁)的另一个线程。然后 LCD 会在一段时间内更新并使用字典中的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多