Arduino Python3 脚本 [英] Arduino Python3 script
问题描述
我正在尝试使用 Python3 脚本来控制 Arduino Mega.这是一个简单的脚本,用于从键盘中取出一行并通过 Arduino 回显.我从 http://petrimaki.wordpress.com/2013/04/28/reading-arduino-serial-ports-in-windows-7/.我发回的字符好像看不到了,可能是格式问题.
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.
这是格式问题吗?Unicode 到 ASCII 的问题?如何使用 Python 3 和 pySerial 读/写二进制/十六进制数据和 ASCII 文本?欢迎给 Python 新手任何建议.
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 脚本:
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 代码:
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);
}
}
输入:迅捷的赤狐
输出:
b''
b'I got: 84\r\n'
b'I got: 104\r\n'
b'I got: 101\r\n'
等等.
推荐答案
bytes(var.encode('ascii'))
好像没必要,直接用.encode()
code> 方法或 bytes()
函数,两者都不需要.您还可以对接收到的数据使用 .decode()
.
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.
异常 serial.SerialTimeoutException
是 写入超时时引发的,与阅读无关.
The exception serial.SerialTimeoutException
is raised on write timeouts, nothing to do with reading.
在Arduino代码中,尝试使用Serial.write()发送数据回来了.
In the Arduino code, try using Serial.write() to send the data back.
这篇关于Arduino Python3 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!