My first Blynk Project with HX711 & NodeMCU

Sure …let me go through then in some more detail. Actually the Arduino sketch w/o Blynk is working perfectly. (Even now when I comment out the Blynk commands, it works without a hitch.) Thought it will be intuitive and easy to hook it up with Blynk, but it seems there are nuances which i am missing. Will revert. Thanks.

Ok…so did some exploration and reading up but unfortunately without success. Here’s the sketch as advised.

#define BLYNK_TEMPLATE_ID "TMPLg_vAXLvt"
#define BLYNK_DEVICE_NAME "IOT WEIGH SCALE PROJECT"
#define BLYNK_FIRMWARE_VERSION        "0.1.0"
#define USE_NODE_MCU_BOARD

#define BLYNK_PRINT Serial

#define APP_DEBUG

#include "BlynkEdgent.h"

BlynkTimer timer;

#include "HX711.h"


#define DOUT  D2
#define CLK  D1
 
HX711 scale(DOUT, CLK);
 
float weight;
float calibration_factor = -104625; //-104625 worked for my 40Kg max scale setup 
long zero_factor;


void setup() 
{
  Serial.begin(115200);
  delay(1000);
  BlynkEdgent.begin();
  timer.setInterval(1000L, weightDataSend); // check if Blynk server is connected every 1 second
  scale.set_scale();
  scale.tare(); //Reset the scale to 0
  zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
}
 

void weightDataSend()
{
  weight = scale.get_units();
  Blynk.virtualWrite(V3, weight);  // sending weight value to Blynk app

  Serial.print("Weight: ");
  Serial.print(weight);
  Serial.println(" KG");
  Serial.println();

  
  }



void loop() 
{

  BlynkEdgent.run();
  timer.run();


}


And here’s the serial monitor output:

Zero factor: -31898
[3935] AP SSID: Blynk IOT WEIGH SCALE PROJECT-76D49
[3935] AP IP:   192.168.4.1
[3936] AP URL:  blynk.setup

The sketch that gives a perfect serial monitor output is as under:



#define BLYNK_TEMPLATE_ID "TMPLg_vAXLvt"
#define BLYNK_DEVICE_NAME "IOT WEIGH SCALE PROJECT"
#define BLYNK_FIRMWARE_VERSION        "0.1.0"
#define USE_NODE_MCU_BOARD

#define BLYNK_PRINT Serial

#define APP_DEBUG

#include "BlynkEdgent.h"

BlynkTimer timer;

#include "HX711.h"


#define DOUT  D2
#define CLK  D1
 
HX711 scale(DOUT, CLK);
 
float weight;
float calibration_factor = -104625; //-104625 worked for my 40Kg max scale setup 
long zero_factor;


void setup() 
{
  Serial.begin(115200);
  delay(1000);
BlynkEdgent.begin();
//timer.setInterval(1000L, weightDataSend); // check if Blynk server is connected every 1 second
  scale.set_scale();
  scale.tare(); //Reset the scale to 0
  zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
}
 


void loop() 
{

//BlynkEdgent.run();
timer.run();

Blynk.virtualWrite(V3, weight);  // sending weight value to Blynk app

  weight = scale.get_units(5);
  Serial.print("Weight: ");
  Serial.print(weight);
  Serial.println(" KG");
  Serial.println();

}

which gives a perfect output in the serial monitor:

Weight: 0.00 KG

Weight: -0.00 KG

Weight: -0.00 KG

Weight: -0.01 KG

Weight: -0.02 KG

Weight: -0.02 KG

Weight: -0.01 KG

Weight: 0.00 KG

Weight: 0.23 KG

Weight: 0.56 KG

Weight: 0.62 KG

Weight: 0.63 KG

Weight: 0.64 KG

Weight: 0.64 KG

Weight: 0.64 KG

Am almost at my wits end and on the verge of quitting this project :frowning:

