-
-
Save jameshi16/7f277bb8dfecf38a30aea0093f30477a to your computer and use it in GitHub Desktop.
[Mine] ESP32 -> AWS IoT via MQTT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <WiFi.h> | |
#include <WiFiClientSecure.h> | |
#include <PubSubClient.h> | |
#define LED_PIN 2 | |
/* Change the following configuration options */ | |
const char* ssid = ""; | |
const char* password = ""; | |
const char* aws_iot_hostname = ""; | |
const char* aws_iot_sub_topic = ""; | |
const char* aws_iot_pub_topic = ""; | |
const char* aws_iot_pub_message = "Acknowledged."; | |
const char* client_id = "MyIoT"; | |
const char* ca_certificate = ""; //CA certificate | |
const char* iot_certificate = ""; //Own certificate | |
const char* iot_privatekey = ""; //Own private key | |
#define SSID_HAS_PASSWORD //comment this line if your SSID does not have a password | |
/* Global Variables */ | |
WiFiClientSecure client; | |
PubSubClient mqtt(client); | |
/* Functions */ | |
void sub_callback(const char* topic, byte* payload, unsigned int length) { | |
Serial.print("Topic: "); | |
Serial.println(topic); | |
Serial.print("Message: "); | |
for (int i = 0; i < length; i++) | |
Serial.print((char) payload[i]); | |
Serial.println(); | |
if ((char) payload[0] == '1') | |
digitalWrite(LED_PIN, HIGH); | |
else if ((char) payload[0] == '0') | |
digitalWrite(LED_PIN, LOW); | |
mqtt.publish(aws_iot_pub_topic, aws_iot_pub_message); | |
} | |
void setup() { | |
//Initializations | |
Serial.begin(9600); | |
Serial.print("Attempting WiFi connection on SSID: "); | |
Serial.print(ssid); | |
pinMode(LED_PIN, OUTPUT); | |
digitalWrite(LED_PIN, LOW); | |
// WiFi | |
#ifdef SSID_HAS_PASSWORD | |
WiFi.begin(ssid, password); | |
#else | |
WiFi.begin(ssid); | |
#endif | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print('.'); | |
} | |
Serial.print("\nWiFi connection succeeded.\n"); | |
client.setCACert(ca_certificate); | |
client.setCertificate(iot_certificate); | |
client.setPrivateKey(iot_privatekey); | |
// AWS IoT MQTT uses port 8883 | |
mqtt.setServer(aws_iot_hostname, 8883); | |
mqtt.setCallback(sub_callback); | |
} | |
void loop() { | |
// reconnect on disconnect | |
while (!mqtt.connected()) { | |
Serial.print("Now connecting to AWS IoT: "); | |
if (mqtt.connect(client_id)) { | |
Serial.println("connected!"); | |
mqtt.subscribe(aws_iot_sub_topic); //subscribe to the topic | |
} else { | |
Serial.print("failed with status code "); | |
Serial.print(mqtt.state()); | |
Serial.println(" trying again in 5 seconds..."); | |
delay(5000); | |
} | |
} | |
mqtt.loop(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment