Hi
First time here. I am trying to drive a dc motor using ESP32 (Devkit V1 - ESP WROOM 32) bluetooth. I have strange problem when I try sending the target value to esp32 it gets updated once but then it goes to 0 automatically. This does not happen while using serial communication
below is my code. Not sure what am I doing wrong
#include <BluetoothSerial.h>
BluetoothSerial SerialBT;
#define enca 12
#define encb 13
#define in1 25
#define in2 26
#define ena 14
int pos = 0;
long prevT = 0;
float ePrev = 0;
float eIntegral = 0;
volatile int target = 0; // Initialize target variable
void setup() {
Serial.begin(115200);
SerialBT.begin("ESP32_BT"); // Bluetooth device name
Serial.println("Process started");
pinMode(enca, INPUT);
pinMode(encb, INPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(ena, OUTPUT);
attachInterrupt(digitalPinToInterrupt(enca), readEncoder, RISING);
}
void readEncoder() {
int b = digitalRead(encb);
if (b > 0) {
pos++;
} else {
pos--;
}
}
void setMotor(int dir, int speedMotor) {
if (dir == 1) {
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
} else if (dir == -1) {
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
} else {
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
}
analogWrite(ena, speedMotor); // Set motor speed using PWM on ENA pin
}
void loop() {
// Check Bluetooth connection status
if (!SerialBT.connected()) {
Serial.println("Bluetooth disconnected!");
delay(1000);
return;
}
float kp = 1;
float kd = 0;
float ki = 0;
long currT = micros();
float deltaT = ((float)(currT - prevT)) / 1.0e6;
prevT = currT;
int e = target - pos;
float dedt = (e - ePrev) / deltaT;
eIntegral = eIntegral + e * deltaT;
float u = kp * e + kd * dedt + ki * eIntegral;
float pwr = fabs(u);
if (pwr > 255) {
pwr = 255;
}
int dir = 1;
if (u < 0) {
dir = -1;
}
setMotor(dir, pwr);
ePrev = e;
// Read input from serial monitor
if (Serial.available() > 0) {
target = Serial.parseInt(); // Parse the input as an integer
Serial.print("New target: ");
Serial.println(target);
}
// Read input from Bluetooth
if (SerialBT.available()) {
target = SerialBT.parseInt(); // Parse the input as an integer
Serial.print("Received target: ");
Serial.println(target);
}
// Print debug information
Serial.print("Target: ");
Serial.print(target);
Serial.print(" Position: ");
Serial.print(pos);
Serial.print(" Power: ");
Serial.print(pwr);
Serial.print(" Error: ");
Serial.println(e);
delay(100); // Delay to allow time for serial communication
}