IOT

Connecting ESP8266 to Amazon AWS IoT Core using MQTT

This is an introduction to Amazon Web Services, specifically AWS IoT Core using the ESP8266. The AWS IoT Core is a managed cloud service that allows connected devices to interface with cloud applications and other devices in a simple and safe manner.

We’ll learn how to connect the ESP8266 to AWS IoT Core and publish sensor data to AWS MQTT in this tutorial. We’ll use the DHT11 Sensor to read the humidity temperature data as an example. The NodeMCU ESP8266 will connect to the local WiFi network and upload the data from the DHT11 Sensor to the AWS IoT Cloud. Not only can we send data to AWS Dashboard, but we can also receive it.

The tutorial comprises multiple sections

  • Signing up & setting the Amazon Web Services
  • Installing Necessary Libraries to Arduino IDE & Writing an Arduino Sketch for the project
  • Creating a Thing is AWS
  • Creating Policy and attaching to Thing
  • Generating Certificates
  • Modifying Arduino Sketch according to Thing Data & Credentials
  • Subscribe & Publish Data to and from AWS Dashboard

This tutorial is intended for people who are new to Amazon AWS IoT Core for IoT Applications. We previously discussed IoT platforms such as Google Firebase and Arduino IoT Cloud. However, with AWS IoT Core, you may create and manage devices for commercial use.

Hardware Setup

An ESP8266 Wifi Module is required for this project’s hardware. We’ll use a DHT11 Humidity and Temperature Sensor for the sensor.

As shown in the circuit diagram, connect the DHT11 Sensor to the ESP8266 Board. Connect the DHT11’s VCC and GND pins to the ESP8266’s 3.3V and GND. Similarly, connect DHT11’s signal pin to NodeMCU ESP8266’s D2 (GPIO4).

ESP8266 DHT11 AWS IoT Core

A breadboard or a male-to-female connector wire can be used to make the connection.

What is Amazon AWS IoT Core?

AWS provides Internet of Things (IoT) services and solutions that enable billions of devices to be connected and managed. These cloud services allow your IoT devices to communicate with other devices as well as AWS cloud services. Device software from AWS IoT can help you link your IoT devices with AWS IoT-based solutions. If your devices are compatible with AWS IoT, AWS IoT can link them to AWS cloud services.

what is aws iot

You can choose the most relevant and up-to-date technology for your solution using AWS IoT. AWS IoT Core supports the following protocols to help you manage and support your IoT devices in the field:

  • MQTT (Message Queuing and Telemetry Transport)
  • MQTT over WSS (Websockets Secure)
  • HTTPS (Hypertext Transfer Protocol – Secure)
  • LoRaWAN (Long Range Wide Area Network)

Getting Started with Amazon AWS IoT Core with ESP8266

It’s very easy to get started using AWS IoT core. To successfully set up the ESP8266 board and begin working on your first project, simply follow the procedures outlined below.

Signing in

Go to your web browser and search visit following link: aws.amazon.com/iot-core/.

Now is the time to set up the AWS account. Create an account with your email address and password. Your bank credit card information is also required by the account. There will be no fees, however AWS will require a bank account verification. It will also need confirmation of your phone number. As a result, the account will be established successfully.

AWS IoT Core Dashboard

The AWS Management Console window will open after you have successfully signed in. Write ‘IoT core’ in the services search tab at the top and push enter.

AWS IoT Core Dashboard

You can now click on IoT Core to open the AWS IoT Dashboard.

There are numerous options on the dashboard’s left side. However, we must choose between two possibilities. The manage option is one, and the secure option is another.

Creating a Thing

Now we must create a thing related to our project. Follow these steps to achieve this:

  • Specifying thing properties
  • Configuring device certificate
  • Attaching policies to certificate

Select Thing from the Manage menu. We must now create a Thing at this location. So, go ahead and click Create Things.

You can select whether create a single thing or create many things. But for our applications, select create a single thing. Then select Next.

Specify Thing Properties

The Thing properties must be specified here. Give the object a name first. You can call it whatever you like. For instance, I’ll call it ESP8266.

  • Under additional configurations, there is no need to make any changes.
  • Select No shadow as the first option under the device shadow option. Then select Next.

Generate Device Certificate

You must now configure the device certificate. So you can generate a new certificate automatically, use your own certificate, submit a CSR, or skip this step.

However, AWS recommends using the Auto Generate New Certificate option. Then select Next.

Create & Attach Policy

We must now assign a policy to the Things we have built. However, no policies are currently in place. As a result, we must first develop a policy.

  • So, select Create Policy. Give the policy any name here. For example, ESP8266 Policy” will be its name.
  • Now comes the crucial part: the add statement. Type IoT in the action field. As a result, a variety of possibilities will appear. We only need to post, subscribe, connect, and receive from here.