Neither of these serial outputs is ‘perfect’, as they show no information about your device connecting to Blynk, which is the first thing you should be seeing.

I previously asked you…

which appears to be another of the things that I’ve previously written which you’ve decided to ignore.

Pete.

@Somu when you have a NodeMCU running the Edgent sketch and you’ve correctly provisioned that device, you should see this when you connect it to the serial monitor and hit the RST button on the device…

>[386] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v1.0.1 on ESP8266

[388] --------------------------
[391] Product:  REDACTED
[393] Firmware: 0.1.0 (build Apr 20 2022 13:42:36)
[398] Token:    ...bGJ7
[400] Device:   ESP8266 @ 80MHz
[403] MAC:      30:83:98:AE:46:5E
[406] Flash:    16384K
[408] ESP core: 3.0.2
[410] ESP SDK:  2.2.2-dev(38a443e)
[413] Boot Ver: 31
[415] Boot Mode:1
[416] FW info:  468320/1626112, MD5:11dadcb61b737a3f738ba622af04f19a
[624] Free mem: 31000
[624] --------------------------
[624] INIT => CONNECTING_NET
[625] Connecting to WiFi: REDACTED
[4768] Using Dynamic IP: 192.168.1.20
[4768] CONNECTING_NET => CONNECTING_CLOUD
[4880] Current time: Wed Apr 20 12:44:33 2022
[4880] Connecting to blynk.cloud:443
[5788] Ready (ping: 11ms).
[5867] CONNECTING_CLOUD => RUNNING

I’d suggest that you start with the Edgent ESP8266 example, add your BLYNK_TEMPLATE_ID and BLYNK_DEVICE_NAME from the template in the web console, un-comment the #define USE_NODE_MCU_BOARD then upload the sketch to your board with no other changes.

You can then open the app and hit the “+ Add Device” button and go through the provisioning process and get your device connected to Blynk.
Do reboot of the device with the RST button and ensure that you see the same serial output as I’ve posted above, and check that the device shows as online in the app and web console.

Once you have this completed, you can then add-in the additional code that relates to the BlynkTimer and HX711 to the sketch and re-upload it. You won’t need to re-provision that particular board again, provided you upload with the Tools > Erase Flash option set to “Only Sketch”.

Pete.

Hi Pete

My apologies for the late reply. Have been doing some reading and was trying out some options. Alright, got the project to run successfully and its updating both the web and mobile dashboard. However the option of connecting over the air w/o using the user id and password didn’t work. Couldn’t set up the device on the mobile for some reason. Had to do the old fashion way w/o using the edgent functionality. Here’s the sketch for reference. Next I will try to put the the nodemcu to deep sleep and see if i can run this weigh scale off a battery. Many thanks for all the help and suggestions.

/*************************************************************

  This is a simple demo of sending and receiving some data.
  Be sure to check out other examples!
 *************************************************************/

// Template ID, Device Name and Auth Token are provided by the Blynk.Cloud
// See the Device Info tab, or Template settings
#define BLYNK_TEMPLATE_ID "Hidden"
#define BLYNK_DEVICE_NAME "Hidden"
#define BLYNK_AUTH_TOKEN "Hidden"


// Comment this out to disable prints and save space
#define BLYNK_PRINT Serial


#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include "HX711.h"


char auth[] = BLYNK_AUTH_TOKEN;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Hidden";
char pass[] = "Hidden";

const char* host = "Hidden";

BlynkTimer timer;

HX711 scale;
// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 4;
const int LOADCELL_SCK_PIN = 5;

//define the parameters for the IFTTT

#define HOSTIFTTT "Hidden"
#define EVENTO "Hidden"
#define IFTTTKEY "Hidden"

WiFiClient client;

boolean alreadyRun = false; 
int upperLimit = 2; 
float calibration_factor = -104625; 
float weight;



