Relay with lm35 and Nodemcu not working

Hello everyone I am currently working on a project which uses LM35 to get temperature values and if it falls below a certain value it will turn on a LED bulb using a relay however the relay does not work if someone can please help me I would appreciate
the code is :

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DallasTemperature.h>
#include <OneWire.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "The Everly"; // Enter your WiFi name
const char* password = ""; // Enter WiFi password
const char* mqttServer = "192.168.16.12";
const int mqttPort = 1883;
const char* mqttUser = "iotadmin123";
const char* mqttPassword = "XR5nsgs0cSqy3vRfgdrKLm";
const int relay = D3;

WiFiClient espClient;
PubSubClient client(espClient);

#define ONE_WIRE_BUS D2 //D2 pin of nodemcu
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire); // Pass the oneWire reference to Dallas Temperature.

unsigned long currentMillis = 0;
unsigned long previous_display = 0;
unsigned long previous_mysql = 0;
unsigned long previous_reconnect = 0;

const int event_display = 3000;
const int event_mysql = 60010;
const int event_reconnect = 30020;

void setup() {

Serial.begin(115200);

WiFi.begin(ssid, password);
sensors.begin();
pinMode(relay, OUTPUT);

while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");

client.setServer(mqttServer, mqttPort);
client.setCallback(callback);

while (!client.connected()) {
Serial.println("Connecting to MQTT...");

if (client.connect("bakery_freezer", mqttUser, mqttPassword )) {
  Serial.println("connected");  
} else {
  Serial.print("failed with state ");
  Serial.print(client.state());
  delay(2000);

}

}
}

void callback(char* topic, byte* payload, unsigned int length) {

Serial.print("Message arrived in topic: ");
Serial.println(topic);

Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}

Serial.println();
Serial.println("-----------------------");

}

void loop() {
currentMillis = millis();

if (!client.connected()) {
reconnect();
} else {
client.loop();
}

if (currentMillis - previous_display >= event_display){
sensors.requestTemperatures(); // Send the command to get temperatures
float temperature = (sensors.getTempCByIndex(0)); // Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
char tempString[8];
dtostrf(temperature, 6, 2, tempString);
Serial.print("Temperature: ");
Serial.print(tempString);
Serial.println("°C");

client.publish("freezer4/bakery_freezer", tempString );

float temp = sensors.getTempCByIndex(0);
if (temp > -13){
digitalWrite(relay, LOW); // ON LED
client.publish("ledon/bakery_freezer", "Danger Temperature -13" );
}
else{
digitalWrite(relay, HIGH); // Off LED
client.publish("ledon/bakery_freezer", "Normal Temperature" );

  }       
previous_display = currentMillis ;

if (currentMillis - previous_mysql >= event_mysql ){
//WiFiClient client;
WiFiClient Client ;
HTTPClient http;
String tempr, postData;
tempr = tempString;

postData = "&tempr=" + tempr ;

http.begin(Client, "http://192.168.16.12/build/freezer_monitoring/bakery_freezer.php"); //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header

int httpCode = http.POST(postData); //Send the request
String payload = http.getString(); //Get the response payload

Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
http.end(); //Close connection
previous_mysql = currentMillis ;
}
}
}

void reconnect() {
// Loop until we're reconnected
if (currentMillis - previous_reconnect >= event_reconnect) {
if (client.connect("bakery_freezer", mqttUser, mqttPassword)) {
Serial.println("Connected");
} else {
Serial.print("Connection failed, rc=");
Serial.print(client.state());
Serial.println("Reconnecting...");
}
previous_reconnect = currentMillis;
}
}

Can you post your code inside tags so it's easier to read.

this is the code for relay which is not working the rest is working fine its uploading to the server and getting information from the lm 35 sensor

I mean post your full code.. but inside the </> tags. Click that button in the edit window... then post your code.

The easier you make it to read and copy your code the more likely it is that you will get help

Please follow the advice given in the link below when posting code , use code tags and post the code here

If you get errors when compiling please copy them from the IDE using the "Copy error messages" button and paste the clipboard here in code tags

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DallasTemperature.h>
#include <OneWire.h>
#include <WiFiClient.h> 
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "The Everly"; // Enter your WiFi name
const char* password =  ""; // Enter WiFi password
const char* mqttServer = "192.168.16.12";
const int mqttPort = 1883;
const char* mqttUser = "iotadmin";
const char* mqttPassword = "XR5nsgs0cSqy3vR";
const int relay = D3;
WiFiClient espClient;
PubSubClient client(espClient);

#define ONE_WIRE_BUS D2                          //D2 pin of nodemcu
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);            // Pass the oneWire reference to Dallas Temperature.
unsigned long currentMillis = 0; 
unsigned long previous_display = 0;
unsigned long previous_mysql = 0;
unsigned long previous_reconnect = 0;

