这里对python来说相当新,并尝试将time.sleep函数分离出几个读数。
const valueToSave = event.target.innerHTML !=='<br>'
? eventTarget.innerText || eventTarget.textContent
: '';
我想要的是读数以不同的频率打印但仍然同时运行。
e.g。
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)
我理解这可能是一个简单的语法问题,但我还没有找到一个简单的解决方案。
非常感谢
答案 0 :(得分: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会更新一段时间并使用字典中的数据。