So you're a Noob? Post your questions here until you graduate! Don't be shy.

User avatar
By Gdipstick
#72940 i'm trying to publish some variable to MQTTBox from a very simple push button counter experiment... the experiment also lights up an rgbled with random colors, I'm successful at publishing the button count and the random color values to the serial printer, but i'm having trouble doing the same using similiar 'client.publish' commands... i'm not sure what the parameter should be for a variables, the count and the rgb values.....

this is a long overdue follow up to my previous:
RGBLED.H LIBRARY ON ESP8266 VS. UNO
viewtopic.php?f=160&t=16042

here's the sketch, a little messy and unstable but hey, it works....




Code: Select all#include <ESP8266WiFi.h>
#include <PubSubClient.h>

int BUTTON_PIN = D3; //button is connected to GPIO pin D3
// Update these with values suitable for your network.
const char* ssid = "?";//put your wifi ssid here
const char* password = "?";//put your wifi password here.
const char* mqtt_server = "broker.mqtt-dashboard.com";
//const char* mqtt_server = "iot.eclipse.org";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];

void setup_wifi() {
   delay(100);
  // We start by connecting to a WiFi network
    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)
{
 
} //end callback

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 you MQTT broker has clientID,username and password
    //please change following line to    if (client.connect(clientId,userName,passWord))
    if (client.connect(clientId.c_str()))
    {
      Serial.println("connected");
     //once connected to MQTT broker, subscribe command if any
      client.subscribe("OsoyooCommand");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
} //end reconnect()

// this constant won't change:

const int  buttonPin = D3;    // the pin that the pushbutton is attached to


// Variables will change:
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;     // previous state of the button
//How long to show each color in the example code (in milliseconds);
int delayMs = 1000;

//
#include <RGBLED.h>

//

// Declare an RGBLED instanced named rgbLed
// Red, Green and Blue LED legs are connected to PWM pins 5,6 & 7 respectively
// In this example, we have a COMMON_ANODE LED, use COMMON_CATHODE otherwise
RGBLED rgbLed(D5,D6,D7,COMMON_ANODE);
//
//// sketch 09_02

void setup() {
  // initialize serial communication:
  Serial.begin(115200);
    setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  pinMode(BUTTON_PIN,INPUT);

//  make the RGBLED library ESP compatible

analogWriteRange(255);

  pinMode(buttonPin, INPUT);

// Report the LED type and pins in use to the serial port...
Serial.println("Welcome to the RGBLED Sample Sketch");
String ledType = (rgbLed.commonType==0) ? "COMMON_CATHODE" : "COMMON_ANODE";
Serial.println("Your RGBLED instance is a " + ledType + " LED");
Serial.println("And the Red, Green, and Blue legs of the LEDs are connected to pins:");
Serial.println("r,g,b = " + String(rgbLed.redPin) + "," + String(rgbLed.greenPin) + "," + String(rgbLed.bluePin) );
Serial.println("");

}

void loop() {
    if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  int status;
 
  // read the pushbutton input pin:
  buttonState = digitalRead(buttonPin);
   
  // compare the buttonState to its previous state
  if (buttonState != lastButtonState) {
    // if the state has changed, increment the counter
    if (buttonState == HIGH) {
      // if the current state is HIGH then the button
      // went from off to on:
      buttonPushCounter++;
      Serial.println("on");
      Serial.print("number of button pushes:  ");
      Serial.println(buttonPushCounter);
      client.publish("OsoyooDataF", "on");
      client.publish("OsoyooDataF", "number of button pushes:  ");
//      client.publish("OsoyooDataF",(buttonPushCounter));
/*  this is where i receive an error...  i simply want to publish the counter # to the MQTT box...
Arduino: 1.8.2 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

C:\Users\GADAWE\Documents\Arduino\node_ct_rgb_box\node_ct_rgb_box.ino: In function 'void loop()':

node_ct_rgb_box:136: error: invalid conversion from 'int' to 'const char*' [-fpermissive]

       client.publish("OsoyooDataF",(buttonPushCounter));

                                                       ^

In file included from C:\Users\GADAWE\Documents\Arduino\node_ct_rgb_box\node_ct_rgb_box.ino:2:0:

C:\Program Files\arduino-1.8.2\libraries\pubsubclient\src/PubSubClient.h:130:12: error:   initializing argument 2 of 'boolean PubSubClient::publish(const char*, const char*)' [-fpermissive]

    boolean publish(const char* topic, const char* payload);

            ^

exit status 1
invalid conversion from 'int' to 'const char*' [-fpermissive]

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
*/
    } else {
      // if the current state is LOW then the button
      // went from on to off:
      Serial.println("off");
    }
   
    // Delay a wee bit to avoid bouncing
    delay(500);
  }
 
  // save the current state as the last state,
  //for next time through the loop
  lastButtonState = buttonState;



//   now the random color LED
//   read the state of the pushbutton value:
//   check if the pushbutton is pressed.
//   if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    rgbLed.writeRandom();
    digitalWrite(LED_BUILTIN, HIGH);
    printRgbValues();
 delay(2000);
  } else {
    // turn LED off:
digitalWrite(LED_BUILTIN, LOW);
  rgbLed.turnOff();

}
}
//printRgbValues prints the LED pins and values to the serial port
//You can monitor the serial port to see those values
void printRgbValues() {
  Serial.println("Requested RGB Values:");
  Serial.println("Mapped RGB Values based on type (COMMON_ANODE or COMMON_CATHODE):");
  Serial.println("Mapped(r,g,b)=(" + String(rgbLed.redMappedValue) + "," + String(rgbLed.greenMappedValue) + "," + String(rgbLed.blueMappedValue) + ")");
  Serial.println("------------------------------");
  client.publish("OsoyooDataF",("Requested RGB Values:"));
  client.publish("OsoyooDataF","Mapped RGB Values based on type (COMMON_ANODE or COMMON_CATHODE):");
//  client.publish("OsoyooDataF",("Mapped(r,g,b)=(" + String(rgbLed.redMappedValue) + "," + String(rgbLed.greenMappedValue) + "," + String(rgbLed.blueMappedValue) + ")"));
  client.publish("OsoyooDataF",("------------------------------"));
}

