Arduino side:
computer side(Python):
Code:
void setup() {
Serial.begin(9600); // Start serial communication at 9600 baud
for (int i = 0; i < numServos; i++) {
servos[i].attach(servoPins[i]); // Attach each servo to its pin
}
}
void loop() {
static int servoIndex = -1; // Static variable to keep track of the servo index
if (Serial.available() > 0) {
int value = Serial.parseInt(); // Read the next integer from the serial buffer
if (servoIndex == -1) {
// If servoIndex is -1, this value is the servo index
servoIndex = value;
} else {
// Otherwise, this value is the servo position
int servoPosition = value;
if (servoIndex >= 0 && servoIndex < numServos) {
servos[servoIndex].write(servoPosition); // Move the specified servo to the position
Serial.print("Servo ");
Serial.print(servoIndex);
Serial.print(" moved to ");
Serial.println(servoPosition);
}
servoIndex = -1; // Reset servoIndex for the next command
}
}
}
computer side(Python):
Code:
import serial
import time
# Replace 'COM3' with the appropriate port for your system
ser = serial.Serial('COM3', 9600)
time.sleep(2) # Wait for the serial connection to initialize
def send_servo_command(servo_index, servo_position):
command = f"{servo_index} {servo_position}\n"
ser.write(command.encode())
print(f"Sent command: {command.strip()}")
# Example usage
send_servo_command(0, 90) # Move servo 0 to 90 degrees
send_servo_command(1, 45) # Move servo 1 to 45 degrees
ser.close()