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:
And here is the python code:
Mod edit: added code tags [code] [/code]=
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);
}
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)
Last edited: