pythonautomationarduino

control arduino with python


I am working on a simple project that involves controlling an Arduino with Python, and at the same time, the Arduino controls two servomotors. The problem is that no matter what character or number I send from Python to the Arduino, the servo moves in some way. This should not happen if the data is incorrect. It even happens that both servos move at the same time.

###python code###
import serial
import time

def iniciar():
    try:
        arduino = serial.Serial("COM7", 9600)
        time.sleep(2)

        while True:
            a = int(input(": "))
            arduino.write(b'a')
            if a == "x":
                    break

    finally:
        arduino.close()

#while True:
iniciar()

###arduino code

#include <Servo.h>
Servo ON;
Servo OFF;
char pr;

void setup() {
Serial.begin(9600);

OFF.attach(8);
ON.attach(9);

}

void loop() {
  if(Serial.available()>0){
    pr = Serial.read();
    if(pr == 'b'){ 
      ON.write(0);  // tell servo to go to a particular angle
      delay(1000);
      ON.write(90);              
      delay(500);
    }
    if(pr == 'a'){
      OFF.write(0);  // tell servo to go to a particular angle
      delay(1000);
      OFF.write(90);              
      delay(500);
    }
  } 
}

I tried changing the type of data sent from Python, switching from 'int' to 'char'. I suppose the error might be in the use of the 'try' block, but honestly, I don't have much idea; I'm somewhat new to working with Python.


Solution

  • You always send the same bytes b'a' to the Arduino regardless of user input.

    arduino.write(b'a')
    

    Essentially, you are sending the char 'a' as a byte and not the variable a.

    You can try something like this:

    while True:
                a = input(": ")
                if a in ['a', 'b']:  # only send valid inputs
                    arduino.write(a.encode())