0

I am making a project where a camera tracks your face. I have a program on my computer that sends the face coordinates to the Arduino through the serial port. The Arduino program drives two servos. One for the X coordinate and one for the Y coordinate. The code works but it is very slow. It takes about a second to update the servo. How would I make this code faster?

Here is the code:

include <Servo.h>

Servo x_servo;
Servo y_servo;

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

    x_servo.attach(9);
    y_servo.attach(10);

    x_servo.write(90);
    y_servo.write(90);
}

void loop() {
    if (Serial.available()) {
        String data = Serial.readString();
         
        int delimeter = data.indexOf(',');

        int x = data.substring(0, delimeter).toInt();
        int y = data.substring(delimeter + 1).toInt();

        int x_pos = map(x, 0, 640, 0, 180);
        int y_pos = map(y, 0, 480, 0, 180);

        x_servo.write(x_pos);
        y_servo.write(y_pos);
    }
}
Maximus39
  • 21
  • 4
  • One option: send the data as 8-bit binary pre-mapped 0-180. Then read 2 bytes at a time and send right to servo. – 001 Jul 10 '20 at 18:39
  • How are you sending the data? It sounds like you are waiting on readString to time out. – Delta_G Jul 10 '20 at 20:47

1 Answers1

-1

A baud rate of 9600 was fast in the early 1990s.

You can trivially set this to 115200 (12x faster). Anecdotal evidence suggests this is the fastest speed the Arduino serial monitor will allow, but the actual hardware can easily go to 460800, possibly faster.

Sending data over a serial port is pretty slow no matter what - so send less of it.

Do the map() on the PC side, packing your co-ordinates into a binary-integer format, and send that. If you want to keep it as a "text" protocol, convert the value into 4 characters.

Kingsley
  • 14,398
  • 5
  • 31
  • 53