2014-07-10 2 views
2

Arduino Mega를 제어하기 위해 Python3 스크립트를 사용하려고합니다. 이것은 키보드에서 한 줄을 가져와 Arduino를 통해 다시 에코하는 간단한 스크립트입니다. http://petrimaki.wordpress.com/2013/04/28/reading-arduino-serial-ports-in-windows-7/에서 작동하는 Python 2 스크립트로 시작했습니다. 내가 보낸 문자를 다시 가져올 수없는 것 같습니다. 아마도 형식 문제 일 것입니다.Arduino Python3 스크립트

서식 문제입니까? ASCII 문제에 대한 유니 코드? Python 3 및 pySerial을 사용하여 2 진수/16 진수 데이터와 ASCII 텍스트를 읽고 쓰려면 어떻게해야합니까? 파이썬 초보자를위한 조언은 환영합니다.

파이썬 3 스크립트

import serial 
import time 

ser = serial.Serial('COM8', 9600, timeout=0) 
var = input("Enter something: ") 
print(var) 
ser.write(bytes(var.encode('ascii'))) 
while 1: 
    try: 
     print(ser.readline()) 
     time.sleep(1) 
    except ser.SerialTimeoutException: 
     print(('Data could not be read')) 

아두 이노 코드 :

int incomingByte=0; 

void setup() { 
    // Open serial connection. 
    Serial.begin(9600); 
} 

void loop() { 
    if (Serial.available() > 0) { 
    // Read the incoming byte. 
    incomingByte = Serial.read(); 

    // Echo what you got. 
    Serial.print("I got: "); 
    Serial.println(incomingByte); 
    } 
} 

입력 : 빠른 붉은 여우

출력 :

b'' 
b'I got: 84\r\n' 
b'I got: 104\r\n' 
b'I got: 101\r\n' 

등등.

+3

메시지를받는 중, 대신 문자 대신 코드 포인트가 인쇄됩니다. ASCII 84는'T', 104는'h', 101은'e'입니다. – MattDMo

+2

ASCII를 다시 얻으려면 구문을 알고 있습니까? – Kathy

답변

0

bytes(var.encode('ascii'))은 불필요한 것처럼 보입니다. 단지 .encode() 방법이나 bytes() 기능을 사용하십시오. 둘 다 필요하지 않습니다. 받은 데이터에 .decode()을 사용할 수도 있습니다.

예외 serial.SerialTimeoutExceptionraised on write timeouts이며 읽기와 관련이 없습니다.

Arduino 코드에서 Serial.write()을 사용하여 데이터를 다시 보냅니다.