Smart Water Level Monitoring System with Motor Actuation Using PIC16F877A

Imthath Usain
18 min readFeb 11, 2024

--

INTRODUCTION

1.1 PROBLEM STATEMENT

Efficient water management is critical in the face of increasing water scarcity. Traditional methods of water level monitoring and control often lack real-time capabilities, leading to inefficiencies and potential water wastage. There is a need for an automated system that can accurately monitor water levels, activate alarms when necessary, and automate the water filling process.

1.2 OBJECTIVES

To design and implement a Water Level monitoring and Control System using the PIC16F877A microcontroller.

To utilize an ultrasonic sensor for precise water level measurements.

ü To activate alarms and indicators based on predefined water level thresholds.

ü To automate the water pump for efficient tank filling.

ü To provide a user-friendly interface through an LCD display.

1.3 SCOPE

The scope of this project encompasses the development of a comprehensive system capable of monitoring water levels in a tank and automating the water filling process. The system integrates various components such as the PIC16F877A microcontroller, ultrasonic sensor, LCD display, LEDs, buzzer, relay, and water pump.

1.4 SIGNIFICANCE OF THE PROJECT

Efficient water management: The system helps in conserving water by ensuring optimal usage and preventing overflow.

Real-time monitoring: The inclusion of an ultrasonic sensor enables precise and instantaneous water level measurements.

Automation: The automated water pump control enhances convenience and reduces the need for manual intervention.

1.5 BACKGROUND INFORMATION

Figure 1 — Visual Representation Block Diagram of the system’s architecture and the connection of each component in the water level monitoring and control functionalities.

1.5.1 Water Level Monitoring

Traditional methods involve manual observation, which is time-consuming and prone to errors. Modern systems use electronic sensors to provide accurate and real-time measurements.

1.5.2. Ultrasonic Sensor

Utilizes sound waves to measure distances accurately. Its advantages include non-contact measurement and applicability in various environments.

1.5.3 PIC Microcontroller

The PIC16F877A is a widely used microcontroller known for its versatility and ease of programming. It serves as the brain of the system, processing sensor data and controlling peripherals.

1.5.4 LCD Display

Provides a visual interface for users to monitor water levels and system status in real-time.

1.5.5 Buzzer, LED, Relay, and Motor

These components serve as indicators, alarms, and actuators in the system, enhancing user feedback and automation.

1.6 MOTIVATION

The motivation behind the water level monitoring and control system project stems from a commitment to address pressing issues related to water conservation and efficient resource management. In light of growing concerns about water scarcity, the project aims to contribute to responsible water usage by providing real-time monitoring and control capabilities. By automating the monitoring process and integrating a motor control component, the system seeks to prevent potential problems such as water overflows or shortages.

The proactive approach not only enhances the reliability of water storage systems but also promotes energy efficiency through optimized resource utilization. The selection of the PIC16F877A microcontroller further underscores the project’s commitment to leveraging versatile, low-power, and feature-rich technology for effective implementation. Ultimately, the project strives to create a solution that aligns with the principles of sustainability, conservation, and intelligent resource management.

LITERATURE SURVEY

The literature survey explores existing works related to water level monitoring systems, focusing solutions utilizing various sensors such as pressure sensors, sight gauges, float switches, and water level sensors using system. This chapter aims to compare and contrast different approaches, methodologies, and results from previous studies, identifying gaps and limitations that the current project seeks to address and improve upon.

2.1 WATER LEVEL MONITORING SYSTEMS IN MARKET

Numerous studies have explored the use of water level monitoring systems, utilizing various sensors setup for this purpose.

2.1.1 Water Level Submersible Pressure Sensor using Level Indicator

Pressure sensors are commonly used in industrial settings due to their capability to provide accurate readings. However, their application in water level measurement involves complexity.

Complexity: Measuring water level precisely through pressure sensors requires an understanding of tank geometry, liquid density, and calibration for temperature changes. Achieving accurate results demands careful consideration of these variables, making the implementation challenging, especially in dynamic environments.

Water Level Submersible Pressure Sensor. [Online] Available at: https://www.indiamart.com/proddetail/water-level-submersible-pressure-sensor-22187545888.html

‌2.1.2 Water tank glass tube level sight gauge

Sight gauges, although simple, possess limitations, particularly in certain scenarios.

