I'm trying to use a Python3 script to control an Arduino Mega. This is a simple script to take a line from the keyboard and echo it back through the Arduino. I started with a working Python 2 script from http://petrimaki.wordpress.com/2013/04/28/reading-arduino-serial-ports-in-windows-7/. I can't seem to get the characters I sent back, which is probably a formatting issue.
Is this a formatting issue? unicode to ASCII issue? How do I read/write binary/hex data and ASCII text with Python 3 and pySerial? Any advice for a Python newbie is welcome.
Python 3 script:
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'))
Arduino code:
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);
}
}
Input: The quick red fox
Output:
b''
b'I got: 84\r\n'
b'I got: 104\r\n'
b'I got: 101\r\n'
and so on.
T, 104 ish, 101 ise.