const int event_display = 3000;
const int  event_mysql = 60010;
const int  event_reconnect = 30020;
void setup() {
 
  Serial.begin(115200);
  
  WiFi.begin(ssid, password);
  sensors.begin();
   pinMode(relay, OUTPUT);

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("bakery_freezer", mqttUser, mqttPassword )) {
      Serial.println("connected");  
    } else {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
 
    }
  }
}
 
void callback(char* topic, byte* payload, unsigned int length) {
 
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
 
  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
 
  Serial.println();
  Serial.println("-----------------------");
 
}
void loop() {
   currentMillis = millis();
   
  if (!client.connected()) {
    reconnect();
  } else {
  client.loop();
  }
 
if (currentMillis - previous_display >= event_display){
  sensors.requestTemperatures();                // Send the command to get temperatures  
  float temperature = (sensors.getTempCByIndex(0));   // Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
  char tempString[8];
    dtostrf(temperature, 6, 2, tempString);
   Serial.print("Temperature: ");
    Serial.print(tempString);
            Serial.println("°C");

    client.publish("freezer4/bakery_freezer", tempString );
 
 float temp = sensors.getTempCByIndex(0);
  if (temp > -13){
            digitalWrite(relay, LOW); // ON LED
            client.publish("ledon/bakery_freezer", "Danger Temperature -13" );
            }
    else{
          digitalWrite(relay, HIGH); // Off LED
         client.publish("ledon/bakery_freezer", "Normal Temperature" );  
 
      }       
    previous_display = currentMillis ;
if (currentMillis - previous_mysql >= event_mysql ){
  //WiFiClient client;
WiFiClient Client ;
HTTPClient http;
String tempr, postData;
tempr = tempString;
  
postData =  "&tempr=" + tempr ;

http.begin(Client, "http://192.168.16.12/build/freezer_monitoring/bakery_freezer.php");             //Specify request destination
http.addHeader("Content-Type", "application/x-www-form-urlencoded");    //Specify content-type header

  int httpCode = http.POST(postData);   //Send the request
  String payload = http.getString();    //Get the response payload

  Serial.println(httpCode);   //Print HTTP return code
  Serial.println(payload);    //Print request response payload
  http.end();  //Close connection
  previous_mysql = currentMillis ;
}    
}
 }
 
void reconnect() {
  // Loop until we're reconnected
  if (currentMillis - previous_reconnect >= event_reconnect) {
     if (client.connect("bakery_freezer", mqttUser, mqttPassword)) {
      Serial.println("Connected");
    } else {
      Serial.print("Connection failed, rc=");
      Serial.print(client.state());
      Serial.println("Reconnecting...");
    }
    previous_reconnect = currentMillis;
  }
}

Better.. although if you can post in a single block then it is easier to copy. A lot of people will copy your code to the editor so they can better understand what is going on. Anyway...

Re this code...

    if (temp > -13) 
    {
      digitalWrite(relay, LOW); // ON LED
      client.publish("ledon/bakery_freezer", "Danger Temperature -13" );
    }
    else 
    {
      digitalWrite(relay, HIGH); // Off LED
      client.publish("ledon/bakery_freezer", "Normal Temperature" );

    }

Do the client.publish commands work?

When you say the relay doesn't work, what do you mean exactly?

Can you post a picture of how the relay is connected to the ESP8266.

yes the client publish is working and sorry i dont have a photo of the relay since its installed in my work place and its connected to Common and NO port, and the relay doesnt do anything i dont hear the clicks i double checked the connectionns and replaced the wires just to be sure

Not hearing the clicks could be power related.
For that we would request a schematic at the very least (even hand drawn).

Most Node MCU's operate in the 3.3 volt range so a relay would often need its own power supply depending on the type of relay being used ?

A LINK to the relay that you purchased may also help ?

Yep.. what @Ballscrewbob said... a picture of how it is connected, and a link to the type of relay would be useful.

You should be able to test the relay in isolation. Just connect power, and set the input HIGH/LOW directly. It could well be a logic level issue. (3.3v vs 5v)

@waleedish, your topic has been moved to a more suitable location on the forum. Installation and Troubleshooting is not for problems with (nor for advise on) your project :wink: See About the Installation & Troubleshooting category.

Hi @waleedish.
There's something weird about your project.

You said:
"I am currently working on a project which uses LM35 to get temperature values",

but it doesn't use the analog port of Nodemcu and uses two libraries for onewire sensors.
#include <DallasTemperature.h>
#include <OneWire.h>

The onenewire libraries are not for the LM35.

They are for onewire devices that include DS18B20 and DS18S20 type thermometers.

ref: https://www.ti.com/lit/ds/symlink/lm35.pdf
RV mineirin

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.