Hey guys,
I have run into a bit of a roadblock the last few days with connecting up a ESP8266-01 to Arduino Nano.
I have managed to flash the ESP8266 through the Arduino and connect to my WIFI network and also establish a connection with the MQTT server, but for the life of me I can't find a good method or example for the communication between the ESP8266 and the Arduino.
My first thought was to make a serial connection but all the examples I looked at just push the settings from the Arduino Firmware into the ESP8266 and you have to end up using Serial monitor to invoke everything.
Is there an easier solution? I have read a few hundred blog posts and can't find any bilateral solution to this.
This is currently my ESP code, Not sure where to go with the Arduino code:
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const char* ssid = "";
const char* password = "";
const char* mqttServer = "";
const int mqttPort = 1883;
const char* mqttUser = "";
const char* mqttPassword = "";
const char* mqttTopic = "home/kitchen/light";
const char* buttonON = 0;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
// Switch on the LED if an 1 was received as first character
if ((char)payload[0] == '1') {
Serial.print("Passed IF");
digitalWrite(LED_BUILTIN, LOW);
// but actually the LED is on; this is because
// it is active low on the ESP-01)
} else {
digitalWrite(LED_BUILTIN, HIGH);
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish(mqttTopic, "hello world");
// ... and resubscribe
client.subscribe(mqttTopic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}