Limited Visibility: Sight gauges may not be suitable for very large or opaque tanks. Their effectiveness diminishes when dealing with tanks that exceed a certain size or when the liquid being measured is not transparent. In such cases, obtaining a clear visual indication of the water level becomes challenging.

Water Tank Glass Tube Level Gauge Oil Tank Level Indicator for Hydraulic Oil/water Tank Level Gauge Sight Indicator [Online] Available at: https://www.alibaba.com/product-detail/water-tank-glass-tube-level-gauge_1600133094149.html

‌2.1.3 Float Switch — Fluid Level Controller

Float switches offer a straightforward mechanism for water level detection but come with inherent drawbacks.

Binary Output: These switches provide a binary “on/off” signal, indicating whether the water level has reached a specific point. However, this binary nature limits their utility for continuous or precise measurement of the water level. Determining the exact level of water in the tank becomes challenging, especially when a finer resolution is required.

Water Tank Accessories: Float Switch — Fluid Level Controller (3M). [Online] Available at: https://hardwaremart.lk/product/water-tank-accessories-float-switch-fluid-level-controller-3m/

2.1.4 Water level sensor based Water Tank Level Monitoring System

Water level sensors, while offering a non-contact alternative, come with their own set of considerations.

ELLENEX Wireless Low Power Water Tank Level Monitoring System. [Online] Net more Market. Available at: https://market.netmoregroup.com/en/listings/1595883-ellenex-wireless-low-power-water-tank-level-monitoring-system

Contact with Water: Some water level sensors require direct contact with the liquid being measured. This method may not be suitable for corrosive or sensitive liquids, potentially affecting the accuracy and longevity of the sensor. Alternative sensor types that don’t require direct contact may need to be considered for specific applications.

However, each type of setup has its advantages and limitations in the context of water level monitoring. Pressure sensors provide accuracy but demand a more intricate setup, sight gauges face challenges with visibility in certain conditions, float switches offer simplicity but lack continuous measurement capabilities, and water level sensors may have limitations based on the liquid being measured. The subsequent chapters will delve into how the project addresses these considerations by utilizing ultrasonic sensors in conjunction with PIC microcontrollers for a comprehensive water level monitoring and control system.

2.2 ULTRASONIC SENSOR APPLICATIONS

Ultrasonic sensors have gained popularity in water level monitoring due to their non-intrusive nature and accuracy. Previous projects have employed ultrasonic sensors to measure water levels in various settings, including tanks and reservoirs. The advantages include real-time measurements, non-contact operation, and suitability for different types of liquids. However, challenges such as calibration issues and interference from external factors have been noted in some studies.

2.3 AUTOMATED MOTOR CONTROL IN WATER FILLING PROCESSES

While some literature addresses water level monitoring, a gap exists concerning automated motor control for water filling processes. Few studies have comprehensively integrated motor control mechanisms into water level monitoring systems. Automated motor control is essential for optimizing water usage, preventing overflow, and ensuring a seamless and efficient water filling process.

2.4 PIC MICROCONTROLLER IN WATER LEVEL MONITORING AND MOTOR CONTROL

Studies incorporating PIC microcontrollers demonstrate the versatility and effectiveness of these devices in processing sensor data, controlling peripherals, and automating motor functions. The combination of ultrasonic sensors and PIC microcontrollers emerges as a promising solution, offering not only accurate water level measurements but also efficient control over automated motor systems.

2.5 COMPARATIVE ANALYSIS

Comparing the various approaches, the integration of ultrasonic sensors, PIC microcontrollers, and automated motor control presents a comprehensive solution for water level monitoring and management. Ultrasonic sensors provide accurate and real-time water level measurements, PIC microcontrollers facilitate efficient data processing, and automated motor control ensures optimal water filling processes.

2.6 IDENTIFIED GAPS AND LIMITATIONS

Despite the advancements in existing literature, several gaps and limitations persist, especially concerning the integration of automated motor control into water level monitoring systems. Common issues include calibration challenges with ultrasonic sensors, limitations in the range and precision of water level sensors, and potential mechanical failures in float switches.

2.7 SIGNIFICANCE OF THE CURRENT PROJECT

