typestar

Serial commands in Arduino

One-letter commands from the monitor drive the relays.

// One-letter commands from the monitor drive the relays.
const int PUMP_PIN = 7;
const int LIGHT_PIN = 9;
void setup() {
  pinMode(PUMP_PIN, OUTPUT);
  pinMode(LIGHT_PIN, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() == 0) return;
  char command = Serial.read();
  switch (command) {
    case 'p': digitalWrite(PUMP_PIN, HIGH); break;
    case 'P': digitalWrite(PUMP_PIN, LOW); break;
    case 'l': digitalWrite(LIGHT_PIN, HIGH); break;
    case 'L': digitalWrite(LIGHT_PIN, LOW); break;
    default: Serial.println("p/P pump, l/L light");
  }
}

How it works

  1. The early return skips the pass when no byte waits.
  2. switch routes each command char to its pin write.
  3. The default arm doubles as the help text.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
539
Tokens
141
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 130 seconds.

Type this snippet

Step 2 of 3 in Serial, step 14 of 27 in Language basics.

← Previous Next →