> For the complete documentation index, see [llms.txt](https://freegrow-1.gitbook.io/product-docs-en/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://freegrow-1.gitbook.io/product-docs-en/en-creator-kit-q1/uwb-creator-kit-q1-complete-setup-and-usage-guide/practice-examples/arduino-mega-2560-integration.md).

# Arduino Mega 2560 Integration

### In this guide

we explain how to connect a GrowSpace developer tag to an Arduino Mega 2560 via serial communication and receive real-time location data using the `lec` and `lep` commands.\
We also provide example code to show how to build a stable high-speed communication setup using the Mega 2560’s hardware serial ports.

***

### Required Materials

* Arduino Mega 2560 Board

<figure><img src="/files/9h0XSiLyYzt9o13dAERT" alt="" width="375"><figcaption></figcaption></figure>

* GrowSpace Developer Tag

<figure><img src="/files/TgAlQ5v48I3G5mnnvitg" alt=""><figcaption></figcaption></figure>

* Arduino IDE Program (Official: <https://www.arduino.cc/en/software>)
* Jumper wires

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td>Jumper cables</td><td></td><td><a href="/files/tL5MKzkJbkuIFBKe9v9I">/files/tL5MKzkJbkuIFBKe9v9I</a></td></tr><tr><td>Included serial (connection cable)</td><td></td><td><a href="/files/zeXALl7Y7AUokKCwM6YY">/files/zeXALl7Y7AUokKCwM6YY</a></td></tr></tbody></table>

> ⚠️ The **UNO board has only one hardware serial port**, which may cause errors during high-speed communication. The **Mega 2560 provides Serial1 to Serial3**, enabling more stable and reliable communication.

***

### Arduino IDE Setup and Board Connection

* Open the Arduino IDE after installation.

* In the top menu, apply the following settings:

  * **Tools > Board > Arduino Mega or Mega 2560**

  <figure><img src="/files/sxGPNUSpmSZfVS2uOJ4l" alt=""><figcaption></figcaption></figure>

  * **Tools > Port > Select the connected COM port** (e.g. COM3)

  <figure><img src="/files/PhjsgpsKQE7BnvAXGDZK" alt=""><figcaption></figcaption></figure>

* Connect the **Arduino Mega 2560** to your PC via USB.

***

### Hardware Pin Connection

Connect the pins using the **right-side connector** (5V only) on the GrowSpace developer tag as shown below:

| Developer Tag Pin | Arduino Mega pin |
| ----------------- | ---------------- |
| TX                | RX1 (pin 19)     |
| RX                | TX1 (pin 18)     |
| 5V                | 5V               |
| GND               | GND              |

> 🔄 **TX and RX must be cross-connected** for communication to work properly.

Below is an example of the pin layout on the Arduino Mega board.

Connect the GrowSpace developer tag using **TX1 (pin 18)** and **RX1 (pin 19)** of **Serial1**.

{% columns %}
{% column width="25%" %}

<figure><img src="/files/DDpXB60HeBajhTPjsfJ1" alt="" width="375"><figcaption><p>Connection example: Developer tag connected to Arduino Mega 2560</p></figcaption></figure>

{% endcolumn %}

{% column %}

<figure><img src="/files/ywLRjrYmYoQtRrotEUQJ" alt=""><figcaption></figcaption></figure>

{% endcolumn %}
{% endcolumns %}

***

### Serial Relay Example (Basic Communication Test)

```cpp
String inputFromSerial0 = "";
String inputFromSerial1 = "";

void setup() {
  Serial.begin(115200);    // USB Serial (Serial0)
  Serial1.begin(115200);   // Hardware Serial1 ( pin 18 TX1, pin 19 RX1)
}

void loop() {
  // serialEvent() and serialEvent1() are called automatically
}

// Input from Serial0 → sent to Serial1 (with carriage return \r added)
void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar != '\n') {
      inputFromSerial0 += inChar;
    }

    if (inChar == '\n') {
      Serial1.print(inputFromSerial0);
      Serial1.print('\r');
      inputFromSerial0 = "";
    }
  }
}

// Input from Serial1 → sent to Serial0
void serialEvent1() {
  while (Serial1.available()) {
    char inChar = (char)Serial1.read();
    inputFromSerial1 += inChar;

    if (inChar == '\n') {
      Serial.print("From Serial1: ");
      Serial.print(inputFromSerial1);
      inputFromSerial1 = "";
    }
  }
}
```

#### Explanation

* In `setup()`, both the USB serial (`Serial`) and the hardware serial (`Serial1`) are initialized.
* `serialEvent()` sends the string entered from the PC (Serial0) to the tag.
* `serialEvent1()` reads the response from the tag and prints it to the PC.
* When a command is sent, the input is split by newline (`\n`), and a carriage return (`\r`) is automatically added.

#### **Serial Monitor Setup Tips**

* Baudrate: **115200bps**
* **Set line ending to**: *New Line*
* If the tag returns system information after sending the `si` command, the communication is working.

If you type `si` in the Serial Monitor and receive a valid response, the connection is successful.

<figure><img src="/files/B4dt8QqFSx9PAelHV5si" alt=""><figcaption></figcaption></figure>

***

### Location Parsing Example Using Commands

```cpp
String bufferSerial0 = "";
String bufferSerial1 = "";

void setup() {
  Serial.begin(115200);    // USB Serial
  Serial1.begin(115200);   // Serial1 for developer tag connection
}

void loop() {
  // Leave empty, serialEvent / serialEvent1 run automatically
}

// Receive command input from Serial0
void serialEvent() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    if (inChar != '\n') {
      bufferSerial0 += inChar;
    }

    if (inChar == '\n') {
      bufferSerial0.trim();  // Remove newline

      if (bufferSerial0.equalsIgnoreCase("lec") || bufferSerial0.equalsIgnoreCase("lep")) {
        Serial.print("Command sent: ");
        Serial.println(bufferSerial0);
        Serial1.print(bufferSerial0); // Append CR only
        Serial1.print('\r');
      } else {
        Serial.println("⚠ Unsupported command.");
      }

      bufferSerial0 = "";
    }
  }
}

// Receive response from Serial1 → parse lec/lep
void serialEvent1() {
  while (Serial1.available()) {
    char inChar = (char)Serial1.read();
    bufferSerial1 += inChar;

    if (inChar == '\n') {
      bufferSerial1.trim();

      if (bufferSerial1.startsWith("POS,")) {
        parseLEP(bufferSerial1);
      } else if (bufferSerial1.startsWith("DIST,")) {
        parseLEC(bufferSerial1);
      } else {
        Serial.println("[Response] " + bufferSerial1);
      }

      bufferSerial1 = "";
    }
  }
}

// --- Parse position only (lep) ---
void parseLEP(String line) {
  Serial.println("[LEP Position Result]");
  int idx = 0;
  String parts[5];
  while (line.length() > 0 && idx < 5) {
    int comma = line.indexOf(',');
    if (comma == -1) {
      parts[idx++] = line;
      break;
    } else {
      parts[idx++] = line.substring(0, comma);
      line = line.substring(comma + 1);
    }
  }

  Serial.print("X: "); Serial.println(parts[1]);
  Serial.print("Y: "); Serial.println(parts[2]);
  Serial.print("Z: "); Serial.println(parts[3]);
  Serial.print("Quality (QF): "); Serial.println(parts[4]);
  Serial.println();
}

// --- Parse full lec data ---
void parseLEC(String line) {
  Serial.println("[LEC Distance + Position Result]");
  int posIndex = line.indexOf("POS,");
  if (posIndex == -1) {
    Serial.println("→ Missing position data");
    return;
  }

  String distPart = line.substring(0, posIndex - 1);
  String posPart = line.substring(posIndex);

  Serial.println("▶ Anchor Distance Info:");
  int anchorIdx = 0;
  int anStart = 0;
  while ((anStart = distPart.indexOf("AN", anStart)) != -1) {
    int idStart = anStart + 2;
    int idEnd = distPart.indexOf(",", idStart);
    String id = distPart.substring(idStart, idEnd);

    int valStart = idEnd + 1;
    float x = distPart.substring(valStart, distPart.indexOf(",", valStart)).toFloat();
    valStart = distPart.indexOf(",", valStart) + 1;
    float y = distPart.substring(valStart, distPart.indexOf(",", valStart)).toFloat();
    valStart = distPart.indexOf(",", valStart) + 1;
    float z = distPart.substring(valStart, distPart.indexOf(",", valStart)).toFloat();
    valStart = distPart.indexOf(",", valStart) + 1;
    float d = distPart.substring(valStart, distPart.indexOf(",", valStart)).toFloat();

    Serial.print("AN"); Serial.print(anchorIdx++); Serial.print(" (ID "); Serial.print(id); Serial.print("): ");
    Serial.print("x="); Serial.print(x); Serial.print(", y="); Serial.print(y); Serial.print(", z="); Serial.print(z);
    Serial.print(" → Distance: "); Serial.print(d); Serial.println("m");

    anStart = valStart;
  }

  Serial.println("▶ Tag Position Info:");
  parseLEP(posPart);
}

```

* LEP Command Execution

<figure><img src="/files/WHpzkqqoJ7LI8Zw2PGDX" alt=""><figcaption></figcaption></figure>

* LEC Command Execution

<figure><img src="/files/EhNs73cC1qfyX73KhiHP" alt=""><figcaption></figcaption></figure>

***

### Conclusion

This guide walks you through setting up serial communication between the Arduino Mega 2560 and the GrowSpace developer tag, and receiving real-time location data using the `lec` and `lep` commands.

* `lep`: View X, Y, Z coordinates and quality factor (QF)
* `lec`: Check anchor information, distance, and full location data