The present project addresses these gaps and limitations by integrating ultrasonic sensors with the PIC16F877A microcontroller and incorporating automated motor control for efficient water filling processes. This holistic approach aims to provide an accurate, real-time, and automated water level monitoring and control system, contributing to the existing literature by offering insights into the design considerations, programming logic, and overall system performance.

METHODOLOGY

This chapter has detailed the methodology, hardware, and software aspects of the Water Level Monitoring and Control System.

3.1 HARDWARE REQUIREMENTS

The Water Level Monitoring and Control System involves the integration of various hardware components, each serving a specific function in the system. The key components include:

PIC16F877A Microcontroller

Ultrasonic Sensor (HC-SR04)

LCD Display

Buzzer

LEDs (Red, Blue, Green)

Relay

Motor

3.2 SOFTWARE REQUIREMENTS

MPLAB X IDE

MPLAB X IDE is a powerful and user-friendly development environment that enhances the workflow of PIC microcontroller programmers, offering tools and utilities essential for embedded systems development.

Proteus Simulation Software

Proteus Simulation Software is an invaluable tool for electronics engineers, students, and hobbyists, offering a versatile platform for designing and testing electronic circuits and systems in a virtual environment before the actual implementation.

KiCad PCB Designing Software

KiCad is an open-source electronic design automation (EDA) suite that is widely used for designing printed circuit boards (PCBs). It provides a comprehensive set of tools for schematic capture, PCB layout, and even 3D visualization.

3.3 CIRCUIT DIAGRAM

The circuit is designed based on the hardware requirements, with connections carefully planned to ensure proper functionality. Key connections include:

Pins for LCD control (RS, EN, and D4-D7) connected to PORTD of the PIC microcontroller.

Trigger and Echo pins of the ultrasonic sensor connected to RB1 and RB2, respectively.

LED control pins (RB3, RB4, and RB5) for different water levels.

Buzzer connected to RB6.

Relay control for motor connected to RB7.

Figure 2 — Circuit Diagram of proteus simulation

3.4 ALGORITHM AND FLOW

The algorithm and flow define the logical steps of the system

I. Initialize microcontroller and peripherals.

II. Continuously read ultrasonic sensor data.

III. Process sensor data to determine water level.

IV. Activate LEDs and buzzer based on water level thresholds.

V. If middle or low water level is detected, activate motor through relay for automatic filling.

VI. Display water level information on the LCD.

3.5 CODE AND REGISTERS

The #define directives and TRISD/TRISB register settings in the code are crucial for defining pin assignments and configuring them as inputs or outputs. These settings facilitate the communication and control of various peripherals.

3.6 WORKING PRINCIPLE

The system operates based on the principle of ultrasonic distance measurement. The ultrasonic sensor emits pulses and measures the time it takes for echoes to return. The microcontroller processes this data to determine water levels. LEDs and the buzzer provide visual and auditory alerts, while the motor is automatically triggered for tank filling.

3.7 TESTING AND DEBUGGING

Testing involves the verification of each component’s functionality and their interactions

Use Proteus for simulation, validating the response of the circuit to different water levels.

Debugging involves checking the accuracy of sensor readings, ensuring proper LCD display, and verifying motor control.

RESULTS AND DISCUSSION

4.1 RESULTS

The water level monitoring system utilizes a PIC16F877A microcontroller, ultrasonic sensor, buzzer, LCD display, and LEDs to effectively track and manage water levels in a tank. The ultrasonic sensor measures the distance from the top of the tank, triggering a buzzer for 10 seconds if the water level exceeds a critical threshold of 15 cm. Real-time information, including current water level and ultrasonic wave travel time, is displayed on the LCD .The system utilizes three LEDs to visually represent the water level status. The lower level is indicated by a red LED, the middle range (between 5 cm and 15 cm) is represented by a blue LED, and the tank full status (below 5 cm) is indicated by a green LED.

Moreover, when the water level is detected at low or medium levels, the system triggers a motor using a relay to initiate water supply or notify users of the need for a refill. The intelligent combination of visual indicators, audible alerts, and motor control ensures efficient and user-friendly water level monitoring.

4.2 CALCULATION

4.2.1 WATER LEVEL MEASUREMENT

We meticulously calibrated the ultrasonic sensor for optimal accuracy within the 0–30cm range of the tank. Our efforts paid off, achieving a consistent +/- 1cm margin of error. This precision surpasses basic float switch systems and allows for reliable monitoring in various home and industrial settings.

