Python script cant control the Arduino motors

I have this arduino code given below

#define M1_PWM 9   // Motor 1 Speed (PWM)
#define M1_DIR 5   // Motor 1 Direction
#define M2_PWM 6   // Motor 2 Speed (PWM)
#define M2_DIR 7   // Motor 2 Direction

void setup() {
  pinMode(M1_PWM, OUTPUT);
  pinMode(M1_DIR, OUTPUT);
  pinMode(M2_PWM, OUTPUT);
  pinMode(M2_DIR, OUTPUT);
  
  Serial.begin(115200);
  Serial.println("Dual Motor Control Ready ( 115200 baud)");
  
  // Initialize with motors stopped
  stop();
}

void loop() {
  if (Serial.available()) {
    char cmd = Serial.read();
    executeCommand(cmd);
  }
}

void executeCommand(char cmd) {
  switch(cmd) {
    case 'F': forward(); break;
    case 'B': reverse(); break;
    case 'L': left(); break;
    case 'R': right(); break;
    case 'S': stop(); break;
    case 'O': turnleft(); break;
    case 'P': turnright(); break;
  }
}

// Motor control functions with PWM speed control
void forward() {

  digitalWrite(M1_DIR, HIGH);
  digitalWrite(M2_DIR, HIGH);
  analogWrite(M1_PWM, 45);  // Medium speed
  analogWrite(M2_PWM, 45);
  Serial.println("FORWARD");
}

void reverse() {
  digitalWrite(M1_DIR, LOW);
  digitalWrite(M2_DIR, LOW);
  analogWrite(M1_PWM, 45);
  analogWrite(M2_PWM, 45);
  Serial.println("REVERSE");
}

void left() {
  // Right motor forward, left motor stopped
  digitalWrite(M1_DIR, LOW);
  digitalWrite(M2_DIR, HIGH);
  analogWrite(M1_PWM, 27);    // Left motor off
  analogWrite(M2_PWM, 25);  // Right motor on
  Serial.println("LEFT");
}

void right() {
  // Left motor forward, right motor stopped
  digitalWrite(M1_DIR, HIGH);
  digitalWrite(M2_DIR, LOW);
  analogWrite(M1_PWM, 27);  // Left motor on
  analogWrite(M2_PWM, 25);    // Right motor off
  Serial.println("RIGHT");
}

void turnleft() {
  // Right motor forward, left motor stopped
  digitalWrite(M1_DIR, LOW);
  digitalWrite(M2_DIR, HIGH);    // Left motor off
  analogWrite(M1_PWM, 0);
  analogWrite(M2_PWM, 30);  // Right motor on
  Serial.println("TURNLEFT");
}

void turnright() {
  // Left motor forward, right motor stopped
  digitalWrite(M1_DIR, HIGH);
  digitalWrite(M2_DIR, LOW);
  analogWrite(M1_PWM, 30);  // Left motor on 
  analogWrite(M2_PWM, 0);  // Right motor off
  Serial.println("TURNRIGHT");
}

void stop() {
  digitalWrite(M1_DIR, LOW);
  digitalWrite(M2_DIR, LOW);
  analogWrite(M1_PWM, 0);
  analogWrite(M2_PWM, 0);
  Serial.println("STOP");
}

the motors and everything worked perfectly well through the serial monitor and python programs i worked on except for this one

import serial
import time

class ObstacleAvoidanceBot:
    def __init__(self):
        self.current_yaw = 0.0
        self.current_distance = 1000.0
        self.safety_dist = 30  # cm
        self.last_command = b'S'

    def parse_sensor_data(self, line):
        try:
            if line.startswith(b'DIST:'):
                parts = line.decode().strip().split(',')
                distance = float(parts[0].split(':')[1])
                yaw = float(parts[1].split(':')[1])
                return distance, yaw
            else:
                print(f"Ignoring unexpected data: {line}")
                return None, None
        except Exception as e:
            print(f"Error parsing data: {e} | Raw data: {line}")
            return None, None

    def connect_serial(self):
        self.esp32 = serial.Serial('COM3', 115200)
        self.arduino = serial.Serial('COM9', 115200)
        time.sleep(2)

    def calculate_direction_command(self, distance, yaw):
        if distance < self.safety_dist:
            return b'S'  # Stop if too close

        yaw_error = (yaw + 360) % 360  # Normalize

        # Turn based on direction to avoid obstacle
        if 315 <= yaw_error or yaw_error <= 45:
            return b'F'
        elif 45 < yaw_error <= 135:
            return b'R'
        elif 225 <= yaw_error < 315:
            return b'L'
        else:
            return b'F'

    def run(self):
        self.connect_serial()
        try:
            while True:
                line = self.esp32.readline()
                print(f"Raw data from ESP32: {line}")

                distance, yaw = self.parse_sensor_data(line)

                if distance is None or yaw is None:
                    continue

                self.current_distance = distance
                self.current_yaw = yaw

                command = self.calculate_direction_command(distance, yaw)

                self.arduino.write(command)
                print(f"Sent to Arduino: {command}")

                # Debug response
                line2 = self.arduino.readline()
                print(f"Arduino response: {line2}")

                time.sleep(0.05)

        except KeyboardInterrupt:
            self.arduino.write(b'S\n')
            self.esp32.close()
            self.arduino.close()

if __name__ == "__main__":
    bot = ObstacleAvoidanceBot()
    bot.run()

i checked the arduino response and it does recieve the instructions as per the conditions in the programs but it doesnt move a bit

how did you check?


Your timing on managing the Serial port might be off - I've written a small tutorial on interfacing with Python. See Two ways communication between Python3 and Arduino

i used readline on the serial to tell me what the arduino says during the python executuion. for example when the script write 'F' to the serial, the arduino would know it has to go forward and would also give a reply through the serial monitor that it does move forward.

@n0za,

Your other topic on the same subject deleted.

Please do not duplicate your questions as doing so wastes the time and effort of the volunteers trying to help you as they are then answering the same thing in different places.

Please create one topic only for your question and choose the forum category carefully. If you have multiple questions about the same project then please ask your questions in the one topic as the answers to one question provide useful context for the others, and also you won’t have to keep explaining your project repeatedly.

Repeated duplicate posting could result in a temporary or permanent ban from the forum.

Could you take a few moments to Learn How To Use The Forum

It will help you get the best out of the forum in the future.

Thank you.

The serial link goes back to Python so you can’t have the serial monitor open…

sorry im new to this, but the arduino does in fact reply back that it moves forward

Replies to python and you print from python ?