0
我正在從Arduino讀取vPython中的串行數據並在readline期間獲取數據錯誤。有時它會連續讀兩行,這次我錯過了逗號,因爲我試圖在照片中顯示。代碼如下。Python誤讀串行數據
這是什麼原因造成的?
[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("");
}
如果將串口設置爲以9600波特運行,會發生這種情況嗎? – pyInTheSky
最可能發生的事情是串行端口的切換太快,所以你得到一個不正確的讀取邊緣... https://www.sparkfun.com/tutorials/215 – pyInTheSky
這發生在9600波特作爲好。我會查找教程,謝謝你的鏈接。我會嘗試新的電纜,看看是否是這個問題。我認爲你對噪音是正確的,因爲有時在錯誤之前讀取的最後一行是兩行作爲一行,這意味着讀取錯誤每次都略有不同。 –