以下是一个使用 Arduino 和蓝牙模块控制电机转动的示例代码:

#include <AFMotor.h>  // 引入电机驱动库

#define bluetoothTx 10  // 蓝牙模块的TX引脚连接到Arduino的数字引脚10
#define bluetoothRx 11  // 蓝牙模块的RX引脚连接到Arduino的数字引脚11

AF_DCMotor motor(1);  // 创建一个电机实例,连接到电机驱动器的M1引脚

void setup() {
  Serial.begin(9600);  // 初始化串口通信
  motor.setSpeed(255); // 设置电机速度(0-255)
  
  pinMode(bluetoothTx, OUTPUT);  // 设置蓝牙模块的TX引脚为输出模式
  pinMode(bluetoothRx, INPUT);   // 设置蓝牙模块的RX引脚为输入模式
}

void loop() {
  if (Serial.available()) {  // 如果串口接收到数据
    char command = Serial.read();  // 读取收到的字符
    
    // 根据收到的字符执行相应的动作
    if (command == 'F') {
      motor.run(FORWARD);  // 电机向前转动
    } else if (command == 'B') {
      motor.run(BACKWARD);  // 电机向后转动
    } else if (command == 'S') {
      motor.run(RELEASE);  // 停止电机转动
    }
  }
}

在使用该代码之前,请确保已经正确连接了电机驱动器和蓝牙模块,并将蓝牙模块的TX引脚连接到Arduino的数字引脚10,RX引脚连接到数字引脚11。

通过蓝牙串口控制器应用程序(如 Arduino Bluetooth Controller)或其他蓝牙串口通信工具,可以向 Arduino 发送字符命令来控制电机的转动。发送'F'将使电机向前转动,发送'B'将使电机向后转动,发送'S'将停止电机转动。

Arduino 蓝牙控制电机转动代码示例

原文地址: https://www.cveoy.top/t/topic/pj5o 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录