Last edited by Gdipstick on Sun Jan 07, 2018 8:08 pm, edited 1 time in total.
User avatar
By schufti
#72947 It is just a shot in the dark after quick look without lengthy diagnosis and not familiar with MQTT

try for line #136
Code: Select allclient.publish("OsoyooDataF",String(buttonPushCounter));

instead of
Code: Select allclient.publish("OsoyooDataF",(buttonPushCounter));
User avatar
By Gdipstick
#72951 no joy... although, i think you are on to something... I'll keep noodling on it, and post the original sketch in a follow up sketch, i copy and pasted from, i don't think it's an MQTTBox problem because i get the error , at the verify step in arduino ide... before i can even upload, and the messages i send to MQTTBox are correct, just the variable line of code that seems to be the problem, hence i commented it out to get the experiment to work...

Arduino: 1.8.2 (Windows 7), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

C:\Users\GADAWE\Documents\Arduino\node_ct_rgb_box\node_ct_rgb_box.ino: In function 'void loop()':

node_ct_rgb_box:136: error: no matching function for call to 'PubSubClient::publish(const char [12], String)'

client.publish("OsoyooDataF",String(buttonPushCounter));

^

C:\Users\GADAWE\Documents\Arduino\node_ct_rgb_box\node_ct_rgb_box.ino:136:61: note: candidates are:

In file included from C:\Users\GADAWE\Documents\Arduino\node_ct_rgb_box\node_ct_rgb_box.ino:2:0:

C:\Program Files\arduino-1.8.2\libraries\pubsubclient\src/PubSubClient.h:130:12: note: boolean PubSubClient::publish(const char*, const char*)

boolean publish(const char* topic, const char* payload);

^

C:\Program Files\arduino-1.8.2\libraries\pubsubclient\src/PubSubClient.h:130:12: note: no known conversion for argument 2 from 'String' to 'const char*'

C:\Program Files\arduino-1.8.2\libraries\pubsubclient\src/PubSubClient.h:131:12: note: boolean PubSubClient::publish(const char*, const char*, boolean)

boolean publish(const char* topic, const char* payload, boolean retained);

^

C:\Program Files\arduino-1.8.2\libraries\pubsubclient\src/PubSubClient.h:131:12: note: candidate expects 3 arguments, 2 provided

C:\Program Files\arduino-1.8.2\libraries\pubsubclient\src/PubSubClient.h:132:12: note: boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int)

boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);

^

C:\Program Files\arduino-1.8.2\libraries\pubsubclient\src/PubSubClient.h:132:12: note: candidate expects 3 arguments, 2 provided

C:\Program Files\arduino-1.8.2\libraries\pubsubclient\src/PubSubClient.h:133:12: note: boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int, boolean)

boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);

^

C:\Program Files\arduino-1.8.2\libraries\pubsubclient\src/PubSubClient.h:133:12: note: candidate expects 4 arguments, 2 provided

exit status 1
no matching function for call to 'PubSubClient::publish(const char [12], String)'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
User avatar
By Gdipstick
#72952 here's the original sketch i downloaded from osoyoo [where i purchased my starter kit] and mortified for my experiment.....

/* ___ ___ ___ _ _ ___ ___ ____ ___ ____
* / _ \ /___)/ _ \| | | |/ _ \ / _ \ / ___) _ \| \
*| |_| |___ | |_| | |_| | |_| | |_| ( (__| |_| | | | |
* \___/(___/ \___/ \__ |\___/ \___(_)____)___/|_|_|_|
* (____/
* Use the NodeMCU send switch button status to MQTT client via WiFi
* Tutorial URL:
* CopyRight www.osoyoo.com
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

int BUTTON_PIN = D2; //button is connected to GPIO pin D1
// Update these with values suitable for your network.
const char* ssid = "********";//put your wifi ssid here
const char* password = "********";//put your wifi password here.
const char* mqtt_server = "broker.mqttdashboard.com";
//const char* mqtt_server = "iot.eclipse.org";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];

void setup_wifi() {
delay(100);
// We start by connecting to a WiFi network
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)
{

} //end callback

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 you MQTT broker has clientID,username and password
//please change following line to if (client.connect(clientId,userName,passWord))
if (client.connect(clientId.c_str()))
{
Serial.println("connected");
//once connected to MQTT broker, subscribe command if any
client.subscribe("OsoyooCommand");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
} //end reconnect()

void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
pinMode(BUTTON_PIN,INPUT);
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
int status;
//send message every 2 second
if (now - lastMsg > 2000) {
lastMsg = now;
status=digitalRead(BUTTON_PIN);
String msg="Button status: ";
if(status==HIGH )
{
msg= msg+ "Pressed";
char message[58];
msg.toCharArray(message,58);
Serial.println(message);
//publish sensor data to MQTT broker
client.publish("OsoyooData", message);
}
else
{
msg= msg+ " Not Press";
char message[58];
msg.toCharArray(message,58);
Serial.println(message);
//publish sensor data to MQTT broker
client.publish("OsoyooData", message);
}
}

}