// Define both left & right motors' speed & rotating direction pins
#define motorleftspeed 14
#define motorleftACW 13
#define motorleftCW 12
#define motorrightspeed 21
#define motorrightCW 22
#define motorrightACW 23
// Define push button pin for changin moving direction
#define button 4 //'0' for forward, '1' for backward
//Define potentiometer pins for speed variation control
const uint8_t slidepin1 = 35; //control left wheel speed
const uint8_t slidepin2 = 34; //control right wheel speed
// Define PWM frequency, resolution, led left & right channel
const int freq = 1000, resolution = 12, ledleft=0, ledright=1;
// Initialise the control the motor speed using PWM
int leftinput = 0, rightinput = 0, dutyCycleleft = 0, dutyCycleright = 0;
// Define boolean variable for motor direction
bool direction = true; //true: forward, false: backward
// Interrupt Service Routine for push button to change direction
void IRAM_ATTR push_button_ISR(){
direction = !direction;
}
void setup() {
Serial.begin(115200);
pinMode(slidepin1, INPUT);
pinMode(slidepin2, INPUT);
pinMode(motorleftCW,OUTPUT);
pinMode(motorrightACW,OUTPUT);
pinMode(motorleftACW,OUTPUT);
pinMode(motorrightCW,OUTPUT);
digitalPinToInterrupt(button); // configure digital pin to interrupt button
attachInterrupt(button, push_button_ISR, RISING);
ledcSetup(ledleft, freq, resolution); //To configure PWM signal
ledcAttachPin(motorleftspeed, ledleft); //Specify PWM channel 0 to motor pin D14
ledcSetup(ledright, freq, resolution); //To configure PWM signal
ledcAttachPin(motorrightspeed, ledright);
}
void loop() {
leftinput = analogRead(slidepin1);
rightinput = analogRead(slidepin2);
dutyCycleleft = map(leftinput,0,4095,0,1000); //Reduce range from 32bits to max 1000rpm
dutyCycleright = map(rightinput,0,4095,0,1000);
Serial.println("");
Serial.print("Left wheel rotates at ");
ledcWrite(ledleft,dutyCycleleft);
Serial.print(dutyCycleleft);
Serial.print(" RPM, ");
Serial.print("Right wheel rotates at ");
ledcWrite(ledright,dutyCycleright);
Serial.print(dutyCycleright);
Serial.println(" RPM");
if (direction == true){
digitalWrite(motorleftCW, HIGH);
digitalWrite(motorrightACW, HIGH);
digitalWrite(motorleftACW, LOW);
digitalWrite(motorrightCW, LOW);
if(leftinput==0 && rightinput==0){
Serial.println("Not moving, stops");
}else{
Serial.println("Moving forward");
if (leftinput>rightinput){
Serial.println("Moving forward, turning right");
}
else if (leftinput<rightinput){
Serial.println("Moving forward, turning left");
}
}
}else{
digitalWrite(motorleftCW, LOW);
digitalWrite(motorrightACW, LOW);
digitalWrite(motorleftACW, HIGH);
digitalWrite(motorrightCW, HIGH);
if(leftinput==0 && rightinput==0){
Serial.println("Not moving, stops");
}else{
Serial.println("Moving backward");
if (leftinput>rightinput){
Serial.println("Moving backward, turning right");
}
else if (leftinput<rightinput){
Serial.println("Moving backward, turning left");
}
}
}
}