Python 误读串口数据

Python misreads serial data

我正在从 Arduino 读取 vPython 中的串行数据,并在 readline 期间收到数据错误。有时它会连续读取两行,而这次它漏掉了一个逗号,因为我试图在照片中显示。代码如下。

这是什么原因造成的?

[img]http://i.imgur.com/cAw7De1.png

Python代码:

arduinoSerialData=serial.Serial('/dev/cu.usbmodem1421',115200) 
while (1==1): #loops forever
     rate (30) # tells vPython to run this loop (times/sec)
     while(arduinoSerialData.inWaiting()==0): 
      pass #do nothing

     sensorCallInfo = arduinoSerialData.readline()
     print sensorCallInfo 

     dataNums = sensorCallInfo.split(',') 

     x1 = float(dataNums[0]) 
     y1 = float(dataNums[1])
     z1 = float(dataNums[2])
     sysCal = int(dataNums[3]) 
     gyroCal = int(dataNums[4])
     accelCal = int(dataNums[5])
     magCal = int(dataNums[6]) 

     print x1, y1, z1, sysCal, gyroCal, accelCal, magCal
     print
     print

Arduino 代码:

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

#define BNO055_SAMPLERATE_DELAY_MS (50)
imu::Vector<3> linearAccel; 
uint8_t systemcal, gyrocal, accelcal, magcal = 0; 
Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup(void)
{
  Serial.begin(115200);
  while (!Serial); 

  if (!bno.begin()) //checks for sensor to start
  {
    Serial.print("No sensor detected.  Check wiring or I2C address.");
    while (1);
  }

  bno.setExtCrystalUse(true);
}

void loop(void)
{
  bno.getCalibration(&systemcal, &gyrocal, &accelcal, &magcal); 
  linearAccel = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL); 

  outputForPython();
  delay(BNO055_SAMPLERATE_DELAY_MS);
}


void outputForPython()
{
  Serial.print(linearAccel.x());  Serial.print(",");
  Serial.print(linearAccel.y());  Serial.print(",");
  Serial.print(linearAccel.z());  Serial.print(",");
  Serial.print(systemcal, DEC);   Serial.print(",");
  Serial.print(gyrocal, DEC);     Serial.print(",");
  Serial.print(accelcal, DEC);    Serial.print(",");
  Serial.print(magcal, DEC);      Serial.println("");
}

您很可能在线路上收到噪音。您可以尝试调整波特率或尝试使用不同的电缆。 Sparkfun 在这个问题上有一些很好的细节:https://www.sparkfun.com/tutorials/215——另一种方法是根据您需要的可靠性使用以太网而不是串行进行通信。我想你会以较低的波特率获得更多的成功。