Python从Arduino读取IMU数据并打印

时间:2018-08-26 19:34:15

标签: python arduino pyserial

我有Arduino代码(实际上是Teensy 3.2)通过串行发送数据

void loop()
{
  data1 = roll; // integer
  data2 = pitch; // integer 
  data3 = yaw; // integer

  byte buf1[4];
  buf1[0] = data1 & 255;
  buf1[1] = (data1 >> 8)  & 255;
  buf1[2] = (data1 >> 16) & 255;
  buf1[3] = (data1 >> 24) & 255;
  Serial.write(buf1, sizeof(buf1));

  byte buf2[4];
  buf2[0] = data2 & 255;
  buf2[1] = (data2 >> 8)  & 255;
  buf2[2] = (data2 >> 16) & 255;
  buf2[3] = (data2 >> 24) & 255;
  Serial.write(buf2, sizeof(buf2));

  byte buf3[4];
  buf3[0] = data3 & 255;
  buf3[1] = (data3 >> 8)  & 255;
  buf3[2] = (data3 >> 16) & 255;
  buf3[3] = (data3 >> 24) & 255;
  Serial.write(buf3, sizeof(buf3));

  while (micros() - loop_timer < 2500);
  loop_timer = micros();
}

我想接收数据并在python中打印它:

import serial
import time
import csv
import sys

PORT = '/dev/tty.usbserial-AL03QWTA'
BAUD = 115200

ser = serial.Serial(PORT, BAUD)

while True:
    data1 = ord(ser.read(1));
    data2 = ord(ser.read(1));
    data3 = ord(ser.read(1));
    data4 = ord(ser.read(1));
    roll = (data4*256*256*256 + data3*256*256 + data2*256 + data1);
    data5 = ord(ser.read(1));
    data6 = ord(ser.read(1));
    data7 = ord(ser.read(1));
    data8 = ord(ser.read(1));
    pitch = (data8*256*256*256 + data7*256*256 + data6*256 + data5);
    data9 = ord(ser.read(1));
    data10 = ord(ser.read(1));
    data11 = ord(ser.read(1));
    data12 = ord(ser.read(1));
    yaw = (data12*256*256*256 + data11*256*256 + data10*256 + data9);
    print(roll + "," + pitch + "," + yaw)

似乎接收到的数据混合在一起,不能正确接收。知道Arduino每隔0.0025s更新一次数据,最好的方法是从Arduino向python发送数据(滚动,俯仰和偏航)。

0 个答案:

没有答案
相关问题