Ultrasonic HC-SR04 module Timing Diagram

Ultrasonic sensing range between objects and sensor

We know that,

Distance = Speed x Time

Here, the speed of sound waves is 343 m/s.

Distance

So, Total distance is divided by 2 because signal travels from HC-SR04 to object and returns to the module HC-SR04

Beyond the Numbers: Accuracy, Reliability, and Effectiveness.

Accuracy: +/- 1cm accuracy is crucial in real-world applications, preventing damage or spillage caused by slight overfill. Careful calibration enhances system performance, making it suitable for critical applications.

Reliability: The PIC16F877A microcontroller serves as the system’s robust backbone, with error-checking routines and watchdog timers minimizing potential malfunctions, ensuring worry-free operation, and maintaining water levels without constant troubleshooting.

Efficiency: The system was optimized for efficiency, with lean algorithms and low-power components, resulting in longer battery life for portable applications and reduced operating costs in fixed installations, minimizing unnecessary processing power demands.

Effectiveness: Our system effectively monitored and controlled water levels, preventing overflows and shortages. Its combination of alarms, LEDs, and LCD display ensured clear notifications, empowering users to take timely action.

4.3 DISCUSSION

In order to enhance the clarity of the water level monitoring system’s logical operation, a detailed flow chart is presented below. This visual representation offers an insightful step-by-step depiction of how each component interacts, ensuring an intuitive understanding of the system’s functionality.

The flow chart outlines the sequential operation of key components, including the ultrasonic sensor, microcontroller, LCD display, buzzer alarm, LED indicators, and automatic motor control. It serves as a comprehensive guide to the decision-making process within the system, detailing the actions taken based on water level measurements and system conditions.

Flow Chart of Water Level Monitoring System

LCD Display: The LCD displayed both current water level and ultrasonic wave travel time, providing valuable information for debugging and understanding sensor behavior. It also provided smooth updates for easy monitoring without constant screen scrutiny.

Buzzer Alarm: The device features a 10-second buzzer alert for dwindling water levels, ensuring even distracted individuals don’t miss the crucial notification, and adjustable volume for various environments.

LED Indicators: The system uses a trio of LEDs to provide visual feedback on water levels, with red for immediate attention, blue for a reminder, and green for peace of mind.

Motor Control: The 5V DC motor demonstrated potential in real-world systems, with the relay module acting as a bridge, enabling the integration of home voltage motors, automating the tank filling process for added convenience and efficiency.

Incorporating PCB Design and Hardware Picture

1. PCB Design

PCB final in PDF view in KiCad

2. Hardware Implementation Picture

Final Hardware Implementation

Comparison and Beyond: Building on a Solid Foundation

Standing Out from the Crowd: Our system outperformed basic float switch systems with continuous level monitoring, digital display, and automatic control capabilities, offering a feature-rich experience without sacrificing simplicity.

Finding the Right Balance: While complex and expensive systems with multiple sensors and advanced features exist, our system struck a balance between affordability and effectiveness. It delivered a cost-effective and reliable solution for simple water level monitoring needs, making it accessible to a wider range of users.

The Journey Continues: The project aimed to establish a foundation for future possibilities, including expanding the system to multiple tanks, integrating data logging and remote monitoring, and integrating with other control systems.

No System is Perfect: We identified potential errors from temperature fluctuations, object interference, and software bugs, which were minimized through rigorous testing and code optimization.

Knowing the Boundaries: Our prototype, initially designed for a single tank, requires modifications for larger setups and a robust motor driver circuit for safe operation with higher voltages.

CONCLUSION AND FUTURE WORK

This concluding chapter encapsulates the key findings and implications of the water level monitoring system project. It provides a summary of the main points, draws conclusions from the project outcomes, and offers insights into potential future enhancements and areas for improvement. The chapter also reflects on the challenges faced during the project, the lessons learned, and acknowledges sources and references used in the development.

5.1 SUMMARY OF MAIN FINDINGS

The water level monitoring system successfully achieved its objectives, providing accurate water level measurements, clear user interfaces through LCD and LED indicators, and automated control of the water filling process.

The integration of a buzzer alarm served as an effective alert mechanism for low water levels, enhancing the system’s functionality.

