魔镜开发日记(一)软件模拟串口通信--SoftwareSerial库的使用

项目涉及:Arduino与蓝牙模块通信

通常我们将Arduino UNO上自带的串口称为硬件串口,而使用SoftwareSerial类库模拟成的串口,称为软件模拟串口(简称软串口)。

  • 硬件串口:0,1引脚,分别为RX,TX
    软串口接收引脚波特率建议不要超过57600

SoftwareSerial类成员函数

该类库不在Arduino核心类库中,需要进行声明

SoftwareSeial()

  • 作用:通过它指定软串口的RX,TX引脚
  • 语法:SoftwareSerial mySerial= SoftwareSerial(rxPin, txPin)
    SoftwareSerial mySerial(rxPin, txPin)
  • 参数:myserial:用户自定义软件串口对象
    rxPin:软串口接收引脚
    txPin:软串口发送引脚

listen()

  • 作用:开启软串口监听状态
    Arduino在同一时间仅能监听一个软串口
  • 语法:myserial.listen()

isListening()

  • 作用:监测软串口是否正在监听状态。
  • 语法:mySerial.isListening()
  • 参数:
    mySerial:用户自定义的软件串口对象
  • 返回值:
    Boolean型
    True:正在监听
    False:没有监听

end()

  • 作用:停止监听软串口。
  • 语法:mySerial. end()
  • 参数:
    mySerial:用户自定义的软件串口对象
  • 返回值:
    Boolean型
    True:关闭监听成功
    False:关闭监听失败

overflow()

  • 作用:检测缓冲区是否溢出。
  • 语法:mySerial.overflow()
  • 参数:mySerial:用户自定义的软件串口对象
  • 返回值:
    Boolean型
    True:溢出
    False:没有溢出

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*
Arduino UNO软串口通信
通过listen()切换监听软串口
*/

#include <SoftwareSerial.h>
SoftwareSerial portOne(10, 11);
SoftwareSerial portTwo(8, 9);

void setup() {
Serial.begin(9600);
while (!Serial) {
}

portOne.begin(9600);
portTwo.begin(9600);
}

void loop() {
//监听1号软串口
portOne.listen();

Serial.println("Data from port one:");
while (portOne.available() > 0) {
char inByte = portOne.read();
Serial.write(inByte);
}

Serial.println();
//监听2号软串口
portTwo.listen();

Serial.println("Data from port two:");
while (portTwo.available() > 0) {
char inByte = portTwo.read();
Serial.write(inByte);
}

Serial.println();
}