***Python code:***
import serial
import pandas as pd
import time
import re
import xlrd
from msvcrt import getch
import numpy as np
i = 0
x = 0
y = 0
df = pd.read_excel(r'C:\Users\lynchfamily\Desktop\mlglovesdata.xls')
# Read COM9
# Read from COM10 as well
# Readline() only works with a timeout (IMPORTANT)
serHC = serial.Serial('COM9', 115200,timeout=.250,parity=serial.PARITY_NONE,rtscts=1) # This is the JY
serRN = serial.Serial('COM10', 115200,timeout=.250,parity=serial.PARITY_NONE,rtscts=1) # This is the silvermate
def serialin():
# Sensor lists
sensor_names = list()
sensor_values = list()
global i
# Read a certain amount of bytes from serial and then continue
# Regular expressions for finding the proper data
while i < 6:
# print(i) for debugging
global serHC
global serRN
#searchObj = re.search(r'(A\d?\d*)?(\d*)?',serHC.read(4).decode(),re.I)
#searchObjRN = re.search(r'(A\d?\d*)?(\d*)?',serRN.read(4).decode(),re.I)
# Serial data stops while in loop
# The if statements keep the false values out of the program
#if searchObj.group(1):
sensor_names.append(serHC.read(2))
#if searchObj.group(2):
sensor_values.append(serHC.read(2))
#if searchObjRN.group(1):
sensor_names.append(serRN.read(2))
#if searchObjRN.group(2):
sensor_values.append(serRN.read(2))
i = i + 1
while 1:
# Get the key from the msvcrt module
key = getch().decode('ASCII')
# If key is pressed, do something
if key:
print(key)
# Zip them together
# Final 2D list
final_2d_list = zip(sensor_names,sensor_values)
print(list(sorted(final_2d_list)))
#vals = df.Dataframe([
#df.append(vals)
#print(sorted_array_1stdim[r])
#sensor_values = [0] * 10
# Thread for reading definition
break
# Fancy recursion
sensor_values.clear()
sensor_names.clear()
i = 0
serialin()
serialin()
Arduino代码:
^{pr2}$我试图通过sparkfun的silver mate和HC-06
模块从传感器发送模拟数据到python。
我必须在每次读取之间延迟5秒读取模拟数据,这样读数就不会发生冲突。
数据通过串行端口COM9
和COM10
。我知道python中的serial可能是阻塞的,所以我尝试先读取它,然后将它放入一个列表中。
我也知道,一旦序列号被通读,它看起来是非阻塞的。当我使用serHC.readline()
和serRN.readline()
时,我得到了我期望看到的东西。
但是,列表中的数据没有根据传感器的变化进行更新。我不得不承认python不是我的主要编程语言,所以我请求帮助。
我认为使用多个线程可能会有用,但我无法在主线程中获得serHC
和{
任何帮助都将不胜感激!!在
正如您所发现的那样,从串行端口顺序读取是不可能的:一个端口的阻塞读取意味着另一个端口同时发送的数据丢失。在
使用基于线程的方法。在
以下草图应足以开始:
学习线程:https://pymotw.com/3/threading/
从序列中定期读取
下面是每个
TIME_PERIOD
秒阅读的草图。 围绕read的无限while循环有一个嵌套的try/catch
块的“thread”循环 用于捕获串行通信问题并在TIME_PERIOD
之后重试连接。在就拿它作为一个开始的例子吧!在
^{pr2}$相关问题 更多 >
编程相关推荐