Arduino已经通过硬件实现了在pin0和pin1的串口通信,但是同时这个串口也提供PC到Arduino的通信。这种硬件的通信时通过Arduino内部的一个叫UART的chip实现的。只要串口通信的缓冲区足够,UART实现了在处理机执行其它任务的时候接收数据。
SoftwareSerial library通过软件的形式,允许串口通信在其它的数字针脚进行,这样的话就可能有多个软件串口。
SoftwareSerial library是在NewSoftSerial library的基础上改进的,并且放进了Arduino 1.0及以后的版本的核心中去了。
(1)如果用软件模拟多个串口,那么在同一时刻只有一个串口可以接收数据。
(2)由于串口接收数据时通过中断的形式实现的,所以如果用其他的pin接收数据,那么找个pin一定要支持中断才可以。Mega和Mega2560支持中断的pin有: 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),所以只有这些pin 可以用来作为RX。
(3)LEONARDO只有8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI)可以用来作为RX。
例子代码:
1 /*
2 Software serial multple serial test 3
4 Receives from the hardware serial, sends to software serial. 5 Receives from software serial, sends to hardware serial. 6
7 The circuit: 8 * RX is digital pin 10 (connect to TX of other device) 9 * TX is digital pin 11 (connect to RX of other device) 10
11 Note: 12 Not all pins on the Mega and Mega 2560 support change interrupts, 13 so only the following can be used for RX: 14 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69 15
16 Not all pins on the Leonardo support change interrupts, 17 so only the following can be used for RX: 18 8, 9, 10, 11, 14 (MISO), 15 (SCK), 16 (MOSI). 19
20 created back in the mists of time 21 modified 25 May 2012 22 by Tom Igoe 23 based on Mikal Hart's example 24
25 This example code is in the public domain. 26
27 */
28 #include <SoftwareSerial.h>
29
30 SoftwareSerial mySerial(10, 11); // RX, TX
31
32 void setup() 33 { 34 // Open serial communications and wait for port to open:
35 Serial.begin(57600); 36 while (!Serial) { 37 ; // wait for serial port to connect. Needed for Leonardo only
38 } 39
40
41 Serial.println("Goodnight moon!"); 42
43 // set the data rate for the SoftwareSerial port
44 mySerial.begin(4800); 45 mySerial.println("Hello, world?"); 46 } 47
48 void loop() // run over and over
49 { 50 if (mySerial.available()) 51 Serial.write(mySerial.read()); 52 if (Serial.available()) 53 mySerial.write(Serial.read()); 54 }
通过调用这个函数能新建一个串口对象,同时调用SoftwareSerial.begin()启动通信
rxPin:相对于Arduino板子来说,接收串口数据
txPin:相对于Arduino板子来说,发送串口数据
1 #define rxPin 2
2 #define txPin 3
3
4 // set up a new serial port
5 SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);