DIY Drone - ESP32 [Version 2] #3 (How to control Brushless Motor) Source code
Receiver side
#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 #define Brushless_Motor_PIN 25 int i = 0; BluetoothSerial SerialBT; void setup() { //Bluetooth Serial.begin(115200); SerialBT.begin("ESP32test"); //Bluetooth device name Serial.println("The device started, now you can pair it with bluetooth!"); //Brushlessmotor pinMode(Brushless_Motor_PIN, OUTPUT);//Brushless_Motor_PIN as OUTPUT ledcSetup(0, 1000, 8);//PWM channel is 0, Frequency 1000Hz, 8 bit(Duty with 256 levels of resolution, the value is 0-255) ledcAttachPin(Brushless_Motor_PIN,0);//Assign channel 0 to Brushless_Motor_PIN } uint8_t calculate_checksum(uint8_t *data) { uint8_t checksum = 0; checksum |= 0b11000000 & data[1]; checksum |= 0b00110000 & data[2]; checksum |= 0b00001100 & data[3]; checksum |= 0b00000011 & data[4]; return checksum; } void loop() { uint8_t recv_data[6]; if (SerialBT.available()) { SerialBT.readBytes(recv_data, 6); if (recv_data[0] != 'T') { Serial.print("Receive error!"); return; } if (recv_data[5] != calculate_checksum(recv_data)) { Serial.print("Decode error!"); return; } Serial.printf("left_x: %d, left_y: %d, right_x: %d, right_y: %d\n", recv_data[1], recv_data[2], recv_data[3], recv_data[4]); if((recv_data[2] < 50)&&(i < 125)){//Duty MAX About 0.5(≒124/255) ledcWrite(0, i++); } if((recv_data[2] > 200)&&(i >= 1)){ ledcWrite(0, i--); } Serial.printf("i:%d\n", i); } delay(20); }
Controller side is ↓↓↓↓↓↓↓↓
desktopmake.hateblo.jp