Hi everybody,
I'm trying to send some data from a program in python to my Arduino UNO. It's a number between 0 and 500, and the idea is to receive the data in order to move a servo.
The problem is that the data is "decomposed", for example if the number is 278, sometimes it will indeed receive the right number, but sometimes it only receives 2, or 78.
I don't know where the problem may be... I've already tried different methods but I can't resolve the problem. I anyone can help me, I would be great!
Thank you!
That's how I send data with Python:
x, y, w, h = face.faceRect
ser.write(str(x))
ser.write("\n")
Here's the Arduino's code:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
#include <Servo.h>
#define servomaxx 160 // max degree servo horizontal (x) can turn
#define screenmaxx 500 // max screen horizontal (x)resolution
#define distancex 10 // x servo rotation steps
int x;
int posx = 0;
int incx = 10; // significant increments of horizontal (x) camera movement
Servo myServo;
void setup(){
lcd.begin(16,2);
myServo.attach(9);
Serial.begin(9600);
myServo.write(90); //Servo 90°
}
void loop(){
if (Serial.available() > 0) {
x = Serial.parseInt();
lcd.print(x);
moveTurret();
}
while (Serial.available() > 0) {
Serial.read();
}
}
void moveTurret() {
// read last servos positions
posx = myServo.read();
Serial.println(posx);
//Find out if the X component of the face is to the right of the middle of the screen.
if(x < (screenmaxx/2 - incx)){
if( posx >= incx )
posx -= distancex; //Update the pan position variable to move the servo to the left.
}
//Find out if the X component of the face is to the left of the middle of the screen.
else if(x > screenmaxx/2 + incx){
if(posx <= servomaxx-incx)
posx +=distancex; //Update the pan position variable to move the servo to the right.
}
myServo.write(posx);
/*
int servoX = map(x, 0, 500, 20, 160); // x varie de 0 à 500 (écran, OpenCV) et nous le transformons en angle de 20° à 160° (capacité servo arduino)
servoX = min(servoX, 170); //Maybe useless
servoX = max(servoX, 20); //Maybe useless
*/
delay(2000);
lcd.clear();
}