Arduino Python3 script

六眼飞鱼酱① 提交于 2021-02-07 09:44:28

问题


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.


回答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.



来源:https://stackoverflow.com/questions/24682354/arduino-python3-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!