Arduino Python3脚本 [英] Arduino Python3 script

查看:135
本文介绍了Arduino Python3脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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()方法或 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 异常是在写入超时时引发的与阅读无关.

在Arduino代码中,尝试使用 Serial.write()发送数据回来.

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

这篇关于Arduino Python3脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