Arduino MEGA2560软串口使用方法

通常将Arduino上自带的串口称为硬串口,而使用SoftwareSerial类库模拟成的串口称为软串口。软串口是由程序模拟生成的,使用起来没有硬串口稳定,而且和硬串口一样,波特率越高越不稳定。

软串口通过AVR芯片的PCINT中断功能来实现,在Arduino UNO上,所有引脚都支持PCINT中断,因此所有引脚都可设置为RX接收端。但是在Arduino MEGA上能被设置为RX的引脚有10,11,12,13,50,51,52,53,62,63,64,65,66,67,68,69。在Arduino Leonardo上能被设置为RX的引脚有8,9,10,11,14(MISO),15(SCK),16(MOSI)。

        本文采用两块Arduino MEGA板子做实验,A板使用Serilal串口和电脑1通信,Serial1串口和B板通信;B板使用Serial和电脑2通信,软串口(10,11引脚分别为RX,TX)和A板通信。接线关系为:
 

A板B板
18 TX110
19 RX111

A板程序为:

void setup()
{
  Serial.begin(9600); 
  Serial1.begin(9600); 
}
String device_A_String = "";
String device_B_String = "";
void loop()
{
  if (Serial.available() > 0) 
  {
    if(Serial.peek() != '\n')
    {
      device_A_String += (char)Serial.read();
    }
    else
    {
      Serial.read();
      Serial.print("you said:");
      Serial1.println(device_A_String);
      Serial.println(device_A_String);
      device_A_String = "";
    }
  }
  if (Serial1.available() > 0)
  {
    if(Serial1.peek() != '\n')
    {
      device_B_String += (char)Serial1.read();
    }
    else
    {
      Serial1.read();
      Serial.print("device B said:");
      Serial.println(device_B_String);
      device_B_String = "";
    }
  }
}

B板程序为:

#include <SoftwareSerial.h>
SoftwareSerial softSerial(10,11); //定义虚拟串口名为serial,rx为10号端口,tx为11号端口
void setup()
{
  softSerial.begin(9600); //初始化虚拟串口
  Serial.begin(9600); //初始化Arduino默认串口
  softSerial.listen();
  Serial.println(softSerial.isListening());
}
String device_A_String = "";
String device_B_String = "";
void loop()
{
  if (Serial.available() > 0)
  {
    if(Serial.peek() != '\n')
    {
      device_B_String += (char)Serial.read();
    }
    else
    {
      Serial.read();
      Serial.print("you said:");
      Serial.println(device_B_String);
      softSerial.println(device_B_String);
      device_B_String = "";
    }
  }
  
  if (softSerial.available() > 0) 
  {
    if(softSerial.peek() != '\n')
    {
      device_A_String += (char)softSerial.read();
    }
    else
    {
      softSerial.read();
      Serial.print("device A said:");
      Serial.println(device_A_String);
      device_A_String = "";
    }
  }
}

联系我们

 

 

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值