2

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.

2
  • 3
    You are receiving the message, they're just printing the codepoint instead the character. ASCII 84 is T, 104 is h, 101 is e. Commented Jul 10, 2014 at 17:13
  • 2
    Do you know the syntax to get ASCII back? Commented Jul 15, 2014 at 15:39

1 Answer 1

1

bytes(var.encode('ascii')) seems unnecessary, just use the .encode() method or the bytes() function, no need for both. You can also use .decode() on the data that you receive.

The exception serial.SerialTimeoutException is raised on write timeouts, nothing to do with reading.

In the Arduino code, try using Serial.write() to send the data back.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.