#define SERVO_PIN 4 // Pin for the servo motor String data = ""; // String to store incoming serial data void setup() { Serial.begin(115200); // Initialize serial communication with a baud rate of 115200 pinMode(SERVO_PIN, OUTPUT); // Set the servo pin as an output } void loop() { if (Serial.available()) { char digit = Serial.read(); // Read the incoming byte from the serial port if (digit == '\n') { // Check if the incoming byte is a newline character Serial.println("Data: " + data); // Print the received data to serial monitor // Convert the received data (which represents the servo angle) to an integer // Serial.println( ( (data[0]-48) * 100 ) + ( (data[1]-48) * 10 ) ); int servoAngle = (data[0] - 48) * 100 + (data[1] - 48) * 10 + (data[2] - 48); Serial.println("Angle: " + servoAngle); // Print the servo angle to serial monitor servoPulse(SERVO_PIN, servoAngle); // Call the function to control the servo motor data = ""; // Clear the data string for the next input } else { data = data + digit; // Append the incoming byte to the data string } } } // Function to control the servo motor void servoPulse(int servo, int angle) { int pwm = (angle * 11) + 500; // Convert angle to microseconds digitalWrite(servo, HIGH); // Set servo pin high delayMicroseconds(pwm); // Wait for the calculated pulse width digitalWrite(servo, LOW); // Set servo pin low delay(15); // Wait for the refresh cycle of the servo }