分离时间。睡眠针对不同的行动

2024-04-28 13:14:53 发布

您现在位置:Python中文网/ 问答频道 /正文

对于python来说,这是一个相当新的概念,试图将时间。睡眠多个读数的函数。你知道吗

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)

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

非常感谢


Tags: fromanreadinputdatetimetimeonsleep
1条回答
网友
1楼 · 发布于 2024-04-28 13:14:53

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

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将更新一个周期并使用字典中的数据。你知道吗

相关问题 更多 >