void setup()
{
  // Debug console
  Serial.begin(115200);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk.cloud", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);

   
  Serial.println("Initializing the scale");
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
  scale.set_scale();
  scale.tare(); //Reset the scale to 0
  long zero_factor = scale.read_average(); //Get a baseline reading
  
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  Serial.println("Readings:"); 

  timer.setInterval(1000L, sensorDataSend); //timer will run every sec 
}

void loop()
{
  Blynk.run();
  timer.run();
  // You can inject your own code or combine it with other sketches.
  // Check other examples on how to communicate with Blynk. Remember
  // to avoid delay() function!
}

void sensorDataSend()
{
  Serial.print("The weight in kg is:\t");
  weight = (scale.get_units(5));   // Assign Weight to reading
  Serial.println(weight);

  Blynk.virtualWrite(V3, weight);  // sending weight value to Blynk app

  if(weight > upperLimit && alreadyRun == false)
  {
    sendSMS();
    alreadyRun = true;
  }
  
  else 
  {
   Serial.println("Still running loop()");
   delay(1000);
        
   if(weight < upperLimit && alreadyRun == true)
   {
    alreadyRun = false;
   } 
  }

}

void sendSMS() {
    Serial.println("Initiating to send SMS");
    WiFi.begin(ssid, pass);
    Serial.println(" ");
    Serial.print("Waiting to connect to WiFi....");
    while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(".");
    }
    Serial.print("");
    Serial.print("Connected to ");
    Serial.print(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    delay(1000);
   
    if (client.connected())
    {
      client.stop();
    }

    client.flush();
    if (client.connect(host,80)) 
    {
    Serial.println("Connected");
    // build the HTTP request
    String toSend = "GET /trigger/";
    toSend += EVENTO;
    toSend += "/with/key/";
    toSend += IFTTTKEY;
    toSend += "?value1=";
    toSend += weight;
    toSend += " HTTP/1.1\r\n";
    toSend += "Host: ";
    toSend += HOSTIFTTT;
    toSend += "\r\n";
    toSend += "Connection: close\r\n\r\n";
    client.print(toSend);
    delay(1000);
  
    Serial.print("SMS Sent");
    delay(1000);
    }
  
    client.flush();
    client.stop();  
 
  }







And here’s the output:


6798] Connected to WiFi
[6798] IP: 192.168.0.115
[6798] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v1.0.1 on ESP8266

[6804] Connecting to blynk.cloud:80
[6980] Ready (ping: 56ms).
Initializing the scale
Readings:
The weight in kg is:	0.00
Still running loop()
The weight in kg is:	0.00
Still running loop()
The weight in kg is:	0.00
Still running loop()
The weight in kg is:	0.00
Still running loop()
The weight in kg is:	-0.00
Still running loop()
The weight in kg is:	-0.00
Still running loop()
The weight in kg is:	-0.00
Still running loop()
The weight in kg is:	-0.00
Still running loop()
The weight in kg is:	0.00
Still running loop()
The weight in kg is:	0.00
Still running loop()

You might want to edit your last post to remove your credentials.

If you’re not going to use dynamic provisioning of WiFi credentials and auth token then there is little point in using the Edgent sketch. Edgent does give you Blynk.Air OTA updates, but this won’t work if you use deep sleep anyway.

If you’d have mentioned your desire to use deep sleep earlier then I would have pointed you towards this topic, as it would have been a much better starting point for that type of project (you need to read the whole topic from start to finish)…

Pete.

Thanks again. Have removed the credentials. Related to this, if I use my user ID/PWD and other credentials in the sketch directly, how secure are they ? Is there any chance of data leak or misuse?

Let me go through the post on deep sleep.

I’m not going to get in to a discussion about WiFi security or SSL versus non-SSL data security over the internet - it’s beyond the scope of this forum and is covers in lots of detail on the internet.

Pete.

Hi Pete,

