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

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

  • 相关阅读:
    设计算法,求AB两个整数集合的交集
    C++函数传递指针面试题
    C++构造函数、析构函数与抛出异常
    c++ 虚函数表解析
    c++ 对象的内存布局
    09 构造函数能调用虚函数吗?
    C++构造函数初始化顺序
    计数排序,基数排序和桶排序
    80 求论坛在线人数
    79 两个整数集合A和B,求其交集
  • 原文地址:https://www.cnblogs.com/wind-under-the-wing/p/11923757.html
Copyright © 2011-2022 走看看