Go Down

Topic: Having an ESP8266 successfully communicate (Read 96 times) previous topic - next topic

My main question is if I put my computer's IP address for "mqtt_server":

Code: [Select]
/*
ESP8266 Code
 
 Function: Read voltage from ADC, convert, and publish to Mosca MQTT server in Node-Red

 ESP8266 12E Pin Mapping Information:

 static const uint8_t D0   = 16;
 static const uint8_t D1   = 5;
 static const uint8_t D2   = 4;
 static const uint8_t D3   = 0;
 static const uint8_t D4   = 2;
 static const uint8_t D5   = 14;
 static const uint8_t D6   = 12;
 static const uint8_t D7   = 13;
 static const uint8_t D8   = 15;
 static const uint8_t D9   = 3;
 static const uint8_t D10  = 1;
*/

//Include libraries for WiFi and MQTT communication:
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Wi-Fi Settings:

const char* ssid = "Labwifi"; //Wireless network name (SSID)
const char* password = "wieghtsensor"; //WiFi network password (WPA2)

//Server Information:
// 137.104.151.229 - local
// 192.168.43.9
const char* mqtt_server = "137.104.151.229"; //MQTT broker IP. If this is running locally on your computer, use the command "ipconfig" in the Windows command line to find your computer's IP address. Your computer MUST be connected to the same WiFi network as the ESP8266 if Node-Red is running locally
const int mqtt_port = 1883; //This should be set to 1883
const char* input_topic = "MQTTtoboard"; //Node-Red MQTT topics. This must match the topic in the Mosca MQTT broker running in Node-Red.
const char* output_topic = "sensors";

//Constants:
unsigned long lastConnectionTime = 0;
const int postingInterval = 5 * 1000; //Time interval for publishing (in milliseconds)
const float adc_to_v_factor = 3.3/1024; //Volts/ADC sample points
const float adc_to_v_offset = -0.06; //Offset to get voltage value closer to real value. This can be changed.

//Measurement information:
const char* measurement_unit = "Voltage (V)"; //Name and units of what you are measurement with your sensor (for outputting to the serial console)
float hi_thres = 1.0; //Default high threshold until new value is received from MQTT server
float lo_thres = 0.5; //Default low threshold until new value is received from MQTT server

//ADC pin information:
const int analogIn  = A0; //Pin A0 is an analog in pin. Capable of reading voltages from 0V to 3.3V.
float readingIn = 0; //Initialize readingIn value to zero

WiFiClient client; //Initialize WiFi client
PubSubClient mqttClient(client); //Initialize the PuBSubClient library.

//=====FUNCTIONS:=====

//FUNCTION: Switch LEDs on/off based on threshold values set by user
void thresholdCheck(float x)
{
  //Turn pins D0 and D1 on/off based on Project 3 requirements:
  if(x < lo_thres)        { digitalWrite(D0, HIGH); digitalWrite(D1, HIGH); }
  else if (x > hi_thres)  { digitalWrite(D0, HIGH); digitalWrite(D1, LOW); }
  else                    { digitalWrite(D0, LOW); digitalWrite(D1, LOW); }
}

//FUNCTION: MQTT client-server reconnect
void reconnect()
{
  while (!mqttClient.connected())
  {
    Serial.print("Attempting NR MQTT connection...");
    if (mqttClient.connect("ESP8266Client")) //Attempt MQTT connection
    {
      Serial.println("Connected!");
    }
    else
    {
      Serial.print("Failed! rc="); // Print to know why the connection failed.
      // See http://pubsubclient.knolleary.net/api.html#state for the failure code explanation.
      Serial.print(mqttClient.state());
      Serial.println(" try again in 5 seconds.");
      delay(5000);
    }
  }
}

//FUNCTION: Publish measurement to MQTT server
void mqttPublish(float readingIn) {

  //Convert readingIn from float to char array. Might cause a buffer overflow
  char buf[25];
  sprintf(buf, "%f", readingIn);

  //Publish to MQTT server
  if(mqttClient.publish(output_topic, buf ) )
  {
    Serial.println("Publishing to MQTT server... DONE! ");
    Serial.print(">> Topic: ");
    Serial.println(output_topic);
    Serial.print(">> Payload: ");
    Serial.println(buf);
  }
  
  lastConnectionTime = millis(); //Update last connection time
}

//FUNCTION: Sample voltage and return value measured in volts
float getVoltageReading()
{
  return (adc_to_v_factor*analogRead(analogIn) + adc_to_v_offset); // offset
}

//FUNCTION: Convert voltage sample to your measurement value. This function will vary depending on the sensor.
float convertVoltage(float readingIn)
{
  float measurement = readingIn; //Edit this line to convert your measured voltage to your measurement value
  return measurement;
}

