#include <HX711.h>
char flag;
char ans;
float Gain = 1;
HX711 loadcell;
const int dout = 2;
const int sck = 4;
const long offset;
const long gain;
void setup() {
Serial.begin(115200);
loadcell.begin(dout,sck);
loadcell.set_offset();
loadcell.scale();
Serial.println("");
Serial.println("::: Force sensor :::");
Serial.println("For offset compensation, press 'o' ;");
Serial.println("For gain calibration, press 'g' ;");
Serial.println("To start and stop real-time measurement, press 's' ;");
Serial.println("::: end :::");
Serial.println("");
}
void loop() {
loadcell.set_scale();
while (Serial.available()==0) {
}
flag = Serial.read();
if(flag=='o') {
OffsetComp();
}
if(flag=='g') {
GainCalib();
}
if(flag=='s') {
StartStop();
}
delay(1); // this speeds up the simulation
}
void OffsetComp() {
Serial.println("Offset compensation - remove wire and leave every static load (pulley, bracket...)");
delay(500);
Serial.println("Press 'd' when done");
ans = 'a';
while (ans!='d') {
if (Serial.available()>0) {
ans = Serial.read();
}
}
loadcell.tare();
Serial.println("Tare done");
}
/* void GainChoice() {
Serial.println("Gain calibration...");
delay(500);
Serial.println("Do offset compensation first ?");
Serial.println("For 'yes', press 'y' ;");
Serial.println("For 'no', press 'n' ;");
while (Serial.available()==0) {
}
ans = Serial.read();
if(ans=='n') {
GainCalib();
}
if(ans=='y') {
OffsetComp();
GainCalib();
}
} */
void GainCalib() {
Serial.println("Gain calibration - add wire with weight ;");
Serial.println("When stabilized, enter the weight value in kg :");
int weight = 0;
while (weight==0) {
if (Serial.available()>0) {
weight = Serial.parseInt();
}
}
Serial.print("Weight = "); Serial.print(weight); Serial.println(" kg");
Gain = loadcell.get_units(10)/weight;
Serial.print("Gain = "); Serial.println(Gain);
Serial.println("Gain calibration done");
}
void StartStop() {
Serial.println("Reading");
delay(500);
char stop = 'a';
while(stop!='s') {
long reading = loadcell.get_units(10);
Serial.println(reading);
if (Serial.available()>0) {
stop = Serial.read();
}
}
Serial.println("Stop reading");
}