Arduino + Raspy3系列问题

时间:2016-07-26 13:28:13

标签: python arduino raspberry-pi

我是python的新手,我试图使用python将Arduino Uno与Raspberry Pi3连接起来。 Arduino每1秒发送一次数据(ID,Temp和Humidity)。

问题在于我希望raspberry每隔5秒读一次串口,而且烂掉正在丢失数据...它只获得ID:2,4,6,8等,所以我是丢失数据,我还发现,当粗略读取时,它没有获得最新数据,似乎它正在读取串行数据的缓冲区(我也试过每秒读取一次,问题是相同)。

以下是代码的一部分:

import numpy
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtCore import pyqtSignal as Signal
from PyQt4.QtGui import *
import serial

class Ventana(QMainWindow, ui_SQL.Ui_Ventana):

port1 = serial.Serial(3)   # port1 = serial.Serial('/dev/ttyUSB0')             
port1.baudrate = 9600
port1.timeout = 1

    def __init__(self, parent=None):

        self.l1 = []
        self.l2 = []
        self.l3 = []
        super(Ventana, self).__init__(parent)
        self.setupUi(self)
        self.cajita.clicked.connect(self.cancel1)
        timer = QTimer(self)
        timer.timeout.connect(self.medir)
        timer.start(5000)

    def medir(self):

        texto = self.port1.readline()
        texto1 = texto.split(" ")
        num1 = int(texto1[0])
        num2 = float(texto1[1])
        num3 = float(texto1[2])
        self.lect1.setText(str(num2))
        self.lect2.setText(str(num3))
        dato1 = round(num2/num3, 2)
        num4 = self.blancoSpin.value()
        dato2 = round(num4/num3, 2)
        self.muestraDo.setText(str(dato1))
        self.guardarTxt()

    def guardarTxt(self):
        guardar = self.port1.readline()
        if self.cajita.isChecked(): 
                with open(self.lineEdit.text()+'.txt', 'a') as yourFile:
                    yourFile.write("%s\n" % guardar)

这是arduino代码。它只是发送随机值。

int n=1;
float a;
float b;

void setup(){

Serial.begin(9600);
}

void loop()
{
a = random(10, 30000);
a /= 100;
b = random(900,1100);
b /= 100;
Serial.print(n);
Serial.print(" ");
Serial.print(a);
Serial.print(" ");
Serial.println(b);
n +=1;
delay(1000);
}

有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

对于那些有同样问题的人,我终于使用线程解决了这个问题....在这里我粘贴部分修改后的代码:

class guardarTxt (QtCore.QThread):

    def __init__(self, texto, nombre):
        QtCore.QThread.__init__(self)
        self.nombre = nombre
        self.texto = texto

    def __del__(self):
        self.wait()

    def run (self):
        with open(nombre+'.txt', 'a') as yourFile:
            yourFile.write("%s\n" % texto)
        self.terminate()    

而且,在class Ventana中,我已更改self.guardarTxt()以获取以下内容:

nombre = self.lineEdit.text()
self.guardarTxt = guardarTxt(texto, nombre)
self.guardarTxt.start()