Suffix

Send data from a computer to an Arduino

Most tutorials will explain how to send data from an Arduino to a computer, what about the opposite?

I’m a programmer, not an electrical engineer. I bought an Arduino to learn how to connect the physical world with the computing one where I know my way around. I hope to post a few howtos when I learn something new.

Serial Communication

Most tutorials will explain how to send data from an Arduino (or a connected sensor) to a computer. I want the opposite: send data from my computer to an Arduino Uno board. Talking with an Arduino over a USB cable is called ‘serial communication’ which means you can send one instruction at a time. This may sound slow — and it is — but it's the easiest way to learn how it works.

Sketch

Connect the Arduino with your computer using a USB cable and open the editor (read the Bare Minimum tutorial if you don't know how). Now load the sketch below and open the Serial Monitor (last button in the Arduino editor toolbar).

int ledPin = 13;

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

void loop() {
  if (Serial.available() > 0) {
    char value = Serial.read();
    if (value == '1') {
      digitalWrite(ledPin, HIGH);
    } else {
      digitalWrite(ledPin, LOW);
    }
    Serial.println(value);
  }
  delay(1000);
}

Using the input field in the Serial Monitor you can send a 1 to the Arduino board to turn the built-in LED on, anything else will turn it off. The Serial Monitor displays the value the Arduino sent back (the one it got as the input).

How?

  1. The first line specifies the LED we want to use, pin 13 is the built-in LED on an Arduino Uno, change this if you use another board.
  2. The Serial.begin line tells the Arduino what baud rate to use.
  3. The loop function will look if there is some input waiting and if so read it in the value variable (only one char at the time). If the value is 1 it will turn the LED on, if not it will turn it off.
  4. The Serial.print sends the input back to the computer (optional but nice to see what the Arduino received) and wait for 1 second before checking for new input.