#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <math.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
// HC-SR04
#define TRIG_PIN 5
#define ECHO_PIN 18
// Inventory settings
#define MAX_STOCK 10
const float FULL_DISTANCE = 5.0;
const float EMPTY_DISTANCE = 30.0;
float getDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 30000);
if (duration == 0) {
return -1;
}
return duration * 0.0343 / 2;
}
int calculateStock(float distance) {
// Sensor error
if (distance < 0) {
return -1;
}
// If distance is smaller than our full-stock distance
if (distance <= FULL_DISTANCE) {
return MAX_STOCK;
}
// If distance is larger than our empty distance
if (distance >= EMPTY_DISTANCE) {
return 0;
}
// Convert distance to stock percentage
float percentage =
(EMPTY_DISTANCE - distance) /
(EMPTY_DISTANCE - FULL_DISTANCE);
// Convert percentage to number of products
int stock = round(percentage * MAX_STOCK);
return stock;
}
void setup() {
Serial.begin(115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("SMART INVENTORY");
delay(2000);
lcd.clear();
}
void loop() {
float distance = getDistance();
int stock = calculateStock(distance);
// Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.print(" cm");
Serial.print(" | Stock: ");
Serial.println(stock);
// LCD
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("STOCK: ");
if (stock < 0) {
lcd.print("ERROR");
}
else {
lcd.print(stock);
lcd.print("/");
lcd.print(MAX_STOCK);
}
lcd.setCursor(0, 1);
if (stock < 0) {
lcd.print("Sensor Error");
}
else if (stock == 0) {
lcd.print("OUT OF STOCK!");
}
else if (stock <= 2) {
lcd.print("LOW STOCK!");
}
else {
lcd.print("STOCK OK");
}
delay(1000);
}