5.2 CONCLUSION AND IMPLICATIONS

The project concludes with the affirmation of the system’s accuracy, reliability, and efficiency in monitoring and managing water levels.

Implications include the practicality of the system for real-world applications, especially in scenarios where efficient water resource management is crucial.

5.3 RECOMMENDATIONS FOR FUTURE WORK

Variable Tank Heights: Implement a feature to set different tank heights through a keypad, enabling the system to adapt to various tank configurations.

IoT Integration: Explore the integration of IoT (Internet of Things) technology to allow remote monitoring and control of the water level system through a mobile phone or other devices.

Wireless Ultrasonic Technology: Investigate the use of wireless ultrasonic sensors to eliminate the need for physical wiring, offering more flexibility in system deployment.

5.4 REFLECTION ON CHALLENGES AND LESSONS LEARNED

LCD Interface Issues: Overcoming challenges faced while interfacing with the LCD, including encountering a black box, taught valuable debugging skills and enhanced understanding of display technologies.

KiCad PCB Design Challenges: Addressing path errors in KiCad during PCB design provided insights into PCB layout best practices and improved proficiency in design tools.

Ultrasonic Sensor Limitations: Tackling issues with ultrasonic sensors displaying negative values at maximum distances highlighted the importance of understanding sensor specifications and implementing error-handling mechanisms.

Environmental Factors: Dealing with environmental factors, such as high humidity affecting sensor readings, underscored the need for robust design considering real-world conditions.

Keypad Code Errors: Resolving errors while working with the keypad improved coding skills and emphasized the importance of thorough testing.

In conclusion, the water level monitoring system project not only met its objectives but also provided insights into potential future enhancements and challenges faced in the development process. The lessons learned contribute to the continual improvement of both technical and problem-solving skills. This project represents a valuable step toward efficient water resource management and serves as a foundation for future innovations in the field.

Appendix

/* config.h file

* File: Smart Water Level Indicator with Motor Control

* Author: IL.Imthath Usain, MSM.Suhail

* Comments:

* Revision history:

*/

// This is a guard condition so that contents of this file are not included

// more than once.

#ifndef XC_HEADER_TEMPLATE_H

#define XC_HEADER_TEMPLATE_H

#include <xc.h> // include processor files — each processor file is guarded.

#include <pic.h>

#define _XTAL_FREQ 20000000

#define RS RD2

#define EN RD3

#define D4 RD4

#define D5 RD5

#define D6 RD6

#define D7 RD7

#define Trigger RB1 //34 is Trigger

#define Echo RB2//35 is Echo

//#define PWM_PIN RB7 // PWM output pin

#pragma config FOSC = HS // Oscillator Selection bits (HS oscillator)

#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT disabled)

#pragma config PWRTE = ON // Power-up Timer Enable bit (PWRT enabled)

#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)

#pragma config LVP = OFF // Low-Voltage (Single-Supply) In-Circuit Serial Programming Enable bit (RB3 is digital I/O, HV on MCLR must be used for programming)

#pragma config CPD = OFF // Data EEPROM Memory Code Protection bit (Data EEPROM code protection off)

#pragma config WRT = OFF // Flash Program Memory Write Enable bits (Write protection off; all program memory may be written to by EECON control)

#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)

// TODO Insert appropriate #include <>

// TODO Insert C++ class definitions if appropriate

// TODO Insert declarations

// Comment a function and leverage automatic documentation with slash star star

/**

<p><b>Function prototype:</b></p>

<p><b>Summary:</b></p>

<p><b>Description:</b></p>

<p><b>Precondition:</b></p>

<p><b>Parameters:</b></p>

<p><b>Returns:</b></p>

<p><b>Example:</b></p>

<code>

</code>

<p><b>Remarks:</b></p>

*/

// TODO Insert declarations or function prototypes (right here) to leverage

// live documentation

#ifdef __cplusplus

extern “C” {

#endif /* __cplusplus */

// TODO If C++ is being used, regular C code needs function names to have C

// linkage so the functions can be used by the c code.

#ifdef __cplusplus

}

#endif /* __cplusplus */

#endif /* XC_HEADER_TEMPLATE_H */

main.c file code

#include “config.h”

#include <stdio.h>

//LCD Functions

void Lcd_SetBit(char data_bit) //Based on the Hex value Set the Bits of the Data Lines

