Arduino的多串口通信问题

对于Arduino的串口通信,主要有硬件串口和软串口。当然硬件串口相对于软串口要可靠地多。
以下将对mega2560的硬件串口和软串口进行描述。
* 硬件串口*
ArduinoMega有四个硬件串口,想想也够用了吧,不过要是还不够用那就加软串口喽。
串口与引脚对应为:
0——Rxd0 1——-Txd0
19—-Rxd1 18—–Txd1
17—-Rxd2 16—–Txd2
15—-Rxd3 14—–Txd3
我们通常写的Serial.begin(9600);其实就是默认打开并对串口0的波特率设定。
这里我们主要用到两个串口,Serial0和Serial1.我们主要实现两个串口之间进行数据交互,发什么对应的就接收什么。
准备工具:USB转TTL串口线两根(主要用来连接PC机查看串口数据)
arduinomega2560或arduinoUNO一个(其实都是一样的UNO只有一个硬件串口当然我们用软串口)
STEP1:连线,原装串口线正常连接(连接的为串口0),主要是串口3的连接,USB-TTL串口线有四根线,对应为GND黑、VCC红、TXD绿、RXD白,对应连接到Mega2560的引脚。VCC和GND不多讲。Txd连Rxd,Rxd连Txd。废话不多说,上图:

这里写图片描述

连接完成后上代码,很短很简单:

String inputString;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial3.begin(115200);
}

void loop() {
  // put your main code here, to run repeatedly:

}
void serialEvent(){
  while(Serial.available()){
    char inChar = (char)Serial.read();   //every time receive one char at the same time remove this char
    delayMicroseconds(1000);             //complete receive next char value by dalay(1ms)
    inputString +=inChar;                //concatenate char into Strings
  }
  Serial3.print(inputString);
  inputString="";                        //empty the String 
}
/************************/
void serialEvent3(){
  while(Serial3.available()){
    char inChar = (char)Serial3.read();   //every time receive one char at the same time remove this char
    delayMicroseconds(1000);             //complete receive next char value by dalay(1ms)
    inputString +=inChar;                //concatenate char into Strings
  }
  Serial.print(inputString);
  inputString="";                        //empty the String 
}

注意喽,这里我的波特率是115200,你可以改成9600或者其他。接着就是调试了,随便的串口助手软件都可以,分别对应打开COM口。然后发个信息看,不论你发什么,对应的就能接收什么,当然对应也能接收。
代码解析
我们定义了一个String类型的inputString变量,这个主要存储从缓冲区读取进来的字符,同时也起到一个连接字符串的作用。
Serial.begin(115200); Serial3.begin(115200);这两句分别打开串口0和3 。
void serialEvent();和void serialEvent3();主要是监听函数,一旦缓冲区接收到了数据,就会执行此函数,当然对应串口0和3.
char inChar = (char)Serial3.read(); 读取缓冲区数据,一次读取一个字符,并移除。
delayMicroseconds(1000); 延时1ms等待完成下一个读取。
inputString +=inChar;连接字符串并存储在变量inputString内。
Serial.print(inputString);将读取的数据发送到串口,这个是对应的,比如从串口0读取的数据就发送到串口3,从串口3读取的数据就发到串口0.
inputString=”“;最后这一句为变量清空,以便于下一次存储。代码对应有注释,由于IDE不支持中文就上English啦。

猜你喜欢

转载自blog.csdn.net/qq_41751237/article/details/81630612