Skip to content

Lab — Serial with Arduino

Learn by programming: follow each step, write your own code, then apply it to the course assignment.

What you will build

Send a command from C++ and read the Arduino response over USB-serial.

  1. 1

    Arduino sketch

    Upload a sketch that in `loop()` reads `Serial.available()`, compares the command (e.g. `LED_ON\n`), and replies with fixed text. Use 9600 baud in `Serial.begin(9600)`.
    
    								void setup() { Serial.begin(9600); }
    void loop() {
      if (Serial.available()) {
        String cmd = Serial.readStringUntil('\n');
        if (cmd == "LED_ON") Serial.println("OK:LED_ON");
        else Serial.println("ERR:UNKNOWN");
      }
    }
    							
  2. 2

    Test in Serial Monitor

    Open the Arduino IDE Serial Monitor, send `LED_ON`, and verify `OK:LED_ON`. Close the monitor before opening the port from C++.

    Tip: Theory: /en/proyecto-final/comunicacion-serial-arduino/

  3. 3

    Open port in C++

    Identify the port (`COM3` on Windows, `/dev/ttyUSB0` or `/dev/ttyACM0` on Linux). Use the serial library your instructor specifies or Qt SerialPort if your GUI already uses it.
  4. 4

    Send and read response

    From C++ console, send `LED_ON\n`, wait for the response line, and print it with `std::cout`. Repeat with an invalid command and verify `ERR:UNKNOWN`.

Back to tutorial page