Skip to content

Instantly share code, notes, and snippets.

@jonchen727
Created December 18, 2019 00:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonchen727/d018fc5baeff5ced3506d379d704f65d to your computer and use it in GitHub Desktop.
Save jonchen727/d018fc5baeff5ced3506d379d704f65d to your computer and use it in GitHub Desktop.
ESP MQTT Scale with OTA Update Code
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <Update.h>
#include <HX711_ADC.h>
#include <PubSubClient.h>
char msg_buff[50];
const char* host = "esp32";
const char* ssid = "yourssid";
const char* password = "yourpassword";
const char* mqtt_server = "192.168.1.117";
float calibration_factor = 115.50; //115.50 worked for my scale ;
int switchValue;
//MQTT Setup
WiFiClient esp32Client;
PubSubClient client(esp32Client);
//HX711 Constructor (dout, sck):
HX711_ADC LoadCell(19, 18);
const int eepromAdress = 0;
long t;
WebServer server(80);
/*
Login page
*/
const char* loginIndex =
"<form name='loginForm'>"
"<table width='20%' bgcolor='A09F9F' align='center'>"
"<tr>"
"<td colspan=2>"
"<center><font size=4><b>ESP32 Login Page</b></font></center>"
"<br>"
"</td>"
"<br>"
"<br>"
"</tr>"
"<td>Username:</td>"
"<td><input type='text' size=25 name='userid'><br></td>"
"</tr>"
"<br>"
"<br>"
"<tr>"
"<td>Password:</td>"
"<td><input type='Password' size=25 name='pwd'><br></td>"
"<br>"
"<br>"
"</tr>"
"<tr>"
"<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
"</tr>"
"</table>"
"</form>"
"<script>"
"function check(form)"
"{"
"if(form.userid.value=='admin' && form.pwd.value=='admin')"
"{"
"window.open('/serverIndex')"
"}"
"else"
"{"
" alert('Error Password or Username')/*displays error message*/"
"}"
"}"
"</script>";
/*
Server Index Page
*/
const char* serverIndex =
"<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
"<input type='file' name='update'>"
"<input type='submit' value='Update'>"
"</form>"
"<div id='prg'>progress: 0%</div>"
"<script>"
"$('form').submit(function(e){"
"e.preventDefault();"
"var form = $('#upload_form')[0];"
"var data = new FormData(form);"
" $.ajax({"
"url: '/update',"
"type: 'POST',"
"data: data,"
"contentType: false,"
"processData:false,"
"xhr: function() {"
"var xhr = new window.XMLHttpRequest();"
"xhr.upload.addEventListener('progress', function(evt) {"
"if (evt.lengthComputable) {"
"var per = evt.loaded / evt.total;"
"$('#prg').html('progress: ' + Math.round(per*100) + '%');"
"}"
"}, false);"
"return xhr;"
"},"
"success:function(d, s) {"
"console.log('success!')"
"},"
"error: function (a, b, c) {"
"}"
"});"
"});"
"</script>";
/*
setup function
*/
void setup() {
delay(100);
pinMode(BUILTIN_LED, OUTPUT);
pinMode(23, INPUT_PULLUP);
Serial.begin(115200);
Serial.println("HX711 Calibration");
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
scale_setup();
}
void setup_wifi() {
// Connect to WiFi network
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
/*use mdns for host name resolution*/
if (!MDNS.begin(host)) { //http://esp32.local
Serial.println("Error setting up MDNS responder!");
while (1) {
delay(1000);
}
}
Serial.println("mDNS responder started");
/*return index page which is stored in serverIndex */
server.on("/", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", loginIndex);
});
server.on("/serverIndex", HTTP_GET, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
/*handling uploading firmware file */
server.on("/update", HTTP_POST, []() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}, []() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
});
server.begin();
}
void scale_setup() {
client.subscribe("HX711cal1");
Serial.println("HX711 Calibration");
Serial.println("Remove all weight from scale");
Serial.println("After readings begin, place known weight on scale");
Serial.println("Press a,s,d,f to increase calibration factor by 10,100,1000,10000 respectively");
Serial.println("Press z,x,c,v to decrease calibration factor by 10,100,1000,10000 respectively");
Serial.println("Press t for tare");
LoadCell.begin();
long stabilisingtime = 2000; // tare preciscion can be improved by adding a few seconds of stabilising time
LoadCell.start(stabilisingtime);
if (LoadCell.getTareTimeoutFlag()) {
Serial.println("Tare timeout, check MCU>HX711 wiring and pin designations");
}
else {
LoadCell.setCalFactor(calibration_factor); // set calibration value (float)
Serial.println("Startup + tare is complete");
};
}
void callback(char* topic, byte* payload, unsigned int length) {
int i = 0;
Serial.println("Message arrived: topic: " + String(topic));
Serial.println("Length: " + String(length, DEC));
for (i = 0; i < length; i++) {
msg_buff[i] = payload[i];
}
msg_buff[i] = '\0';
String msgString = String(msg_buff);
Serial.println("Payload: " + msgString);
if (msgString == "tare") { // if there is a "1" published to any topic (#) on the broker then:
digitalWrite(BUILTIN_LED, LOW); // set pin to the opposite state
Serial.println("Switching LED");
LoadCell.tareNoDelay();
digitalWrite(BUILTIN_LED, HIGH);
}
else if (msgString == "+0.1")
calibration_factor += 0.1;
else if (msgString == "-0.1")
calibration_factor -= 0.1;
else if (msgString == "+1")
calibration_factor += 1;
else if (msgString == "-1")
calibration_factor -= 1;
else if (msgString == "+10")
calibration_factor += 10;
else if (msgString == "-10")
calibration_factor -= 10;
else if (msgString == "+100")
calibration_factor += 100;
else if (msgString == "-100")
calibration_factor -= 100;
}
void reconnect() {
while (!client.connected()) {
Serial.print("AtinByteting MQTT connection...");
if (client.connect("ESP8266Client")) {
Serial.println("connected");
client.subscribe("HX711cal1");
client.publish("IP", WiFi.localIP().toString().c_str(), true);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void loop(void) {
if (!client.connected()) {
reconnect();
}
server.handleClient();
delay(1);
client.loop();
LoadCell.update();
//get smoothed value from data set
if (millis() > t + 250) {
float i = LoadCell.getData();
Serial.print("Load_cell output val: ");
Serial.println(i);
t = millis();
LoadCell.setCalFactor(calibration_factor);
client.publish("HX711calfactor1", String(calibration_factor).c_str(), true);
client.publish("Scale2",String(i).c_str(),true);
Serial.print(" calibration_factor: ");
Serial.print(calibration_factor);
Serial.println();
}
//receive from serial terminal
if (Serial.available() > 0) {
float i;
char inByte = Serial.read();
if (inByte == 't') LoadCell.tareNoDelay();
else if (inByte == '+' || inByte == 'a')
calibration_factor += 0.1;
else if (inByte == '-' || inByte == 'z')
calibration_factor -= 0.1;
else if (inByte == 's')
calibration_factor += 1;
else if (inByte == 'x')
calibration_factor -= 1;
else if (inByte == 'd')
calibration_factor += 10;
else if (inByte == 'c')
calibration_factor -= 10;
else if (inByte == 'f')
calibration_factor += 100;
else if (inByte == 'v')
calibration_factor -= 100;
}
//check if last tare operation is complete
if (LoadCell.getTareStatus() == true) {
Serial.println("Tare complete");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment