ABC of Electronics cosycom.com
ARDUINO 17 · Communication

Two-Way Communication over Serial

Send commands from your computer to your Uno over the same cable, and have the sketch act on them.

You'll need: an LED and resistor on pin 8, and your Uno — this lesson builds on Lesson ard-09's Serial Monitor, now sending data in the opposite direction.

Lesson ard-09 covered the board sending text to your computer; the Serial Monitor's input box at the top can also send text the other way, into the board's incoming serial buffer, readable in your sketch with a few new functions.

void setup() {
  pinMode(8, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    char command = Serial.read();

    if (command == '1') {
      digitalWrite(8, HIGH);
    } else if (command == '0') {
      digitalWrite(8, LOW);
    }
  }
}

Serial.available() checks whether any incoming data is waiting to be read, returning the number of bytes ready. Serial.read() reads one of those bytes as a single character. Type 1 into the Serial Monitor's input box and press Send (make sure line ending is set to something other than "No line ending," or send just the single character) — the LED should turn on; typing 0 turns it off.

This same pattern — read a character, decide what it means, act on it — scales to a simple text-based remote control for any of the outputs you've already built: relays, servos, motors, all driven by typed commands instead of a hardwired button.

Computer UNO abcofelectronics
Two-way serial The same USB cable carries data both directions — text out to the Serial Monitor, and typed commands back in to the sketch.
TRY THIS
Serial.available() tells you data is waiting before you try to read it — checking it first avoids acting on stale or empty input.