# Controlling Relays and LEDs Through Retrieve Commands

In this project, you will use the **Antares Workshop Shield** on the **Lynx-32 Development Board** module. In this **Antares Shield Workshop**, there are temperature, humidity (DHT11), relay, LED, and push button sensors. You will publish data using MQTTX which contains commands to control the LEDs and relays. Then the **Lynx-32 Development Board** **subscribes data to the Antares IoT Platform** which contains two command options, namely if the Relay input is 1 then the relay will turn on; Relay input is 0 then the relay will turn off; LED is 1 then the LED will turn on; LED input is 0 then the LED will turn off.

## Prerequisites

The materials required follow the **General Prerequisites** on the previous page. If you have not prepared the requirements on that page, then you can visit the following page.

{% content-ref url="../../general-prerequisites-esp32-wi-fi" %}
[general-prerequisites-esp32-wi-fi](https://docs.antares.id/en/code-and-library-examples/esp32-wi-fi/general-prerequisites-esp32-wi-fi)
{% endcontent-ref %}

The additional materials specific to this project are as follows.

1. Shield Workshop Antares
2. Antares ESP HTTP Library. This documentation uses the Antares ESP MQTT library version 1.0.

{% hint style="info" %}
If you have not installed **Antares ESP MQTT version 1.0**, you can follow these steps.

[antares-wi-fi-mqtt](https://docs.antares.id/en/getting-started/arduino-library-installation/antares-wi-fi-mqtt "mention")
{% endhint %}

3. MQTTX Software&#x20;

{% hint style="info" %}
If you have not installed the MQTTX Software, you can follow the steps in the following link.

[mqttx-installation](https://docs.antares.id/en/getting-started/software-installation/mqttx-installation "mention")
{% endhint %}

## Follow These Steps

### 1. Launch the Arduino IDE application

### 2. Opening Sample Programme

{% hint style="info" %}
You can open the programme code in the Arduino IDE via **File > Examples > Antares ESP HTTP > Lynx32-Simple-Project > RETRIEVE\_DATA\_RELAY\_LED.**
{% endhint %}

Here is the sample programme code of **RETRIEVE\_DATA\_RELAY\_LED**.

```arduino
// Include necessary libraries
#include <AntaresESPMQTT.h> // Include the ESP32 HTTP library
#include <Adafruit_SSD1306.h> // Include the OLED library

// Replace these with your own credentials
#define ACCESSKEY "YOUR-ACCESS-KEY"       // Replace with your Antares account access key
#define WIFISSID "YOUR-WIFI-SSID"         // Replace with your Wi-Fi SSID
#define PASSWORD "YOUR-WIFI-PASSWORD"     // Replace with your Wi-Fi password

#define projectName "YOUR-APPLICATION-NAME"   // Replace with the Antares application name that was created
#define deviceName "YOUR-DEVICE-NAME"     // Replace with the Antares device name that was created

#define relayPin 25
#define ledPin 12

const unsigned long interval = 10000;    // 10 s interval to send message
unsigned long previousMillis = 0;  // will store last time message sent

AntaresESPMQTT antares(ACCESSKEY);

void callback(char topic[], byte payload[], unsigned int length) {
  antares.get(topic, payload, length);

  Serial.println("New Message!");
  Serial.println("Topic: " + antares.getTopic());
  Serial.println("Payload: " + antares.getPayload());

  String relayValue = antares.getString("Relay"); // Change data field to "Relay"
  String ledValue = antares.getString("LED");     // Add reading for "LED" data field
  // Control relay based on received data
  if (relayValue == "1") {
  digitalWrite(relayPin, HIGH);
  } 
  else if (relayValue == "0") {
  digitalWrite(relayPin, LOW);
  }

  // Control LED based on received data
  if (ledValue == "1") {
  digitalWrite(ledPin, HIGH);
  } 
  else if (ledValue == "0") {
  digitalWrite(ledPin, LOW);
  }

  Serial.println("Received data - Relay: " + relayValue + " | LED: " + ledValue);
  
}

void setup() {
    Serial.begin(115200); // Initialize serial communication
    antares.setDebug(true); // Enable debugging for Antares
    antares.wifiConnection(WIFISSID, PASSWORD); // Connect to WiFi
    antares.setMqttServer();
    antares.setCallback(callback);
    pinMode(relayPin, OUTPUT); // Set relayPin as an output
    pinMode(ledPin, OUTPUT); // Set ledPin as an output
}

void loop() {
 /*
    Check if we're still connected to the MQTT broker/server.
    If disconnected, the device will try to reconnect.
   */
  antares.checkMqttConnection();
}
```

### 3. Set WiFi Credential and Antares Credential in Program Code

Change the HTTP Protocol parameters in the following variables **\*ACCESSKEY, \*WIFISSID, \*PASSWORD, \*projectName**, and **\*deviceName**. Adjust to the parameters in the Antares console.

```arduino
#define ACCESSKEY "YOUR-ACCESS-KEY"       // Replace with your Antares account access key
#define WIFISSID "YOUR-WIFI-SSID"         // Replace with your Wi-Fi SSID
#define PASSWORD "YOUR-WIFI-PASSWORD"     // Replace with your Wi-Fi password

#define projectName "YOUR-APPLICATION-NAME"   // Replace with the Antares application name that was created
#define deviceName "YOUR-DEVICE-NAME"     // Replace with the Antares device name that was created
```

{% hint style="info" %}
The **\*Access key** parameter is obtained from your Antares account page.
{% endhint %}

<figure><img src="https://3873791589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7cujmJ5QHdJaAjH815aZ%2Fuploads%2FXFp6dpoqKRlbHS5qPGOt%2Fimage.png?alt=media&#x26;token=524ad85d-72a3-4dba-be84-2d105882eded" alt=""><figcaption><p>Access Key Location on Antares Account Page</p></figcaption></figure>

{% hint style="info" %}
The **WIFISSID** parameter is obtained from the name of the **Wifi / Hotspot** that is currently being used by you. for example in the image below.
{% endhint %}

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/fm60xi9gISZdtrdZHlwd/2.png" alt=""><figcaption><p>WIFISSID</p></figcaption></figure>

{% hint style="info" %}
The **\*PASSWORD** parameter is obtained from the **Wi-Fi password** you are currently using.
{% endhint %}

{% hint style="info" %}
The parameters **\*projectName** and **\*deviceName** are obtained from the **Application Name** and **Device Name** that have been created in the Antares account.
{% endhint %}

<figure><img src="https://3873791589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7cujmJ5QHdJaAjH815aZ%2Fuploads%2Fm90ZA4alRh0frzDc0Jx7%2Fimage.png?alt=media&#x26;token=5ea895f9-3317-482e-a891-c835c4565d68" alt=""><figcaption><p>Application Name Display</p></figcaption></figure>

<figure><img src="https://3873791589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7cujmJ5QHdJaAjH815aZ%2Fuploads%2F1xzLZFehIooERLqDtdzl%2Fimage.png?alt=media&#x26;token=f652a375-afbe-432e-9dad-f31104d9383e" alt=""><figcaption><p>Device Name Display</p></figcaption></figure>

### 4. Compile and Upload Program

Connect the **Lynx-32** with your computer and make sure the **Communication Port** is read.

{% hint style="info" %}
On Windows operating systems the check can be done via **Device Manager**. If your **Lynx-32** is read then the **USB-Serial CH340** appears with the port adjusting the port availability (in this case it reads **COM4**).
{% endhint %}

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/PA42eH2EpLq4N0tZLlVv/4.PNG" alt=""><figcaption><p>Device Manager Display</p></figcaption></figure>

Set up the **ESP32** board by clicking **Tools > Board > esp32** in the Arduino IDE, then make sure the **ESP32 Dev Module** is used. Select the port according to the communication port that is read (in this case COM4). The result will look like the following image.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/2niVmuwhge9zVF5gDwv5/5.png" alt="" width="464"><figcaption><p>Display of Board Specifications and Ports Used</p></figcaption></figure>

After all the setup is complete, upload the programme by pressing the arrow icon as shown below. Wait for the compile and upload process to finish

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/8qATm2UxpYJz4JmKgV3q/6.PNG" alt=""><figcaption><p>Compile Icon for Tick and Upload Icon for Arrow</p></figcaption></figure>

{% hint style="info" %}
**The Tick icon** on the Arduino IDE is just the verify process. Usually used to C**ompile** the programme to find out whether there are errors or not. \
**The Arrow icon** on the Arduino IDE is the verify and upload process. Usually used to **Compile** the programme as well as Flash the programme to the target board.
{% endhint %}

If the programme upload is successful, it will look like the following image.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/DLmtLjXt2FAWhXiP3IXR/7.PNG" alt=""><figcaption><p>Arduino IDE page image after successful upload</p></figcaption></figure>

After uploading the programme, you can view the **serial monitor** to debug the programme. The **serial monitor** icon is shown in the following image.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/cvI0dOV70ZCUdiQllkZZ/8.png" alt=""><figcaption><p>Serial Monitor Icon</p></figcaption></figure>

Set the **serial baud rate** to 115200 and select BothNL & CR. The result will look like the following image.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/X0px2VIGK5s2FiOhrBZn/6_sm.PNG" alt=""><figcaption><p>Serial Monitor Display</p></figcaption></figure>

{% hint style="danger" %}
Make sure the **serial baud rate** matches the value defined in the programme code. If the **serial baud rate** is not the same between **the programme code** and **the serial monitor**, the ASCII characters will not be read properly.
{% endhint %}

### 5. MQTTX Software Setup

**Open the MQTTX App, then select New Connection**

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/1Qf76slCEoCoPHY8EaOn/New%20Connection%20MQTTX.jpg" alt=""><figcaption><p>Creating a New Connection</p></figcaption></figure>

In order to configure MQTTX with Antares broker, adjust the Name, Host and Port as shown below, then click Connect.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/dNBW0rKB5prlnMoAuJBU/Configuration%20MQTTX.jpg" alt=""><figcaption><p>Antares MQTT Broker Configuration</p></figcaption></figure>

If it is connected, there is a notification as shown belowt

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/6skt10X3v8JfmU8RHIcd/Connected%20MQTTX.jpg" alt=""><figcaption><p>Antares Broker MQTTX Connected</p></figcaption></figure>

Enter **Topic** and **Payload** in the fields in MQTTX.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/CXpcEzhL2lqavulFfoUA/Topic%20dan%20Payload%20MQTTX.jpg" alt=""><figcaption><p>Topic and Payload pages in MQTTX</p></figcaption></figure>

<table><thead><tr><th width="111">Field</th><th>Value</th></tr></thead><tbody><tr><td><strong>Topic</strong></td><td><mark style="color:red;"><code>/oneM2M/req/your-access-key/antares-cse/json</code></mark></td></tr><tr><td><strong>Payload</strong></td><td><pre class="language-json"><code class="lang-json">{
      "m2m:rqp": {
        "fr": "your-access-key",
        "to": "/antares-cse/antares-id/nama-aplikasi-anda/nama-device-anda",
        "op": 1,
        "rqi": 123456,
        "pc": {
          "m2m:cin": {
            "cnf": "message",
            "con": "{\"your-first-data\":\"the-integer-value\",\"your-second-data\":\"the-string-data\"}"
          }
        },
        "ty": 4
      }
    }
</code></pre></td></tr></tbody></table>

{% hint style="info" %}
Customise <mark style="color:red;">your-access-key</mark>, <mark style="color:red;">your-application-name</mark>, and <mark style="color:red;">your-device-name</mark> to the names registered to your Antares account. Fill in the "Field" data and "Value" data in "con" as you wish.
{% endhint %}

In the MQTTX software, enter the Topic and Payload that you want to use. Then click Publish to send the message from MQTTX to the Antares server.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/QBATHqNKro8I254CpH7M/Publish%20to%20Antares%20MQTTX.jpg" alt=""><figcaption><p>Publish to send the message to the Antares server</p></figcaption></figure>

### **6.** Sending MQTTX Messages to the Antares Server

After the MQTTX software setup is complete, it's time to send the PUBLISH command. The "Relay" field is filled with the string "1" or "0" as the command message for the Relay which will be sent via the MQTT protocol to the Antares server. The "LED" field is filled with the string "1" for LED ON or "0" for LED OFF as a command message for the LED that will be sent via the MQTT protocol to the Antares server.

```json
{
      "m2m:rqp": {
        "fr": "your-access-key",
        "to": "/antares-cse/antares-id/nama-aplikasi-anda/nama-device-anda",
        "op": 1,
        "rqi": 123456,
        "pc": {
          "m2m:cin": {
            "cnf": "message",
            "con": "{\"Relay\":\"1\",\"LED\":\"1\"}"
          }
        },
        "ty": 4
      }
    }
```

If you have finished filling in the "test" field, then press the **PUBLISH** button on the MQTTX software located to the right of the Topic filling column, as shown below.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/DrJuPD1ys7nyBGQz60nw/Relay_LED%20MQTTX.jpg" alt=""><figcaption><p>MQTTX Payload content image</p></figcaption></figure>

If it has been published, the MQTTX page will have a message like the following.

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/2gmPYt5tN6r3tncKEZMQ/Published%20MQTTX.jpg" alt=""><figcaption><p>Message Notification Published</p></figcaption></figure>

### 7. Check Data in Antares

After uploading the programme successfully, then open the device antares page and see if the data has been successfully sent.

<figure><img src="https://3873791589-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F7cujmJ5QHdJaAjH815aZ%2Fuploads%2FmSI9Fm10YrK7bfzR0V4G%2Fimage.png?alt=media&#x26;token=32e6c1b1-1527-457c-a518-af237070b421" alt=""><figcaption><p>Image of the Antares Console Page When Data is Successfully Received.</p></figcaption></figure>

{% hint style="info" %}
The data received by **LYNX-32** with the MQTT protocol is in the form of Relay and LED variables.
{% endhint %}

### 8. View Retrieve Message&#x20;

Retrieve data from the **Antares IoT Platform** and display it on the OLED display after connecting to Wi-Fi as shown in the figure below:

<figure><img src="https://content.gitbook.com/content/7cujmJ5QHdJaAjH815aZ/blobs/mbWPfB48yYLMWIRKIkTz/IMG_20230809_061851.jpg" alt=""><figcaption><p>OLED Display</p></figcaption></figure>