//FUNCTION: MQTT message callback function. Handles what needs to be done if a MQTT message is received. This function can be edited as needed but its arguments MUST NOT be changed. The payload is formatted as a byte array (byte*).
void callback(char* topic, byte* payload, unsigned int length)
{
  //Inform user MQTT message received by printing to serial console
  Serial.println("Reading from MQTT server... DONE!");
  Serial.print(">> Topic: ");
  Serial.println(topic);

  char pl[length];
  String numone, numtwo;
  int firstnum, secondnum;
  
  //Convert the incoming MQTT message from Node-Red (in the format AAA;BBB, where AAA and BBB are numbers of an unknown length) to two value that can be used to set the high and low thresholds:
  //There is most likely a better way to do this:
  for (int i=0;i<length;i++)
  {  
    pl[i] = (char)payload[i];
  }
  for(int j=0; j< length; j++)
  {
    if(pl[j] == ';')
    {
      firstnum = j;
    }
  }
  secondnum = length - firstnum;
  for(int k=0; k<firstnum; k++)
  {
    numone+=pl[k];
  }
  for(int l = firstnum + 1; l < length; l++)
  {
    numtwo += pl[l];
  }
  
  lo_thres = numone.toFloat(); //Update low threshold for LEDs
  hi_thres = numtwo.toFloat(); //Update high threshold for LEDs

  //Print MQTT message information
  Serial.print(">> Payload: ");
  Serial.println(pl);

  //Print new threshold values
  Serial.println("Threshold values updated:");
  Serial.print(">> High threshold updated to: ");
  Serial.println(hi_thres);
  Serial.print(">> Low threshold updated to: ");
  Serial.println(lo_thres);
}

//=====SETUP:=====
void setup() {
  mqttClient.setServer(mqtt_server, mqtt_port); // Set the MQTT broker details for the MQTT server connection
  mqttClient.setCallback(callback); //Set callback function for handling incoming MQTT messages from MQTT server
  
  Serial.begin(9600); //Set baud rate for serial monitor
  WiFi.begin(ssid, password); //Connect to WiFi
  
  //Set digital pins as outputs for LEDs:
  pinMode(D0, OUTPUT);
  pinMode(D1, OUTPUT);
  
  //Loop if WiFi is not connected and print out voltage reading (for debug purposes):
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500); //Delay half second
    thresholdCheck(getVoltageReading()); //Get voltage
    
    //Print error message and voltage reading to serial monitor (for debug purposes):
    Serial.println("Error: Not connected to Wifi!");
    Serial.print("ADC Pin Voltage Reading: ");
    Serial.println(readingIn);
  }
  
  //Print IP address of board:
  Serial.print("ESP8266 is connected to ");
  Serial.println(ssid);
  Serial.print("ESP8266 has the IP address: ");
  Serial.println(WiFi.localIP());
}

//=====LOOP:=====
void loop() {
  delay(postingInterval/2); //Delay for time specified by postingInterval divided by 2
  
  float measurement = convertVoltage(getVoltageReading()); //Get voltage and convert to the unit being measured
  thresholdCheck(measurement); //Check that it falls within the user set threshold values

  //Print measurment:
  Serial.print(">> Voltage Reading: ");
  Serial.print(measurement_unit);
  Serial.print(": ");
  Serial.println(measurement);

  if(!mqttClient.connected())
  {
    reconnect(); //Connect to MQTT server if not connected
    mqttClient.subscribe(input_topic); //Subsrcibe to the MQTT topic passed in as argument. Checks for new MQTT posts
  }
  
  mqttClient.loop(); //Call the loop continuously to establish connection to the server.
  
  // If interval time has passed since the last connection, publish data
  if (millis() - lastConnectionTime > postingInterval)
  {
    mqttPublish(measurement);
  }
  
  delay(postingInterval/2); //Delay for time specified by postingInterval divided by 2
  mqttClient.loop(); //Call the loop continuously to establish connection to the server.
}

I connected 0.73 V to the analog input.

Here is the serial monitor:

Code: [Select]
Error: Not connected to Wifi!
ADC Pin Voltage Reading: 0.00
Error: Not connected to Wifi!
ADC Pin Voltage Reading: 0.00
Error: Not connected to Wifi!
ADC Pin Voltage Reading: 0.00
ESP8266 is connected to Labwifi
ESP8266 has the IP address: 192.168.43.9
>> Voltage Reading: Voltage (V): 0.73
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.
Attempting NR MQTT connection...Failed! rc=-2 try again in 5 seconds.

Juraj

137.104.151.229
doesn't look like a local IP

Go Up