{

if(data_bit& 1)

D4 = 1;

else

D4 = 0;

if(data_bit& 2)

D5 = 1;

else

D5 = 0;

if(data_bit& 4)

D6 = 1;

else

D6 = 0;

if(data_bit& 8)

D7 = 1;

else

D7 = 0;

}

void Lcd_Cmd(char a)

{

RS = 0;

Lcd_SetBit(a); //Incoming Hex value

EN = 1;

__delay_ms(4);

EN = 0;

}

void Lcd_Clear()

{

Lcd_Cmd(0); //Clear the LCD

Lcd_Cmd(1); //Move the curser to first position

}

void Lcd_Set_Cursor(char a, char b)

{

char temp,z,y;

if(a== 1)

{

temp = 0x80 + b — 1; //80H is used to move the curser

z = temp>>4; //Lower 8-bits

y = temp & 0x0F; //Upper 8-bits

Lcd_Cmd(z); //Set Row

Lcd_Cmd(y); //Set Column

}

else if(a== 2)

{

temp = 0xC0 + b — 1;

z = temp>>4; //Lower 8-bits

y = temp & 0x0F; //Upper 8-bits

Lcd_Cmd(z); //Set Row

Lcd_Cmd(y); //Set Column

}

}

void Lcd_Start()

{

Lcd_SetBit(0x00);

for(int i=1065244; i<=0; i — ) NOP();

Lcd_Cmd(0x03);

__delay_ms(5);

Lcd_Cmd(0x03);

__delay_ms(11);

Lcd_Cmd(0x03);

Lcd_Cmd(0x02); //02H is used for Return home -> Clears the RAM and initializes the LCD

Lcd_Cmd(0x02); //02H is used for Return home -> Clears the RAM and initializes the LCD

Lcd_Cmd(0x08); //Select Row 1

Lcd_Cmd(0x00); //Clear Row 1 Display

Lcd_Cmd(0x0C); //Select Row 2

Lcd_Cmd(0x00); //Clear Row 2 Display

Lcd_Cmd(0x06);

}

void Lcd_Print_Char(char data) //Send 8-bits through 4-bit mode

{

char Lower_Nibble,Upper_Nibble;

Lower_Nibble = data&0x0F;

Upper_Nibble = data&0xF0;

RS = 1; // => RS = 1

Lcd_SetBit(Upper_Nibble>>4); //Send upper half by shifting by 4

EN = 1;

for(int i=2130483; i<=0; i — ) NOP();

EN = 0;

Lcd_SetBit(Lower_Nibble); //Send Lower half

EN = 1;

for(int i=2130483; i<=0; i — ) NOP();

EN = 0;

}

void Lcd_Print_String(char *a)

{

int i;

for(i=0;a[i]!=’\0';i++)

Lcd_Print_Char(a[i]); //Split the string using pointers and call the Char function

}

void Lcd_Print_Int(int value) {

char buffer[10];

sprintf(buffer, “%d”, value);

Lcd_Print_String(buffer);

}

/*End of LCD Functions*/

int time_taken;

int distance;

int main() {

TRISD = 0x00; //PORTD declared as output for interfacing LCD

TRISB0 = 1; //DEfine the RB0 pin as input to use as interrupt pin

TRISB1 = 0; //Trigger pin of US sensor is sent as output pin

TRISB2 = 1; // Echo pin of US sensor is set as an input pin

TRISB3 = 0; //RB3 is output pin for LED

TRISB4 = 0; //RB4 is output pin for LED

TRISB5 = 0; //RB5 is output pin for LED

TRISB6 = 0; //buzzer

TRISB7 = 0; //motor

T1CON=0x20;

Lcd_Start();

Lcd_Set_Cursor(1,1);

Lcd_Print_String(“US sensor”);

Lcd_Set_Cursor(2,1);

Lcd_Print_String(“with PIC16F877A”);

__delay_ms(2000);

Lcd_Clear();

while(1) {

TMR1H =0; TMR1L =0; //clear the timer bits

Trigger = 0;

__delay_us(15);

Trigger = 1;

__delay_us(15);

Trigger = 0;

while (Echo == 0);

TMR1ON = 1;

while (Echo == 1);

TMR1ON = 0;

time_taken = (TMR1L | (TMR1H << 8));

distance = (0.0343 * time_taken) / 2;

time_taken = time_taken * 0.8; //0.8 is a correction fector

Lcd_Set_Cursor(1, 1);

Lcd_Print_String(“Time:”);

Lcd_Print_Int(time_taken);

Lcd_Print_String(“us”);

Lcd_Set_Cursor(2, 1);

Lcd_Print_String(“Distance:”);

Lcd_Print_Int(distance);

Lcd_Print_String(“cm”);

// Turn on LED and buzzer based on distance

if (distance <= 5) {

RB3 = 0; // Turn off RB3 LED

RB4 = 0; // Turn off RB4 LED

RB5 = 1; // Turn on RB5 LED

RB6 = 0; // Turn on buzzer

RB7 = 0;

} else if (distance <= 15) {

RB3 = 0; // Turn off RB3 LED

RB4 = 1; // Turn on RB4 LED

RB5 = 0; // Turn off RB5 LED

RB6 = 0; // Turn off buzzer

RB7 = 1;

} else if (distance <= 30) {

RB3 = 1; // Turn on RB3 LED

RB4 = 0; // Turn off RB4 LED

RB5 = 0; // Turn off RB5 LED

RB6 = 1; // Turn off buzzer

__delay_ms(1000); // Buzzer on for 1 second

RB6 = 0; // Turn off buzzer

RB7 = 1;

} else {

// If distance is greater than 40 cm, turn off all LEDs and buzzer

RB3 = 0;

RB4 = 0;

RB5 = 0;

RB6 = 0;

RB7 = 0;

}

}

return 0;

}

References

[1] Kim, J., Kim, J., Yoon, J. (2018). ”An Efficient Ultrasonic Sensor-based Water Depth Measurement System.” IEEE Sensors Journal, 18(23), 9575–9582.

[2]Electronics, E. Et al. (2017) Interfacing Ultrasonic Sensor HC-SR04 with PIC Microcontroller, Circuit Digest. Available at: https://circuitdigest.com/microcontroller-projects/interfacing-ultrasonic-sensor-hc-sr04-with-pic16f877a.

[3] IoT Based Water Level Indicator Using Ultrasonic Sensor (no date) iotdesignpro.com. Available at: https://iotdesignpro.com/projects/iot-based-water-level-indicator-using-ultrasonic-sensor.

[4] Gsantony (no date) AUTOMATIC WATER TANK LEVEL INDICATOR & MOTOR CONTROL USING ULTRASONIC SENSOR, Instructables. Available at: https://www.instructables.com/AUTOMATIC-WATER-TANK-LEVEL-INDICATOR-MOTOR-CONTROL/

[5] Water Pump Automation with Ultrasonic Sensor (no date) projecthub.arduino.cc. Available at: https://projecthub.arduino.cc/munir03125344286/water-pump-automation-with-ultrasonic-sensor-1569fb

[6] What is the correct supply voltage for LEDs? (no date) Electrical Engineering Stack Exchange. Available at: https://electronics.stackexchange.com/questions/558601/what-is-the-correct-supply-voltage-for-leds (Accessed: 19 January 2024).

‌ [7] Motors (2019) Rice.edu. Available at: https://www.clear.rice.edu/elec201/Book/motors.html.

‌ [8] Arduino Get Started (no date) ‘Arduino — Ultrasonic Sensor | Arduino Get Started’. Available at: https://arduinogetstarted.com/tutorials/arduino-ultrasonic-sensor.

[9] Interfacing 16x2 LCD with PIC16F877A microcontroller (no date) www.youtube.com. Available at: https://youtu.be/j20d4HLKgR8?si=8AfxP_Usxfg0Xmen (Accessed: 19 January 2024).

‌ [10] www.youtube.com. (n.d.). Ultrasonic Sensor Interfacing with PIC16F877A Microcontroller. [online] Available at: https://youtu.be/Q-rUQ6SWiDE?si=XGNU4k-2_RkopUdW [Accessed 19 Jan. 2024].

AUTHOR

Imthath Usain (BSc (Hons) Eng. in Electronics & Power System(R))

--

--

Imthath Usain
Imthath Usain

Written by Imthath Usain

0 Followers

BSc(Hons) in Electronics and Power System Engineering UG | Final Year Student

No responses yet