Hello Pete,
Thank you very much for your reply. The code I made indeed does subscribe and publish to the same topic, this with a delay of 5 seconds. I also tested it with 2 Wemos devices and had the first measuring and publishing and the second subscribing and writing to the serial monitor and that worked well.
Since I am not very good at coding myself, I wrote the code mostly by copying and pasting examples from the web. Therefore also I think it’s strange that the Nodered to Wemos link is not working, as this seems so simple in all these examples.
I read your comments about the MQTTcallback function, but I don’t think it’s in the basis very different of the way the topic is handled in my callback function?
Here is my code, maybe you can see something strange in it?
/*
Basic ESP8266 MQTT example
....
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESP8266Ping.h>
// Update these with values suitable for your network.
const char* ssid = "";
const char* password = "";
const char* mqtt_server = "192.168.68.107";
const char* MQTT_username = "";
const char* MQTT_password = "";
const IPAddress remote_ip_RPI(192, 168, 68, 107); // RPI
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
// US distance sensor:
const int trigPin = 12; // D6
const int echoPin = 13; // D7
long duration;
float distance;
// Timers auxiliar variables
long now = millis();
long lastMeasure = 0;
// Ledkleuren:
#define uit 0
#define blauw 1
#define groen 2
#define magenta 3
#define rood 4
#define lichtblauw 6
int RodePin = 0; // Rode pin voor Led = D8
int GroenePin = 2; // Groene pin voor Led = D9
int BlauwePin = 15; // Blauwe pin voor Led = D10
bool Success;
//-----------------------------------------------------------------------------------------
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
//-----------------------------------------------------------------------------------------
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message arrived at ");
Serial.print(topic);
Serial.print("; Message: ");
String messageTemp;
//Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
messageTemp += (char)payload[i];
}
Serial.println();
//------------------------
if(topic = "test"){
//Serial.print("Changing LED to ");
if(messageTemp.toFloat() <= 6){
LedAan(1);
//Serial.println("blauw");
}
else if(messageTemp.toFloat() > 6){
LedAan(2);
//Serial.println("groen");
}
}
}
//-----------------------------------------------------------------------------------------
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(), MQTT_username, MQTT_password)) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("test", "hello world");
// ... and resubscribe
client.subscribe("test");
//client.subscribe("test/dist"); // Evt subscribtion to 2nd topic
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
//--------------------------------------------------------------------------------------------------------------
void LedAan(int Kleurfunctie)
{
switch(Kleurfunctie)
{
case 0: // Led uit
analogWrite(RodePin,0);
analogWrite(BlauwePin,0);
analogWrite(GroenePin,0);
break;
case 1: // blauw
analogWrite(RodePin,0);
analogWrite(BlauwePin,255);
analogWrite(GroenePin,0);
break;
case 2: // groen
analogWrite(RodePin,0);
analogWrite(BlauwePin,0);
analogWrite(GroenePin,255);
break;
case 3: // magenta
analogWrite(RodePin,255);
analogWrite(BlauwePin,255);
analogWrite(GroenePin,0);
break;
case 4: // rood
analogWrite(RodePin,255);
analogWrite(BlauwePin,0);
analogWrite(GroenePin,0);
break;
case 6: // lichtblauw
analogWrite(RodePin,255);
analogWrite(BlauwePin,150);
analogWrite(GroenePin,255);
break;
}
}
//--------------------------------------------------------------------------------------------------------------
void MeasureDist()
{
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance = duration * 0.034 / 2;
client.publish("test", String(distance).c_str()); // Publish distance value
}
//---------------------------------------------------------------
void Pinging(IPAddress remote_ip)
{
Serial.print("Pinging ip ");
Serial.println(remote_ip);
if(Ping.ping(remote_ip))
{
Serial.println("Success!!");
Success = true;
}
else {
Serial.println("Error :(");
Success = false;
}
delay(5000);
}
//=======================================================================================
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
pinMode(RodePin, OUTPUT);
pinMode(BlauwePin, OUTPUT);
pinMode(GroenePin, OUTPUT);
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
//=======================================================================================
void loop() {
//Pinging(remote_ip_RPI);
//delay(10000);
if (!client.connected()) {
reconnect();
}
client.loop();
// Publishes new distance every 5 seconds
now = millis();
if (now - lastMeasure > 5000)
{
lastMeasure = now;
MeasureDist();
//snprintf (msg, MSG_BUFFER_SIZE, "Distance = %ld", distance);
snprintf (msg, MSG_BUFFER_SIZE, "Distance = %f", distance);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("test", msg);
}
}
Configuration of the upper MQTT-in Node in Nodered:
… and the debug-node: