Mechatronics LAB
Published © MIT

Dual Servo Control – Arduino Workshop

This project, we will create Dual Servo Control using Arduino, this time will control two servos using commands from the serial monitor.

BeginnerFull instructions provided1 hour19,426
Dual Servo Control – Arduino Workshop

Things used in this project

Story

Read more

Schematics

Dual Servo Control – Arduino Workshop

Code

Code

Arduino
#include <Servo.h>

char buffer[11];
Servo servo1;
Servo servo2;

void setup() {
  servo1.attach(5);   // Attach servo 1 to digital pin 5
  servo2.attach(6);   // Attach servo 2 to digital pin 6
  Serial.begin(9600); // Initialize serial communication
  while (Serial.available())
    Serial.read();
  servo1.write(90);   // Set initial position for servo 1
  servo2.write(90);   // Set initial position for servo 2
  Serial.println("STARTING...");
}

void loop() {
  if (Serial.available() > 0) {
    int index = 0;
    delay(100);
    int numChar = Serial.available();
    if (numChar > 10) {
      numChar = 10;
    }
    while (numChar--) {
      buffer[index++] = Serial.read();
    }
    buffer[index] = '\0';
    splitString(buffer);
  }
}

void splitString(char* data) {
  Serial.print("Data entered: ");
  Serial.println(data);
  char* parameter;
  parameter = strtok(data, " ,");
  while (parameter != NULL) {
    setServo(parameter);
    parameter = strtok(NULL, " ,");
  }
  while (Serial.available())
    Serial.read();
}

void setServo(char* data) {
  if ((data[0] == 'L') || (data[0] == 'l')) {
    int firstVal = strtol(data + 1, NULL, 10);
    firstVal = constrain(firstVal, 0, 180);
    servo1.write(firstVal);
    Serial.print("Servo 1 set to: ");
    Serial.println(firstVal);
  }
  if ((data[0] == 'R') || (data[0] == 'r')) {
    int secondVal = strtol(data + 1, NULL, 10);
    secondVal = constrain(secondVal, 0, 180);
    servo2.write(secondVal);
    Serial.print("Servo 2 set to: ");
    Serial.println(secondVal);
  }
}

Credits

Mechatronics LAB

Mechatronics LAB

67 projects • 44 followers
I am Sarful , I am a Mechatronics Engineer & also a teacher I am Interested in the evolution of technology in the automation industry .

Comments