一:介绍
Arduino硬件在0pin和1pin口支持串行通信(电脑通过USB连接),其实是使用了一个(内置芯片)称为UART的芯片。这种硬件允许ATmega即使正在进行其他任务时也能通信,只要serial的64 byte缓存有其他的空间。(硬件支持的)
使用SoftwareSerial Library可以在Arduino的任何数字引脚上进行通信,因此软件端口数可以扩展,并且波特率可达115200bps。SoftwareSerial Library的其中一个参数指定了相关协议。起初SoftwareSerial Library用在Arduino 1.0的板子上,但之后,有个叫Mikal Hart的家伙编写了NewSoftSerial library,这个库改进了SoftwareSerial Library,优点更多,因此之后的版本都是基于这个库的。(这种其实是软件模拟通信的,具有很多局限性)
二:局限性
1.如果使用多个软件串行端口,每次只有一个端口可以接收数据;
2.Mega和Mega2560板子只有以下接口可以使用:
RX:10,11,12,13,14,15,50,51,52,53,A8(62),A9(63),A10(64),A11(65),A12(66),A13(67),A14(68),A15(69);
而Leonardo 和Micro为:
RX: 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI)。
如果你的程序需要同步数据流,则应该参考:AltSoftSerial library库的相关操作。
三:函数
(1)SoftwareSerial()
(2)available()
(3)begin()
(4)isListening()
(5)overflow()
(6)peek()
(7)read()
(8)print()
(9)println()
(10)listen()
(11)write()
具体介绍见:http://www.arduino.cc/en/Reference/SoftwareSerial
四:示例
/*
Software serial multple serial test
Receives from the hardware serial, sends to software serial.
Receives from software serial, sends to hardware serial.
The circuit:
* RX is digital pin 10 (connect to TX of other device)
* TX is digital pin 11 (connect to RX of other device)
Note:
Not all pins on the Mega and Mega 2560 support change interrupts,
so only the following can be used for RX:
10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69
Not all pins on the Leonardo support change interrupts,
so only the following can be used for RX:
8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI).
created back in the mists of time
modified 25 May 2012
by Tom Igoe
based on Mikal Hart's example
This example code is in the public domain.
*/
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup()
{
// Open serial communications and wait for port to open:
Serial.begin(57600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
Serial.println("Goodnight moon!");
// set the data rate for the SoftwareSerial port
mySerial.begin(4800);
mySerial.println("Hello, world?");
}
void loop() // run over and over
{
if (mySerial.available())
Serial.write(mySerial.read());
if (Serial.available())
mySerial.write(Serial.read());
}