Ok…so got the deep sleep mode working…had to make a slight change to my previous sketch (w/o deepsleep) as the timer.setInterval(1000L, sensorDataSend) function was not running the getSensorData function, but instead going into deep sleep mode before that. So moved the getSensorData function code into the setup() function and disabled the timer.setInterval(1000L, sensorDataSend) . Its working fine, but dont know why the timer.setInterval(1000L, sensorDataSend) function will not work. Any pointers will help for academic interest.

Also wanted to know if the following sketch can be used within the void setup () before the Blynk.begin(auth, ssid, pass) -to set the ssid and pwd externally from a webpage, say, instead of hardcoding it into the sketch. Have used a jumper to connect the RST with D0 pins for enabling deepsleep.

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>          //https://github.com/kentaylor/WiFiManager

 
void setup() {
   
  Serial.begin(115200);
  Serial.println("\n Starting");
  
 
  WiFi.printDiag(Serial); 
  Serial.println("Opening configuration portal");
     
  WiFiManager wifiManager;  
  
  if (WiFi.SSID()!="") wifiManager.setConfigPortalTimeout(60); 
 
  if (!wifiManager.startConfigPortal("ESP8266","password")) 
  {
     Serial.println("Not connected to WiFi but continuing anyway.");
  } 
  else 
  {
     Serial.println("connected to WiFi");
  }
      


My working sketch as of now…

// Template ID, Device Name and Auth Token are provided by the Blynk.Cloud
// See the Device Info tab, or Template settings
#define BLYNK_TEMPLATE_ID "Hidden"
#define BLYNK_DEVICE_NAME "Hidden"
#define BLYNK_AUTH_TOKEN "Hidden"


// Comment this out to disable prints and save space
#define BLYNK_PRINT Serial


#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include "HX711.h"


char auth[] = BLYNK_AUTH_TOKEN;

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Hidden";
char pass[] = "Hidden";
const char* host = "Hidden";

BlynkTimer timer;

HX711 scale;
// HX711 circuit wiring
const int LOADCELL_DOUT_PIN = 4;
const int LOADCELL_SCK_PIN = 5;

//define the parameters for the IFTTT

#define HOSTIFTTT "Hidden"
#define EVENTO "Hidden"
#define IFTTTKEY "Hidden"

WiFiClient client;

boolean alreadyRun = false; 
int upperLimit = 2; 
float calibration_factor = -104625; 
float weight;



void setup()
{
  // Debug console
  Serial.begin(115200);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk.cloud", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);

   
  Serial.println("Initializing the scale");
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
  scale.set_scale();
  //scale.tare(); //Reset the scale to 0
  //long zero_factor = scale.read_average(); //Get a baseline reading
  
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  Serial.println("Readings:"); 

  //timer.setInterval(1000L, sensorDataSend); //timer will run every sec 

  Serial.print("The weight in kg is:\t");
  weight = ((scale.get_units(5))-0.42);   // Assign Weight to reading
  Serial.println(weight);

  Blynk.virtualWrite(V3, weight);  // sending weight value to Blynk app

  if(weight > upperLimit && alreadyRun == false)
  {
    sendSMS();
    alreadyRun = true;
  }
  
  else 
  {
   Serial.println("Still running loop()");
   delay(1000);
        
   if(weight < upperLimit && alreadyRun == true)
   {
    alreadyRun = false;
   } 
  }


  delay(1000);
  Serial.println("Going to Sleep");
  Serial.println();
  ESP.deepSleep(100*1000000); //deep sleep for 1.65 minutes
  
}

void loop()
{
  Blynk.run();
  timer.run();
  // You can inject your own code or combine it with other sketches.
  // Check other examples on how to communicate with Blynk. Remember
  // to avoid delay() function!
}


void sendSMS() {
    Serial.println("Initiating to send SMS");
    WiFi.begin(ssid, pass);
    Serial.println(" ");
    Serial.print("Waiting to connect to WiFi....");
    while (WiFi.status() != WL_CONNECTED)
    {
    delay(500);
    Serial.print(".");
    }
    Serial.print("");
    Serial.print("Connected to ");
    Serial.print(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());
    delay(1000);
   
    if (client.connected())
    {
      client.stop();
    }

    client.flush();
    if (client.connect(host,80)) 
    {
    Serial.println("Connected");
    // build the HTTP request
    String toSend = "GET /trigger/";
    toSend += EVENTO;
    toSend += "/with/key/";
    toSend += IFTTTKEY;
    toSend += "?value1=";
    toSend += weight;
    toSend += " HTTP/1.1\r\n";
    toSend += "Host: ";
    toSend += HOSTIFTTT;
    toSend += "\r\n";
    toSend += "Connection: close\r\n\r\n";
    client.print(toSend);
    delay(1000);
  
    Serial.print("SMS Sent");
    delay(1000);
    }
  
    client.flush();
    client.stop();  
 
  }

i dont like your code structure at all.
Your void loop will never be executed, so you should probably have it empty.
Your delays are wasting battery power, and I’m extremely surprised that pin V3 is being updated at all - I doubt that this update will reliably execute each time.

The alreadyRun flag is also redundant.

If you work on 100 second sleep periods then the code will probably connect quite quickly, but if you extend that then you’ll reach a point where the WiFi connection takes quite a bit longer because the router will have flushed the routing table and the device and router will need to re-negotiate a DHCP address assignment. That’s why it’s better to hard-code the IP address, gateway, DNS etc when using deep sleep.

If you want to avoid hard-coding your WiFi credentials then you’d be better going back to the Edgent sketch as the basis for your project rather than using WiFi Manager.

Pete.

Understand. But what’s the optimal code that you will suggest. If i need deep sleep , I can’t use Edgent as you mentioned in earlier post. The delays can be taken off, if that helps in conserving battery… The void loop is really not doing anything , so I can remove the timer. Can I remove blynk.run also?

The V3 is getting updated alright. It’s running on battery for the last 6 hrs or so. Not sure if it’s by sheer serendipity that it’s working and will fail if some delays, etc are changed.

The alreadyRun is required to check if an SMS has already been sent, when the weight was more than 2 kg. If SMS was sent which actually informs me to reduce weight, don’t resend another SMS. If i took action and reduced the weight to below 2 kg, reset the Boolean to false, in which case no SMS will be sent. If after that , the weight is again increased, send another SMS. That’s the logic. How else can this be handled?

Here’s the screenshot of the app dashboard

I’ve pointed you towards the Beehive Connected project, which works well. There are other good deep sleep examples too, but you threw the deep sleep requirement in at the end of the discussion, rather than at the beginning. I’m also unclear about what else you want, whether dynamic provisioning is essential, and if so why.

Your void loop never gets executed, so yes.

You don’t seem to realise that the void setup is executed just once, at startup. As you put the device to sleep at the end of void setup, there isn’t any looping process. It takes one reading, sends the SMS if needed then goes to sleep.
When it wakes up, it reboots itself and all variables are cleared, and the process repeats. There can be no multiple SMS messages per wake-up period, and the alreadyRun variable is re-initialised when the device wakes again.

Pete.

Yes , understand that part Pete regarding the SMS. It was originally in the void loop , but put it in the void set up as deep sleep required it to be in the set up code. Can you suggest any other way of coding this? The Arduino best practice suggests that deep sleep should be in the setup code and Blynk also suggests that the void loop should be kept as clean as possible.

With regards to the requirement, i am going through a learning process and see what all can be done. I am trying to add features and experiment with this product. I intend to take reading maybe once in an hour and see how it behaves. You have already indicated that this will force a complete clean up of the routing tables, etc. Would like to see how to add tare functionality through a reset button (in the void setup part?), deep sleep, OTA updates, etc.

Wanted to thank you for all the responses and guidance. Cheers, Somu.

That doesn’t apply to deep sleep.

Yes, see the Beehive Connected topic.

Is that a button in Blynk?
If so then you’d need to process Blynk.run multiple times and use BLYNK_CONNECTED to know when the value from that button has been received by the board.

You’d need to stop the device going to sleep, then do the update, then allow sleep again. That’s potentially heavy on battery usage, and your timing for waiting until the device is awake and waiting for the update.

That could mean anything, but you don’t seem to be saying that dynamic provisioning is now a requirement?

One other issue with battery powered deep sleep devices is that if you use Blynk.begin then if the device can’t connect to WiFi or the Blynk server then it will never get to the deep sleep command, as Blynk.begin is a blocking command.
That’s why the Beehive Connected sketch used manual WiFi management and Blynk.config/Blynk.begin as this isn’t blocking.

Pete.

If by dynamic provisioning you are referring to non-hard coded wifi credentials , yes , definitely that’s what I would like to try.

By etc. I mean, things like storing the last few values, say last 1 hr, in eprom so that in case of battery dying out, it stores the last few readings and can start from there when the batteries are recharged.

I will redo the code with the beehive example and see how it turns out. Will keep you posted.

Again, many thanks.

Yes, that’s what Dynamic Provisioning means.
What’s your use-case for requiring this, as it increases the complexity by an order of magnitude, and I don’t think you have the coding skills for that.

Don’t use EEPROM, use SPIFFS OR LittleFS instead.

Life gets much easier if you work-out what your functional requirements and wishlist are to begin with, and communicate these to people who you ask for assistance. It saves you, and us, lots of wasted time.

Pete.

Ok, Pete…redid the code based on the Beehive project…had to make some major changes and reading wrt the esp32 and esp8266 libraries and commands and had to replace / remove some commands which I believe are not supported in esp8266 (for example: RTC_DATA_ATTR int bootCount = 0).

Can you check now if this looks okay now?

I still would want to:

  1. use dynamic provisioning
  2. Hopefully this should work if I want to read the weight say once every 6 or12 hrs only
  3. send SMS once only if the weight exceeds 2kg. Currently it will be sending it every time it wakes up from deep sleep and finds the weight to be more than 2kg
  4. store some of the data like the last 1 hour readings in some memory on the board as back up for battery dying.

Here’s the code:



// Template ID, Device Name and Auth Token are provided by the Blynk.Cloud
// See the Device Info tab, or Template settings
#define BLYNK_TEMPLATE_ID "Hidden"
#define BLYNK_DEVICE_NAME "Hidden "
#define BLYNK_AUTH_TOKEN "Hidden"


#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include "HX711.h"

// Comment this out to disable prints and save space
#define BLYNK_PRINT Serial

const char auth[] = BLYNK_AUTH_TOKEN;
const char blynk_server [] =   "blynk.cloud"; // new variable to hold the name of the Blynk server
const int blynk_port =         8080;              // new variable to hold the port used by the Blynk server

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "Hidden";
char pass[] = "Hidden";
const char* host = "Hidden";

int wifi_connect_count = 0;          // New variable to keep track of how manty times we've tried to connect to the Wi-Fi
int wifi_connect_max_retries = 50;   // New variable to specify how many attempts we will have at connecting to the Wi-Fi
//float sleep_time_minutes =     1;   // New variable - how long (in minutes) we sleep for. As this is a float variable then it can be 0.5 for a 30 second test

// HX711 circuit wiring
HX711 scale;
const int LOADCELL_DOUT_PIN = 4;
const int LOADCELL_SCK_PIN = 5;

//define the parameters for the IFTTT
#define HOSTIFTTT "Hidden"
#define EVENTO "Hidden"
#define IFTTTKEY "Hidden"

WiFiClient client;

int upperLimit = 2; 
float calibration_factor = -104625; 
float weight = 0;

void getWeight()
{
  Serial.println("Initializing the scale");
  scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  Serial.print("Reading: ");
  Serial.print("The weight in kg is:\t");
  weight = ((scale.get_units(10))-0.42);   // Assign Weight to reading
  Serial.println(weight);
  Serial.print("calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();
}


void WiFi_Connect() // New functon to handle the connectuon to the Wi-Fi network
{
  Serial.println("Connecting to Wi-Fi");
  if (WiFi.status() != WL_CONNECTED)
  {
      WiFi.begin(ssid, pass); // connect to the network
  }
  while (WiFi.status() != WL_CONNECTED  && wifi_connect_count < wifi_connect_max_retries) // Loop until we've connected, or reached the maximum number of attemps allowed
  {
    delay(500);
    wifi_connect_count++;   
    Serial.print("Wi-Fi connection - attempt number ");
    Serial.println(wifi_connect_count);
  }
  
  if (WiFi.status() == WL_CONNECTED)
  {
    Serial.println("Wi-Fi CONNECTED");
    Serial.println();
  }
} 



void Deep_Sleep_Now()
{
  Serial.println("Going to sleep now");
  Serial.flush(); 
  ESP.deepSleep(60* 1000000);
}


void sendSMS() {
    Serial.println("Initiating to send SMS");
    if(client.connected())
    {
      client.stop();
    }

    client.flush();
    if (client.connect(host,80)) 
    {
    Serial.println("Connected");
    // build the HTTP request
    String toSend = "GET /trigger/";
    toSend += EVENTO;
    toSend += "/with/key/";
    toSend += IFTTTKEY;
    toSend += "?value1=";
    toSend += weight;
    toSend += " HTTP/1.1\r\n";
    toSend += "Host: ";
    toSend += HOSTIFTTT;
    toSend += "\r\n";
    toSend += "Connection: close\r\n\r\n";
    client.print(toSend);
    delay(1000);
  
    Serial.println("SMS Sent");
    delay(1000);
    }
  
    client.flush();
    client.stop();  
   }



void setup()
{
  Serial.begin(115200);
  WiFi_Connect(); // Attempt to connect to Wi-Fi

  if (WiFi.status() == WL_CONNECTED)               // If we managed to connect to Wi-Fi then try to connect to Blynk, else go to sleep
  {
    Blynk.config(auth, blynk_server, blynk_port);  // Initialise the Blynk connection settings
    Blynk.connect();                               // Attempt to connect to Blynk
  }
  else
  {
    Serial.println ("Wi-Fi connection failed - going to sleep");
    Deep_Sleep_Now();
  }
  
  if (Blynk.connected())                          // If we manages to connect to Blynk then carry-on as normal, else go to sleep
  {  
    Serial.println ("Connected to Blynk");
  }
  else
  {  
    Serial.println("Blynk connection failed - going to sleep");
    Deep_Sleep_Now();
  }
   delay(2000);
 }

void loop()
{
  delay(2000);
  getWeight();
  
   if(weight > upperLimit)
  {
     Serial.println("Weight is more than 2 kg, sending SMS....");
     sendSMS();
  }
  
  else 
  {
   Serial.println("Weight is less than 2 kg, not sending SMS");
   delay(1000);
  }      
  Blynk.virtualWrite(V3, weight);
  Blynk.run(); // Needed to ensure that the Wake Time value is always uploaded to Blynk before going to sleep
  delay(100);
  Deep_Sleep_Now();
  
}  
 






I’ve already given you my thoughts on that.

Another previously unmentioned requirement. The maximum deep sleep time, when using latest versions of the ESP core, is around 3.5 hours.

That will require the use of NVR, and as I’ve said earlier you should use SPIFFS or LittleFS for this.

How are you going to do that, if the device is asleep for more than 1 hour?

Why arent you using the Blynk server for storage rather than the device memory?

As I’ve said before, the first task is to define your functional requirements. Once you have these, then they will dictate the code and code structure that needs to be used. You’re approaching the problem from the wrong direction.

Pete.