#include <LiquidCrystal.h>
// Smart Water Tank Management System
// STM32 Nucleo-C031C6
const int TRIG_PIN = 2;
const int ECHO_PIN = 3;
const int PUMP_LED = 4;
// LCD pins: RS, E, D4, D5, D6, D7
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
// Distance from sensor to water surface
const float EMPTY_DISTANCE = 100.0; // Tank empty
const float FULL_DISTANCE = 20.0; // Tank full
bool pumpOn = false;
// Update LCD with water level and pump status
void showOnLCD(float waterLevel) {
int level = (int)(waterLevel + 0.5);
// First row: water level
lcd.setCursor(0, 0);
lcd.print("Water: ");
lcd.print(level);
lcd.print("% ");
// Second row: pump state and level bar
lcd.setCursor(0, 1);
if (pumpOn) {
lcd.print("ON [");
} else {
lcd.print("OFF [");
}
// Eight blocks represent the water level
int filledBlocks = (int)((waterLevel * 8.0 / 100.0) + 0.5);
for (int i = 0; i < 8; i++) {
if (i < filledBlocks) {
lcd.write((uint8_t)255); // Filled block
} else {
lcd.print(" ");
}
}
lcd.print("] ");
}
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(PUMP_LED, OUTPUT);
digitalWrite(TRIG_PIN, LOW);
digitalWrite(PUMP_LED, LOW);
Serial.begin(115200);
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print(" SMART WATER");
lcd.setCursor(0, 1);
lcd.print(" TANK SYSTEM");
Serial.println("Smart Water Tank Management System");
Serial.println("----------------------------------");
delay(2000);
lcd.clear();
}
void loop() {
// Send ultrasonic pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read echo with timeout
unsigned long duration = pulseIn(ECHO_PIN, HIGH, 30000);
if (duration == 0) {
// Stop the pump if the sensor gives no reading
pumpOn = false;
digitalWrite(PUMP_LED, LOW);
lcd.setCursor(0, 0);
lcd.print("Sensor error ");
lcd.setCursor(0, 1);
lcd.print("Pump: OFF ");
Serial.println("Sensor reading unavailable. Pump OFF.");
delay(1000);
return;
}
// Convert echo time into distance in cm
float distance = duration / 58.0;
// Convert distance into water-level percentage
float waterLevel =
(EMPTY_DISTANCE - distance) * 100.0 /
(EMPTY_DISTANCE - FULL_DISTANCE);
if (waterLevel < 0) waterLevel = 0;
if (waterLevel > 100) waterLevel = 100;
// Pump control: ON at 20%, OFF at 80%
if (waterLevel <= 20) {
pumpOn = true;
} else if (waterLevel >= 80) {
pumpOn = false;
}
digitalWrite(PUMP_LED, pumpOn ? HIGH : LOW);
// Update the LCD
showOnLCD(waterLevel);
// Keep the existing Serial Monitor readings
Serial.print("Distance: ");
Serial.print(distance, 1);
Serial.print(" cm | Water level: ");
Serial.print(waterLevel, 0);
Serial.print("% | Pump: ");
Serial.println(pumpOn ? "ON" : "OFF");
delay(1000);
}Loading
st-nucleo-c031c6
st-nucleo-c031c6