当然可以!下面是一个使用 BluetoothSerial
类的 Arduino 示例代码。这段代码展示了如何初始化蓝牙串口、读取按键和操控摇杆,并将状态信息发送回连接的设备。
#include <BluetoothSerial.h>
// 定义蓝牙串口对象
BluetoothSerial bluetoothSerial(Serial1); // 假设使用 Serial1 作为蓝牙通信接口
void setup() {
// 初始化蓝牙串口,设置波特率为9600
bluetoothSerial.begin(9600);
Serial.begin(9600); // 用于调试输出到串口监视器
Serial.println("Bluetooth Serial Initialized");
}
void loop() {
// 读取来自蓝牙的输入
bluetoothSerial.readSerial();
// 检查按钮状态(假设有两个按钮,ID为0和1)
if (bluetoothSerial.isButtonPressed(0)) {
Serial.println("Button 0 is pressed");
bluetoothSerial.sendAlert("Button 0 was pressed!");
}
if (bluetoothSerial.isButtonPressed(1)) {
Serial.println("Button 1 is pressed");
bluetoothSerial.sendAlert("Button 1 was pressed!");
}
// 检查摇杆状态(假设有一个摇杆,ID为0)
if (bluetoothSerial.isJoystickUpdated(0)) {
BluetoothSerialJoystick joystick = bluetoothSerial.getJoystick(0);
int xValue = joystick.getX(); // 获取X轴值
int yValue = joystick.getY(); // 获取Y轴值
Serial.print("Joystick Updated - X: ");
Serial.print(xValue);
Serial.print(", Y: ");
Serial.println(yValue);
String displayMessage = "JoyStick X: " + String(xValue) + ", Y: " + String(yValue);
bluetoothSerial.setDisplay(displayMessage, 0); // 显示在应用上
}
// 清除按钮缓冲区以准备下一次读取
bluetoothSerial.clearBuffer();
delay(100); // 简单的延时,用于避免过于频繁地循环读取
}
注意事项:
- 在实际使用中,请确保你连接了合适的硬件并且已配置好相关引脚。
- 确保你的蓝牙模块支持与
HardwareSerial
通信,如 HC-05 或 HC-06 等。 - 根据实际需求修改 ID 和其他参数。
内容由零声教学AI助手提供,问题来源于学员提问