Select the IoT Connect option first. Replace the last section of the Resource ARN with the Client ID. Give the client ID any name, such as “ESP8266.” Select allow under effect.

  • Add another statement. Choose IoT Publish this time. Replace the last section of the resource ARN with esp8266/pub. Select allow once more under effect.
  • Add the third statement once more. Choose IoT Subscribe this time. Replace the last section of the resource ARN with esp8266/sub. Select allow once more under effect.
  • Now add the fourth statement. Choose IoT Receive this time. Replace the last section of the resource ARN with esp8266/sub. Select allow once more under effect.
  • To create the policy, click Create. As a result, the policy has been effectively created.
  • Return to the Create Thing option now. As a result, a policy option will be available. The policies must be attached to the certificate. Select the policy that appears and click Create a Thing.

Downloading Certificates and Keys

Now we must obtain the necessary certificates from this list.

  • To identify the device certificate, first download it and rename it as a device certificate.
  • Also, save the public key as a public key and rename it. Then save the private key and rename it to something else.
  • There are two certificates among the Root CA Certificates. However, we just require a Root CA1 certificate, so please get it as well.

So we have downloaded all the certificates that we need for our project.

Installing Necessary Arduino Libraries

1. ArduinoJSON Library

So, go to the library manager and search for “JSON” before installing the library as shown below.

2. PubSubClient Library

Search for “PubSubClient” in the library manager and install the library from Nick O’Leary.

PubSubClient Library

3. DHT11 Sensor Library

Search for “dht11” & install the library as shown below.

DHT11 Library

Source Code/Program for connecting AWS IoT Core with ESP8266

The Arduino IDE is used to write the code that connects the ESP8266 to the DHT11 Sensor and the Amazon AWS IoT Core. There are two portions to the code. The main ino file and the header file are the two files.

Main .ino File

In the Arduino IDE, create a new sketch and put the following code into it.

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <time.h>
#include “secrets.h”
#include “DHT.h”

#define DHTPIN 4 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11

DHT dht(DHTPIN, DHTTYPE);

float h ;
float t;
unsigned long lastMillis = 0;
unsigned long previousMillis = 0;
const long interval = 5000;

#define AWS_IOT_PUBLISH_TOPIC “esp8266/pub”
#define AWS_IOT_SUBSCRIBE_TOPIC “esp8266/sub”

WiFiClientSecure net;

BearSSL::X509List cert(cacert);
BearSSL::X509List client_crt(client_cert);
BearSSL::PrivateKey key(privkey);

PubSubClient client(net);

time_t now;
time_t nowish = 1510592825;


void NTPConnect(void)
{
Serial.print(“Setting time using SNTP”);
configTime(TIME_ZONE * 3600, 0 * 3600, “pool.ntp.org”, “time.nist.gov”);
now = time(nullptr);
while (now < nowish)
{
delay(500);
Serial.print(“.”);
now = time(nullptr);
}
Serial.println(“done!”);
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
Serial.print(“Current time: “);
Serial.print(asctime(&timeinfo));
}


void messageReceived(char *topic, byte *payload, unsigned int length)
{
Serial.print(“Received [“);
Serial.print(topic);
Serial.print(“]: “);
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println();
}


void connectAWS()
{
delay(3000);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

Serial.println(String(“Attempting to connect to SSID: “) + String(WIFI_SSID));

while (WiFi.status() != WL_CONNECTED)
{
Serial.print(“.”);
delay(1000);
}

NTPConnect();

net.setTrustAnchors(&cert);
net.setClientRSACert(&client_crt, &key);

client.setServer(MQTT_HOST, 8883);
client.setCallback(messageReceived);


Serial.println(“Connecting to AWS IOT”);

while (!client.connect(THINGNAME))
{
Serial.print(“.”);
delay(1000);
}

if (!client.connected()) {
Serial.println(“AWS IoT Timeout!”);
return;
}
// Subscribe to a topic
client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC);

Serial.println(“AWS IoT Connected!”);
}


void publishMessage()
{
StaticJsonDocument<200> doc;
doc[“time”] = millis();
doc[“humidity”] = h;
doc[“temperature”] = t;
char jsonBuffer[512];
serializeJson(doc, jsonBuffer); // print to client

client.publish(AWS_IOT_PUBLISH_TOPIC, jsonBuffer);
}


void setup()
{
Serial.begin(115200);
connectAWS();
dht.begin();
}


void loop()
{
h = dht.readHumidity();
t = dht.readTemperature();

if (isnan(h) || isnan(t) ) // Check if any reads failed and exit early (to try again).
{
Serial.println(F(“Failed to read from DHT sensor!”));
return;
}

Serial.print(F(“Humidity: “));
Serial.print(h);
Serial.print(F(“% Temperature: “));
Serial.print(t);
Serial.println(F(“°C “));
delay(2000);

now = time(nullptr);

if (!client.connected())
{
connectAWS();
}
else
{
client.loop();
if (millis() – lastMillis > 5000)
{
lastMillis = millis();
publishMessage();
}
}
}

Secrets.h

In the Arduino IDE, create a new tab and name it Secrets.h. And then paste the code below into this file.



#include <pgmspace.h>

#define SECRET

const char WIFI_SSID[] = “*****************”; //TAMIM2.4G
const char WIFI_PASSWORD[] = “*****************”; //0544287380

