Arduino库教程-Software Serial-Software Serial Example
Software Serial Example
Arduino和genuino板内置的引脚0和1支持串口通信,但是如果你需要更多的串行端口怎么办?SoftwareSerial 库已经发展到允许串行通信发生在你开发板的其他数字引脚上,用软件复制硬件RX和TX线的功能。这可能是非常有用的,尤其是需要与两个串行功能的设备进行通信,或只和一个设备,但要让主要的串行端口开放来调试。
在下面的例子中,你的Arduino或genuino板的数字引脚pin10和11作为虚拟的RX和TX串行线使用。虚拟的RX引脚设置成等待通过主串口线的任何进入的信息,然后回波(虚拟TX线输出数据)。相反,任何在虚拟RX上收到的东西将被发送到硬件TX上。
硬件要求
- Arduino or Genuino Board
电路
- 这个例子没有额外电路。确保你的Arduino或genuino开发板通过USB是能串口通讯连接到电脑。
图由 Fritzing 软件绘制
原理图
图由 Fritzing 软件绘制
样例代码
/*
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 and Micro 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 native USB port 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());
}
}
[Get Code]
更多
- The Software Serial Library
- TwoPortReceive – 当接收到一个特殊字符时,两个串口端口由一个切换到另一个的数据来接受数据。.
- MultiSerialMega - 使用在Arduino和Genuino Mega上的两个有效串行端口。
- Serial Call Response - 通过呼叫-响应(握手)方法来发送多个变量。
- Serial Call Response ASCII - 通过呼叫-响应(握手)方法来发送多个变量,并且在发送前ASCII编码这些值。
获取最新文章: 扫一扫右上角的二维码加入“创客智造”公众号