关于Arduino Leonardo与ESP32-WROOM-32的串口通信
首先是硬件连接
ESP32-WROOM-32的串口有三个(serial,serial1,serial2),这里连的是serial
Arduino Leonardo的串口有两个,这里连的是serial1
ESP32-WROOM-32的LED的pin脚是 2
Arduino Leonardo的LED的pin脚是 13
Arduino 程序:
void setup() {
Serial1.begin(115200);
pinMode(13, OUTPUT);
}
void loop() {
if (Serial1.available())
{
if (Serial1.read()=='a')
{
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
}
}
}
ESP32程序:
void setup() {
Serial.begin(115200);
pinMode(2, OUTPUT);
}
void loop() {
digitalWrite(2, HIGH);
Serial.write('a');
delay(1000);
digitalWrite(2, LOW);
}
下一步制作蓝牙键盘
具体原理如图:
Arduino 测试程序:
#include "Keyboard.h"
char text;
void setup() {
Keyboard.begin();
Serial.begin(115200);
Serial1.begin(115200);
pinMode(13, OUTPUT);
}
void loop() {
if (Serial1.available())
{
text = Serial1.read();
Serial.print(text);
if (text == 'a')
{
digitalWrite(13, HIGH);
Serial.print(text);
Keyboard.print(text);
delay(1000);
digitalWrite(13, LOW);
}
}
}
以下是完整版
ESP32蓝牙接收程序--2023/3/26
#include "BluetoothSerial.h"
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
BluetoothSerial SerialBT;
void setup() {
pinMode(2, OUTPUT);
Serial.begin(115200);
Serial2.begin(115200);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("The device started, now you can pair it with bluetooth!");
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
digitalWrite(2, HIGH);
delay(100);
Serial.write(SerialBT.read());
Serial2.write(SerialBT.read());
digitalWrite(2, LOW);
}
delay(20);
}
Arduino串口接收测试程序--2023/3/26
#include "Keyboard.h"
char key;
void setup() {
Keyboard.begin();
Serial1.begin(115200);
pinMode(13, OUTPUT);
}
void loop() {
if (Serial1.available())
{
key = Serial1.read();
digitalWrite(13, HIGH);
Keyboard.print(key);
digitalWrite(13, LOW);
}
}
PC端Python发送程序--2023/3/26
import serial
import time
text = "nmcli con show 'ETH1'"
ser = serial.Serial('com11', 115200, parity='E', stopbits=1, bytesize=8, timeout=0.5)
for key in text:
ser.write(key.encode("gbk"))
time.sleep(0.2)
ser.close()