#include <AFMotor.h>

AF_DCMotor motor(1); // 创建一个DC电机对象,连接到电机驱动器的M1端口 char command; // 用于存储蓝牙模块发送的指令

void setup() { Serial.begin(9600); // 初始化串口通信 motor.setSpeed(255); // 设置电机转速, 0-255 }

void loop(){ if(Serial.available() > 0) { // 如果串口缓冲区中有数据 command = Serial.read(); // 读取指令

// 根据指令控制电机转动
if(command == 'F') { // 前进
  motor.run(FORWARD);
} else if(command == 'B') { // 后退
  motor.run(BACKWARD);
} else if(command == 'S') { // 停止
  motor.run(RELEASE);
}

} }

这是一个简单的例子,你可以根据自己的需求进行修改和扩展。注意,这个代码假设你已经连接了蓝牙模块,并且正确配置了串口通信。

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

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

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