Python脚本无法正确读取Arduino

时间:2014-11-18 22:34:13

标签: c arduino

我试图让我的Arduino将数据发送到我的计算机上的python脚本,并且由于某种原因,python脚本正在错误地读取数据。具体来说,它正确读取数据大约4-5接收然后它开始失去同步。以下是我的代码:

Arduino的:

struct sensorData
{
    char beginPad[5];
    int data0;
    char pad0;
    //int data1;
    //char pad1;
    //int data2;
};

union data
{
    unsigned char buffer[sizeof(sensorData)];
    sensorData vars;
};

data sendData;

void setup()
{
    Serial.begin(9600);

    static char temp[5] = {0, 1, 2, 3, 4};
    memcpy(sendData.vars.beginPad, temp, 5);
    sendData.vars.pad0 = 0;
    //sendData.vars.pad1 = 0;
}

void loop()
{
    sendData.vars.data0 = (256);
    //sendData.vars.data1 = (512);
    //sendData.vars.data2 = (1024);
    Serial.write(sendData.buffer, sizeof(sensorData));
    delay(100);
}

的Python:

import serial

class SensorData:
    def __init__(self, ser_obj, s_dict, p_start, p_len):
        self.ser = ser_obj
        self.sensor_buffer = s_dict
        self.num_sensors = len(s_dict)
        self.pad_start = p_start
        self.pad_len = p_len
        self.wait_for_beginning(p_start)

    def poll(self):
        for i in range(self.num_sensors):
            tmp = self.ser_read()
            tmp+=(self.ser_read()<<8)
            print tmp
            self.sensor_buffer.values()[i].append(tmp)
            self.ser_read()
        return self.sensor_buffer

    def ser_read(self):
        while True:
            try:
                data = ord(self.ser.read())
                break
            except:
                continue
        return data

    def wait_for_beginning(self, start):
        while True:
            while(self.ser_read() != 0): continue
            flag = 0
            for i in range(1, self.pad_len):
                if i == self.ser_read(): continue
                else:
                    flag = 1
                    break
            if flag: continue
            else: break

    def wait_for_end(self):
        while True:
            pad = self.ser_read()
            if pad == self.pad_len-1:
                break

#END OF CLASS
#main.py

def serial_poll( s_dict ):
    dev = serial_init()
    s = SensorData( dev, s_dict, 0, 5 )
    while True:
        sensor_buffer = s.poll()
        s.wait_for_end()
        print sensor_buffer

def serial_init():
    ser = serial.Serial()
    ser.baudrate = 9600
    ser.port = '/dev/ttyACM0'
    ser.open()

    return ser

if __name__ == "__main__":
    global sensor_buffer
    sensor_buffer = { 'sensor1': [] }

    serial_thread = threading.Thread( target=serial_poll, args=(sensor_buffer, ) )
    serial_thread.daemon = True
    serial_thread.start()

    while True:
        time.sleep( .1 )

我在新线程上运行串行函数,因为我在此应用程序中还有其他事情。我基本上试图将一些我从Arduino硬编码的数据发送到Linux计算机。我在实际数据之间填充以分隔它。起初我以为我得到缓冲区溢出,因为每个数据缓冲区长度超过14个字节。我缩短了它,问题仍然存在。然后我尝试添加延迟,因为它可能发送数据太快。这也没有任何帮助,现在我没有想法。如果您需要我更具体,请告诉我。

0 个答案:

没有答案