/* Virtuino IoT
* Example: MQTT communication between ESP32/ESP8266 and Thingspeak MQTT
Updated: Mar/26/2023
Created by: Ilias Lamprou
https://virtuino.com
On the code below you have to replace:
1. Your wifi ssid and password
2. The Thingspeak channel id
3. The Thingspeak MQTT Device Credentials
*/
//--------------------------------------------------------------------
//------------------------ Settings-----------------------------------
//--------------------------------------------------------------------
char ssid[] = "Wokwi-GUEST"; // Change this to your network SSID (name).
char pass[] = ""; // Change this your network password
//------ MQTT broker settings and topics
const char* mqtt_server = "mqtt3.thingspeak.com";
//-- published settings
const char* publishTopic ="channels/2383455/publish"; //REPLACE THE NUMBER 114938 WITH YOUR channel ID
//-- subscribed settings Virtuino command 1
const char* subscribeTopicFor_Command_1="channels/2383455/subscribe/fields/field1"; //REPLACE THE NUMBER 114938 WITH YOUR channel ID
//const char* subscribeTopicFor_Command_2="channels/114938/subscribe/fields/field2"; //REPLACE THE NUMBER 114938 WITH YOUR channel ID
const unsigned long postingInterval = 20L * 1000L; // Post data every 20 seconds.
//------------------------ Variables-----------------------------------
//-------------------------------------------------------------------------
#ifdef ESP8266
#include <ESP8266WiFi.h>
#else
#include <WiFi.h>
#endif
#include <PubSubClient.h>
#include <WiFiClient.h>
WiFiClient espClient;
PubSubClient client(espClient); // Download the library PubSubClient from the arduino library manager
unsigned long lastUploadedTime = 0;
//==========================================
void setup_wifi() {
delay(10);
Serial.print("\nConnecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("\nWiFi connected\nIP address: ");
Serial.println(WiFi.localIP());
}
//=====================================
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
//client.connect("cliend ID", "username","password") Replace with your Thingspeak MQTT Device Credentials
if (client.connect("HhcoKTERBSM4DjgoIjwtBgc", "HhcoKTERBSM4DjgoIjwtBgc","AZBAiZGJ0LCzsuvmPDr4OGWj")) {
Serial.println("connected");
client.subscribe(subscribeTopicFor_Command_1); // subscribe the topics here
//client.subscribe(command2_topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying
delay(5000);
}
}
}
//========================================= messageReceived
void messageReceived(String &topic, String &payload) {
Serial.println("incoming: " + topic + " - " + payload);
//-- check for Virtuino Command 1
if (topic==subscribeTopicFor_Command_1){
Serial.println("Command 1 = "+payload);
int v = payload.toInt();
if (v>0) digitalWrite(LED_BUILTIN,HIGH);
else digitalWrite(LED_BUILTIN,LOW);
}
/*//-- check for Virtuino Command 1
if (topic==subscribeTopicFor_Command_2){
Serial.println("Command 2 = "+payload);
}
*/
}
//========================================= setup
//=========================================
void setup() {
pinMode(LED_BUILTIN,OUTPUT);
Serial.begin(9600);
while (!Serial) delay(1);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
//========================================= loop
//=========================================
void loop() {
if (!client.connected()) reconnect();
client.loop();
if (millis() - lastUploadedTime > postingInterval) { // The uploading interval must be > 15 seconds
int sensorValue_1 = random(100); // replace with your sensor value
int sensorValue_2=random(100); // replace with your sensor value
//int sensorValue_3=random(100); // if you want to use three sensors enable this line
String dataText = String("field1=" + String(sensorValue_1)+ "&field2=" + String(sensorValue_2)+"&status=MQTTPUBLISH");
//String dataText = String("field1=" + String(sensorValue_1)+ "&field2=" + String(sensorValue_2)+"&field3=" + String(sensorValue_3)); // example for publish tree sensors
publishMessage(publishTopic,dataText,true);
lastUploadedTime = millis();
}
}
//=======================================
// This void is called every time we have a message from the broker
void callback(char* topic, byte* payload, unsigned int length) {
String incommingMessage = "";
for (int i = 0; i < length; i++) incommingMessage+=(char)payload[i];
Serial.println("Message arrived ["+String(topic)+"]"+incommingMessage);
//--- check the incomming message
if( strcmp(topic,subscribeTopicFor_Command_1) == 0){
if (incommingMessage.equals("1")) digitalWrite(BUILTIN_LED, LOW); // Turn the LED on
else digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off
}
}
//======================================= publising as string
void publishMessage(const char* topic, String payload , boolean retained){
if (client.publish(topic, payload.c_str()))
Serial.println("Message publised ["+String(topic)+"]: "+payload);
}