#define THINGNAME “**************”

int8_t TIME_ZONE = -5; //NYC(USA): -5 UTC

const char MQTT_HOST[] = “******************************”;


static const char cacert[] PROGMEM = R”EOF(
—–BEGIN CERTIFICATE—–

—–END CERTIFICATE—–
)EOF”;


// Copy contents from XXXXXXXX-certificate.pem.crt here ▼
static const char client_cert[] PROGMEM = R”KEY(
—–BEGIN CERTIFICATE—–

—–END CERTIFICATE—–

)KEY”;


// Copy contents from XXXXXXXX-private.pem.key here ▼
static const char privkey[] PROGMEM = R”KEY(
—–BEGIN RSA PRIVATE KEY—–

—–END RSA PRIVATE KEY—–

)KEY”;

Modifying Arduino Sketch according to the Thing

It’s now time to make changes to the Arduino Sketch File. Begin the modification in the secrets.h tab.

A object’s name must be included here. You can copy the item name from the AWS Console’s things section.

.

Copy and paste the thing’s name onto the next line of code.

#define THINGNAME “***************”   

Under the WiFi SSID and password, enter the WiFi SSID and Password of your local network.

const char WIFI_SSID[] = “***************”;
const char WIFI_PASSWORD[] = “***************”;

We must now add the AWS IoT Endpoint here. Go to the settings section of the AWS Dashboard to get the endpoint. The endpoint will be obtained by you.

To copy the endpoint, click the copy icon. Return to the Arduino IDE and paste it on the next line.

const char AWS_IOT_ENDPOINT[] = “***************”;

Between the following lines, you must insert the Amazon Root CA1.

// Amazon Root CA 1
static const char AWS_CERT_CA[] PROGMEM = R”EOF(
—–BEGIN CERTIFICATE—–

—–END CERTIFICATE—–
)EOF”;

So for this, we need to go back to the certificate that we downloaded earlier. Open this file with Notepad++ and copy all the text.

Return to the Arduino IDE and insert the pasted content between the begin and end certificates.

We need to paste the device certificate text under the “Device Certificate” lines. So, open the device certificate file we previously downloaded. Copy the text once more and paste it between the begin and end certificate sections.

// Device Certificate
static const char AWS_CERT_CRT[] PROGMEM = R”KEY(
—–BEGIN CERTIFICATE—–

—–END CERTIFICATE—–

The device’s private key must be entered under “Device Private Key.” So go back to the downloaded folder and use Notepad++ to access the device’s private key file. Copy the content and paste it between the beginning and finish parts once more.

// Device Private Key
static const char AWS_CERT_PRIVATE[] PROGMEM = R”KEY(
—–BEGIN RSA PRIVATE KEY—–

—–END RSA PRIVATE KEY—–

So that’s it for the AWS IoT Core-related changes to the Arduino ESP8266 Sketch.

Testing the Publishing & Subscription of Data

Connect the NodeMCU ESP8266 to your PC once all of the modifications have been completed. Then go to the tools menu and choose the NodeMCU 1.0 Board for this project. Select the COM port as well. Then, to upload the code to the ESP8266 board, select the upload option.

Open the Serial Monitor once the code has been uploaded. The ESP8266 will make an attempt to connect to the WiFi network. It will attempt to connect to the AWS IoT Server once it has joined to the WiFi network.

Amazon AWS IoT Core ESP8266

On the Serial Monitor, the humidity and temperature values will be displayed.

Subscribing Sensor Data to AWS Dashboard

The AWS Server should receive the same information. Go to the AWS Dashboard’s test area to verify this. We have a subscribe and publish option in the test area.

You must now subscribe to a topic in order to see the data. Under the topic filter area, type “esp8266/pub.” If you like, you can adjust the additional configuration.

Then press the subscribe button. When you press the subscribe button, the data from the ESP8266 is immediately posted to AWS Dashboard. Thus, using the ESP8266, you have successfully delivered the DHT11 Sensor data and time data to Amazon AWS IoT Core.

AWS IoT Core Dashboard ESP8266

After a one-second period, the data is refreshed here. This is fantastic since we can send data from the ESP8266 to the AWS IoT Core Dashboard via the MQTT protocol. We read the subscribed data in this manner.

Publishing Data to Serial Monitor

Now let’s try whether we can publish data from the AWS IoT core to the ESP8266.

  • You must now publish a subject in order to see the data. Under the topic filter area, type “esp8266/sub.” Do nothing under further configuration. Then press the publish button.
  • The message sent to the Serial Monitor is immediately visible.
Amazon AWS IoT Core ESP8266

This is how you can use ESP8266 to send and receive data via Amazon AWS IoT Core. We can subscribe to sensor readings topics issued by multiple IoT nodes using AWS MQTT. This is an introductory tutorial for people who want to use Amazon Web Services for their IoT devices.

Conclusion

Hope this blog helps you to understand how to connect ESP8266 to Amazon AWS IoT Core using MQTT. We, MATHA ELECTRONICS  will come back with more informative blogs.

Leave a Reply

Your email address will not be published.