Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Python线程监控传感器_Python_Multithreading_Python 2.7_Class_Arduino - Fatal编程技术网

使用Python线程监控传感器

使用Python线程监控传感器,python,multithreading,python-2.7,class,arduino,Python,Multithreading,Python 2.7,Class,Arduino,目标:使用线程构建独立的Python传感器类,以处理Raspberry Pi和Arduino传感器之间的通信以及一些基本数据处理 背景: 我有一个带有一些传感器的Arduino MEGA,还有一个运行python的Raspberry Pi 3。Pi向Arduino发送请求,以读取其传感器值之一。我的Arduino有编码器、电机、灯、泵等,所以我创建了一个通用python类来处理每种类型的外围设备 每个python类将读取原始传感器值,将其存储在日志中,并进行一些计算 import time im

目标:使用线程构建独立的Python传感器类,以处理Raspberry Pi和Arduino传感器之间的通信以及一些基本数据处理

背景:

我有一个带有一些传感器的Arduino MEGA,还有一个运行python的Raspberry Pi 3。Pi向Arduino发送请求,以读取其传感器值之一。我的Arduino有编码器、电机、灯、泵等,所以我创建了一个通用python类来处理每种类型的外围设备

每个python类将读取原始传感器值,将其存储在日志中,并进行一些计算

import time
import numpy as np

class Encoder(object):
    def __init__(self, hex_address):
        self.hex_address = hex_address
        self.log = []

    def read(self):
        observation = (time.time(), raw_value())
        log.append(observation)

    def raw_value(self):
        ...Communication code...
        return value

    def speed(self, over=1.0):
        times = [obs[0] for obs in self.log if time.time() - obs[0] < over]
        rates = [obs[1] for obs in self.log if time.time() - obs[0] < over]
        return np.polyfit(times, rates, 1)[0]
问题:

在此设置中,要使
Encoder()
类真正正常工作,必须半定期调用
enc.read()
,否则数据点不会添加到日志中

此外,如果我的程序的各个部分调用
enc.read()
,该怎么办。现在,根据调用
enc.read()
的时间和地点,我会获得更多或更少的数据

此外,每次调用
enc.speed()
,我的Pi都必须计算另一个
np.polyfit
,即使数据没有改变

目标:实施线程,为每个传感器对象启动一个新线程

这样,它们独立于我的主线程运行。我想
start()
传感器,然后让它每隔X毫秒调用
read()
将新数据添加到日志中。此外,我可以实现一个
update()
方法,每次调用它时都进行读取和所有计算

我需要什么帮助:

我已经使用了一些线程类,但是在将线程编织到这个示例代码中时遇到了很多麻烦

enc = Encoder('\x04')

while True:
    print enc.read()
    print enc.speed()
    times.sleep(1)