/*
Arduino Serial Servo Control
Based on examples at:
// https://forum.arduino.cc/t/serial-input-basics-updated/382007
Feb 2026
*/
#include <Servo.h>
const byte numChars = 32;
const int LED_PINS[] = {10, 9, 8};
const int SERVO_PIN = 2;
bool newData = false;
char rxChars[numChars]; // an array to store the received data
Servo servo;
void setup() {
Serial.begin(9600);
for (int i = 0; i < 3; i++) {
pinMode(LED_PINS[i], OUTPUT);
}
servo.attach(SERVO_PIN);
Serial.println("<Arduino is ready>");
}
void loop() {
recvWithEndMarker();
showNewData();
}
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (rc != endMarker) {
rxChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
rxChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void showNewData() {
if (newData == true) {
for (int i = 0; i < 3; i++) {
digitalWrite(LED_PINS[i], LOW);
}
//if (rxChars[0] == 'a') servo.write(0);
if (strcmp(rxChars, "left") == 0) {
servo.write(0);
digitalWrite(LED_PINS[0], HIGH);
}
//if (rxChars[0] == 's') servo.write(90);
if (strcmp(rxChars, "center") == 0) {
servo.write(90);
digitalWrite(LED_PINS[1], HIGH);
}
//if (rxChars[0] == 'd') servo.write(180);
if (strcmp(rxChars, "right") == 0) {
servo.write(180);
digitalWrite(LED_PINS[2], HIGH);
}
Serial.print("This just in ... ");
Serial.println(rxChars);
newData = false;
}
}