树莓派arduinoUSB串口通信

安装serial,用于串口通信
sudo apt-get install python-serial
将Arduino用USB线连接到树莓派的USB,在树莓派中输入(注意ls后有一个空格)
Ls /dev/tty*
查看两者连接端口的名字。查看是否出现ttyACM0或ttyUSB0。连接uno出现ttyACM0,连接mega2560出现ttyUSB0。看到ttyACM0或ttyUSB0就说明二者可以通讯了(树莓派上安装了arduino IDE的也可以通过它看开发板的串口号)
在这里插入图片描述

另外硬件通信要用到树莓派的GPIO,那嚒需要安装GPIO库。树莓派中安装python的GPIO模块(库文件),在树莓派中总链接不上,所以建议直接登录网址手动下载,并且可以选择最新版本(博主此时用的是RPi.GPIO-0.6.3)

https://sourceforge.net/projects/raspberry-gpio-python/files/

通过SSH方式(不在此介绍,博主用的是filezilla进行SSH传输)传输到树莓派中

tar xvzf RPi.GPIO-0.6.3.tar.gz(tar解压)

cd RPi.GPIO-0.6.3 (进入解压后的文件夹)

sudo python setup.py install (安装GPIO库文件

作者:GPNU-IOT先生
来源:CSDN
原文:https://blog.csdn.net/qq_18402617/article/details/81414541
版权声明:本文为博主原创文章,转载请附上博文链接!

代码例一
编写arduino端通信代码
void setup()
{
Serial.begin(9600); // 9600 bps
}
void loop()
{
if ( Serial.available())
{
if(‘s’ == Serial.read())
Serial.println(“Hello Raspberry,I am Arduino.”);
}
}

编写树莓派端代码(写到python文件中,保存为xxx.py
在这里插入图片描述
import serial #import serial module
ser = serial.Serial(’/dev/ttyACM0’, 9600,timeout=1); #open named port at 9600,1s timeot

#try and exceptstructure are exception handler
try:
while 1:
ser.write(‘s’);#writ a string to port
response = ser.readall();#read a string from port
print response;
except KeyboardInterrupt:
ser.close()
上面代码在树莓派中保存为communication.py文件。注:这里千万不要命名为serial.py,否则后面运行会出现 AttributeError: ‘module’ object has no attribute ‘Serial’ 的错误。
对代码的简单说明:树莓派向arduino发送一个字符‘s’,arduino向树莓派回复字符串“hello raspberry,i am arduino” 在树莓派终端运行
sudo python communication.py

在这里插入图片描述
代码例二
arduino端通信代码
int temp,data;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
temp=analogRead(0);
temp = (long)100*temp/1024;
Serial.print(“db:”);
Serial.println(temp);
delay(1000);
}
树莓派代码:(写到python文件中,保存为xxx.py
在这里插入图片描述
import serial
ser = serial.Serial(’/dev/ ttyACM0’, 9600, timeout=1)
ser.write(“testing”)
try:
while 1:
response = ser.readline()
print response
except KeyboardInterrupt:
ser.close()
然后将Arduino的程序上传到开发板,连接好电路之后运行树莓派的程序,运行截图如下:

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值