Arduino MEGA2560与蓝牙的通信(玄学)问题

使用Arduino UNO和HC05进行通信的时候,会用到一个语句

SoftwareSerial BT(10, 11);

这是定义一个SoftwareSerial对象:BT,并初始化了RX和TX的引脚,这之后才能通过BT对象对蓝牙进行操作。

但当与HC05通信时的单片机变成MEGA的时候,事情就变得玄学了起来。

某位小伙伴彻夜的实验表明,这条语句似乎对MEGA并不会起什么作用…

经过一番查找,我在Arduino的库文件里找到了这几条语句:

// These serial port names are intended to allow libraries and architecture-neutral
// sketches to automatically default to the correct port name for a particular type
// of use.  For example, a GPS module would normally connect to SERIAL_PORT_HARDWARE_OPEN,
// the first hardware serial port whose RX/TX pins are not dedicated to another use.
//
// SERIAL_PORT_MONITOR        Port which normally prints to the Arduino Serial Monitor
//
// SERIAL_PORT_USBVIRTUAL     Port which is USB virtual serial
//
// SERIAL_PORT_LINUXBRIDGE    Port which connects to a Linux system via Bridge library
//
// SERIAL_PORT_HARDWARE       Hardware serial port, physical RX & TX pins.
//
// SERIAL_PORT_HARDWARE_OPEN  Hardware serial ports which are open for use.  Their RX & TX
//                            pins are NOT connected to anything by default.
#define SERIAL_PORT_MONITOR         Serial
#define SERIAL_PORT_HARDWARE        Serial
#define SERIAL_PORT_HARDWARE1       Serial1
#define SERIAL_PORT_HARDWARE2       Serial2
#define SERIAL_PORT_HARDWARE3       Serial3
#define SERIAL_PORT_HARDWARE_OPEN   Serial1
#define SERIAL_PORT_HARDWARE_OPEN1  Serial2
#define SERIAL_PORT_HARDWARE_OPEN2  Serial3

也就是说,MEGA自己定义了Serial,Serial1,Serial2,Serial3这些对象,如果直接把蓝牙的rxtx接在MEGA的第一组txrx上,然后直接调用Serial1对象,就可以实现通信,譬如这样:

#include  

// Pin10为RX,接HC05的TXD
// Pin11为TX,接HC05的RXD
//SoftwareSerial BT(14, 15); 这是没有用的
char val;

void setup() {
  Serial.begin(9600); 
  Serial.println("BT is ready!");
  Serial3.begin(9600);
}

void loop() {
  if (Serial.available()) {
    val = Serial.read();
    Serial3.print(val);
    delay(20);
  }

  if (Serial3.available()) {
    val = Serial3.read();
    Serial.print(val);
    delay(20);
  }
  delay(20);
}

综上所述,使用MEGA通过蓝牙通信的时候,就不要自己去定义串口对象了,直接使用MEGA提供的Serial1,Serial2,Serial3就可以

你可能感兴趣的:(Arduino)