怎样使用PySerial接口Python和Arduino

电子说

1.2w人已加入

描述

步骤1:安装

Arduino

下载后,打开终端并输入:

tar xfvz /Users/*Account*/Downloads/pyserial-2.6.tar.gz

cd pyserial-2.6

sudo python setup.py install

为确保所有安装正确的设备都打开空闲并输入在“导入序列号”中。如果没有错误出现,则一切正常。

您可以通过

ls /dev/tty.*

行检查可用的端口,步骤2:对Arduino进行编程

现在进行测试,将以下草图上传到Arduino。我不知道这在Arduino克隆上将如何工作。

void setup() {

Serial.begin(9600); // set the baud rate

Serial.println(“Ready”); // print “Ready” once

}

void loop() {

char inByte = ‘ ’;

if(Serial.available()){ // only send data back if data has been sent

char inByte = Serial.read(); // read the incoming data

Serial.println(inByte); // send the data back in a new line so that it is not all one long line

}

delay(100); // delay for 1/10 of a second

}

步骤3:程序空闲

下一步在Idle中创建一个新窗口并创建以下程序。

from time import sleep

import serial

ser = serial.Serial(‘/dev/tty.usbmodem1d11’, 9600) # Establish the connection on a specific port

counter = 32 # Below 32 everything in ASCII is gibberish

while True:

counter +=1

ser.write(str(chr(counter))) # Convert the decimal number to ASCII then send it to the Arduino

print ser.readline() # Read the newest output from the Arduino

sleep(.1) # Delay for one tenth of a second

if counter == 255:

counter = 32

请记住两点。要确定您的Arduino连接了哪个串行端口,请查看Arduino草图的右下角。不管是什么,都应该是Python程序第3行中的引号。

您还可以更改Python程序第3行和Arduino程序的第2行中的波特率,只要它们保持不变即可。程序运行后,它将打印出大多数ASCII字符。首先将它们发送到Arduino,然后将其发送回Python,然后打印出来的计算机。
        责任编辑:wv 

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分