BLE模块与手机APP mRobots通信示例
1196357542(讨论 | 贡献)2017年9月13日 (三) 11:57的版本
BLE模块与手机APP mRobots通信示例
所需硬件
电路搭建 将Battery、Core、BLE、Motor堆叠在一起,通过MicroUSB数据线接入电脑。初次使用请参考:Getting Started。
代码 #include <Microduino_Protocol.h>
#include <Microduino_Motor.h>
#define _DEBUG //DEBUG调试
#define BLE_SPEED 9600 //蓝牙接口速度
#define CHANNEL_NUM 8
#define SAFE_TIME_OUT 250 //失控保护时间
#define MAX_THROTTLE 255 //最大油门 < 255
#define MAX_STEERING 512 //最大转向 < 512
#define CHANNEL_THROTTLE 1 //油门通道
#define CHANNEL_STEERING 0 //转向通道
Motor MotorLeft(MOTOR0_PINA, MOTOR0_PINB);
Motor MotorRight(MOTOR1_PINA, MOTOR1_PINB);
#define ProSerial Serial
ProtocolSer bleProtocol(&ProSerial, 16); //采用ProSerial,数据长度为16个字节
///////////////////////////////////////////////////////////
uint16_t channalData[CHANNEL_NUM]; //8通道数据
int16_t throttle = 0; //油门
int16_t steering = 0; //转向
unsigned long safe_ms = millis();
uint8_t recCmd;
void setup() {
Serial.begin(9600);
Serial.println("Hello Microduino!");
bleProtocol.begin(BLE_SPEED);
MotorLeft.begin(); //电机MotorLeft初始化
MotorRight.begin(); //电机MotorLeft初始化
}
void loop() {
if (bleProtocol.available())
{
bleProtocol.readWords(&recCmd, channalData, 8);
throttle = map(channalData[CHANNEL_THROTTLE], 1000, 2000, -MAX_THROTTLE, MAX_THROTTLE);
steering = map(channalData[CHANNEL_STEERING], 1000, 2000, -MAX_STEERING, MAX_STEERING);
MotorLeft.setSpeed((throttle + steering / 2));
MotorRight.setSpeed(-(throttle - steering / 2));
#ifdef _DEBUG
Serial.print("DATA OK :[");
for (int a = 0; a < CHANNEL_NUM; a++) {
Serial.print(channalData[a]);
Serial.print(" ");
}
Serial.print("],throttle:");
Serial.print(throttle);
Serial.print(",steering:");
Serial.println(steering);
#endif
safe_ms = millis();
}
if (safe_ms > millis()) safe_ms = millis();
if (millis() - safe_ms > SAFE_TIME_OUT) {
MotorLeft.setSpeed(FREE); //设置电机MotorLeft为释放状态,即速度为0
MotorRight.setSpeed(FREE);
}
}
相关案例 |