使用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 <SoftwareSerial.h>
// 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就可以