ARDUINO学习5——通信篇

串口通信简介

参考文章(大佬写的很好可以去看一下)
arduino支持的串行通信有UART,I2C和SPI三种通信协议方式
根据串行数据的传输方向,我们可以将通信分为单工,半双工,双工
单工
是指数据传输仅能沿一个方向,不能实现反向传输
半双工
是指数据传输可以沿两个方向,但不能同时进行传输
全双工
是指数据可以同时进行双向传输

硬件串口通信(UART)——HardwareSerial 类库

除了常见的函数外,另外比较常用的
peek()
功能:返回1字节的数据,但不会从接受缓冲区删除数据,与read()函数不同,read()函数读取该函数后,会从接受缓冲区删除该数据。
write()
功能:输出数据到串口。以字节形式输出到串口,它与print()的区别在于:当使用print()发送一个数据时,arduino发送的并不是数据本身,而是将数据转换为字符,再将字符对应的ASCII码发送出去,串口监视器收到ASCII码,则会显示对应的字符,因此使用print()函数是以ASCII码形式输出数据到串口; 而当使用write() 函数时,arduino发送的是数值本身。但串口监视器接收到数据后,会将数值当做ASCII码而显示其对应的字符。
例如,当使用serial.write(INT)输出一个整型数 123 时,显示出的字符为"{",因为ASCII码 123 对应的字符为"{"

软件模拟串口通信——softwareserial 类库使用

除HardwareSerial 类库外,arduino还提供了softwareserial类库,可将其他数字引脚通过程序模拟成串口通信引脚
通常将arduino上自带的串口成为硬件串口,而使用softwareserial类库模拟成的串口称为软件模拟串口
sofawareserial类库成员函数
其中定义的成员函数和硬件串口的类似
available(), begin(), read(), write(), print(), println(), peek(),函数用法相同
此外软串口还有如下成员函数
SofaWareSerial()
功能:这是SoftwareSerial类的构造函数,通过它可以指定软串口的RX和TX引脚
语法:SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin)
listen()
功能:开启软串口监听状态
arduino在同一时间仅能监听一个软串口,当需要监听某一串口时,需要对该对象调用此函数开启监听功能
overflow()
功能:检测缓冲区是否已经溢出。软串口缓冲区最多可保存64B的数据

实验

使用UART通信模式,需要两部分RX-TX, TX-RX的连接
两个arduino实现通信,一个uno,一个mega,uno端连接lcd1602,显示通信类容
mega的程序如下:

String device_mega = "";
String device_uno = "";
void setup() {
   
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial1.begin(9600);
}

void loop() {
   
  // put your main code here, to run repeatedly:
  if(Serial.available()>0){
   
    if(Serial.peek() != '\n')
      device_mega += (char)Serial.read();
    else{
   
      Serial.read();
      Serial.print("you said: ");
      Serial.println(device_mega);
      Serial1.println(device_mega);
      device_mega = "";
    }
  }

  if(Serial1.available()>0){
   
    if(Serial.available()>0){
   
      if(Serial1.peek() != '\n')
        device_uno += (char)Serial1.read();
      else{
   
        Serial1.read();
        Serial.print("the uno said: ");
        Serial.println(device_uno);
        device_uno = "";
      }
    }
  }
}

uno的程序如下

#include "LiquidCrystal.h"
#include "SoftwareSerial.h"
SoftwareSerial myserial(10,11);
String device_mega = "";
String device_uno = "";
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
void setup() {
   
  // put your setup code here, to run once:
  Serial.begin(9600);
  myserial.begin(9600);
  myserial.listen();
  lcd.begin(16,2);
  lcd.clear();
  
}

void loop() {
   
  // put your main code here, to run repeatedly:
  if(softSerial.available()>0){
   
    delay(100);
    lcd.clear();
    while(Serial.available()>0)
      lcd.write(Serial.read());
    device_mega = "";
  }
  if(Serial.available()>0){
   
	if(softSerial.
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值