zoukankan      html  css  js  c++  java
  • 树莓派和Arduino之间通过串口进行通信

    最近在研究树莓派和Arduino之间通过串口进行通信,参考了度娘道德一些程序,实际上网上找到的程序都来自同一家,并且都是同样的错误,在这里就不拆穿他们了,我在这里拿出自己实际测试可以用的程序供大家参考(学生党学习还是挺忙的,好不容易有空码一篇博文,希望看后感觉好的看管留个赞再走,万分感谢):

    话不多说了,talk is cheap ,now, show the code

    step1:

    首先是Arduino代码:

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);    //设置串口速率9600
    }
    
    void loop() {
      // put your main code here, to run repeatedly:
        if(Serial.available())
        {
        if('s'==Serial.read())    //判决条件:如果读到的字符串是s,则执行下面的输出
          Serial.println("Hello RaspberryPi,I am Arduino,Coonncetion successiful!");   //输出的结果
        }
    }

    通过ArduinoIDE将上述代码编译并上传给Arduino

    step2:

    在树莓派中编写如下代码,并命名为connect_arduino.py:

    1 import serial
    2 
    3 ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)  #/dev/ttyACM0是设备的串口号,一般将arduino通过USB线接到树莓派上后都会显示该设备号,也可能别的,具体看自己情况
    4 
    5 while 1:
    6     send = 's'
    7     ser.write(send.encode())   #此处一定要对字符's'使用encod()方法,否则会报错
    8     responce = ser.readall()
    9     print(responce)

    step3:

    将Arduino通过USB线接到树莓派上去,如图(来自网上,侵删)

    然后执行上述程序python connect_arduino.py

    如果报错可能是没有安装serial模块;可使用如下命令安装

    sudo apt-get install python-serial

    如果没有问题,应该会显示如下结果

  • 相关阅读:
    Core Foundation 框架
    iOS下微信语音播放之切换听筒和扬声器的方法解决方案
    http://blog.sina.com.cn/s/blog_6f40a0e70100p98l.html
    web移动开发最佳实践之js篇
    iOS框架介绍(五)Core Services 层
    针式PKM V9.36 最新版(2012_03_29)
    通过10000个小时的个人知识管理,将自己的智慧潜力挖掘出来
    下载 针式PKM V9.08 版
    如何避免重复造轮子问题?
    和evernote比 针式PKM有什么特色?
  • 原文地址:https://www.cnblogs.com/wind-under-the-wing/p/11923757.html
Copyright © 2011-2022 走看看