Serial communication between python and arduino

Thread Starter

mnobeidat

Joined Dec 20, 2016
20
I am working on object tracking robot. I am using python and OpenCV to detect the object and send the proper data to the arduino that controls two servo motors.
The data which should be sent to the arduino are servo motors angles ranging between 0-180. I am using sample codes to understand how python and arduino communicate using serial bus.When I send a single digit, the arduino receives it and work as intended, but when I send more than one digit nothing happens.
This is the arduino code:
C:
 #include <Servo.h>
    int data;
    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards
    int pos = 0;    // variable to store the servo position

    void setup() {
      Serial.begin(9600); //initialize serial COM at 9600 baudrate
      pinMode(LED_BUILTIN, OUTPUT); //make the LED pin (13) as output
      digitalWrite (LED_BUILTIN, LOW);
      myservo.attach(9);
      Serial.println("Hi!, I am Arduino");
    }
 
    void loop() {
    while (Serial.available()){
     //to receive more than one character
     char buffer[] = {' ',' ',' ',' ',' ',' ',' '}; // Receive up to 7 bytes
     while (!Serial.available()); // Wait for characters
     Serial.readBytesUntil('n', buffer, 7);
     data = atoi(buffer);

    }
    myservo.write(data);
    }
And here is the python code:
Python:
    import serial
    import time  # Required to use delay functions

    # Create Serial port object called arduinoSerialData
    arduinoSerialData = serial.Serial('com14', 9600) 

    time.sleep(2)  # wait for 2 secounds for the communication to get established

    print arduinoSerialData.readline()  # read the serial data and print it as line
    print ("Enter 1 to turn ON LED and 0 to turn OFF LED")

    while 1:  # Do this forever

        var = raw_input()  # get input from user
        print "you entered", var  # print the intput for confirmation

        arduinoSerialData.write(var)
Mod edit: added code tags [code] [/code]=
 
Last edited:

xox

Joined Sep 8, 2017
838
First of all, you need to detect the number of bytes received and then use that to null-terminate the string, ie: buffer[received] = 0 (just make sure that the "received" variable is less than the buffer size; in this case that would have to be 6 since the buffer size is 7). If you don't then string-handling routines like atoi() will basically get confused. Next, verify that you can send data directly (without using any Python routines).
 
Top