2012-07-03 60 views
3

我试图通过Python脚本连续读取我的Arduino Nano数据。但是大多数情况下,readline会抛出异常或返回损坏的数据,如丢失数字。从Arduino连续数据流到Python(失败readlines)

这里的连接部分:

Arduino的代码:

void loop() { 
    // Send data only when you receive data: 
    if (Serial.available() > 0) { 

     // Check if it's the right signal. 
     if (Serial.read()=='S') { 
      // Send a string containing the rows and cols number. 
      send_rows_cols(); 

     } // if(Serial.read()=='S') 
     else { 
      send_data(); 
     } // END: else if(Serial.read()=='Y') 
    }// if(Serial.available() > 0) 
} 

send_rows_cols(),我使用Serial.write,因为它的工作原理,但在send_data()我不得不用Serial.println()将数据发送回。

Python部分。在合法的价值观返回之前,我不得不使用这种荒谬的运行方式。

import serial 
import time 

locations=['/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyUSB3', 
'/dev/ttyS0','/dev/ttyS1','/dev/ttyS2','/dev/ttyS3'] 

for device in locations: 
    try: 
     print "Trying...",device 
     arduino = serial.Serial(device, 9600) 
     break 
    except: 
     print "Failed to connect on",device 

rows_cols ='' 

try: 

    while True: 
     arduino.write('S') 
     rows_cols = str(arduino.readline()) 
     print len(rows_cols) 
     print rows_cols 
     if (len(rows_cols)>3): 
      break 

except: 
    print "Failed to send!" 

到目前为止,它可以在一条或两条读线之后工作。这是负担得起的。不过后来,我不得不使用更疯狂的代码。发送一个字符从Python到Arduino,这样连接就不会死掉,然后你可以看到Arduino必须等待那个字符。在Arduino收到该字符后,它会发回我想要的数据(用逗号分隔的一串数字)。

这最后一个Python部分是它从Arduino发送的'Y'字符和readline,一次又一次地发送,直到没有异常或损坏的数据为止。这么多循环没有。

我想要的是一种让我的Arduino不断数据的方式,而不是始终保持“握手”状态,并且数据不会始终被垃圾回收。

有没有这样的方式?也许是串行超时选项?

+0

如果您想要执行更高级别的连接管理,我会考虑使用类似库扭曲。然后,您可以使用“ReconnectingClientFactory”连接到设备,以便在连接丢失时自动重新连接。由于扭曲是事件驱动的,它会让你更容易理解你的“保持活力”的呼叫。看到这里开始:http://stackoverflow.com/questions/4715340/python-twisted-receive-command-from-tcp-write-to-serial-device-return-response – jozzas

回答

4

你还没有打开Arduino IDE串口监视器吗?我花了一个“愉快”的晚上调试我的“Python到Arduino接口代码”,然后才意识到我已经把它打开了,并且偶尔吃到了字符:)

我已经使用了非常简单的Serial.write()Serial.println()代码readline()一次运行几十分钟的连续“命令/响应”测试(数千行发送和接收)

+0

你的意思是串行监视器?因为终端总是在Arduino IDE的底部打开。 – storedope

+0

对不起,是的,这就是我的意思。如你所说更新 –

+0

。出于某种原因,在从python读取数据时打开串行监视器会搞砸一切。非常感谢您的帮助。除了我之外,这可能会成为拯救生命的人。 – storedope