The Smart-Sprayer is an advanced IoT-enabled agricultural device built on the ESP32 microcontroller platform. It provides intelligent, automated pesticide spraying with weather-aware operation and user-friendly button-based scheduling. The system features ultrasonic level monitoring, GSM SMS notifications, LCD status display, and comprehensive feedback systems for professional agricultural applications.
- System Startup: ESP32 initializes all hardware components
- Button Scheduling: User sets spray time using ESP32 buttons
- Automated Monitoring: System continuously checks time and weather
- Weather Validation: Prevents spraying during rain conditions
- Smart Activation: Activates pumps when conditions are optimal
- Level Monitoring: Real-time container level checking during operation
- Feedback System: Professional audio-visual status indicators
- Button-Based Scheduling: Intuitive time setting using ESP32 buttons with LCD menu navigation
- Weather-Aware Operation: Automatic rain detection prevents unnecessary spraying
- Container Level Monitoring: Real-time ultrasonic measurement with low-level warnings
- Automated Spraying: Scheduled activation with intelligent condition checking
- Professional Feedback: Commercial-grade LED patterns and industrial buzzer tones
- GSM Notifications: SMS alerts for completion, postponement, and system events
- Network Resilience: Automatic reconnection with SMS retry mechanisms
- Dual Relay Control: Independent pump/valve operation for precision spraying
- RTC Timekeeping: Accurate scheduling with NTP synchronization and battery backup
- Firebase Integration: Cloud data logging and remote monitoring capabilities
- WiFi Management: Automatic configuration with captive portal fallback
- Serial Diagnostics: Comprehensive command interface for testing and configuration
- Modular Architecture: Clean separation of concerns with dedicated config headers
- ESP32 Microcontroller: Dual-core processing with WiFi/Bluetooth
- Ultrasonic Sensors: HC-SR04 for precise container level measurement
- GSM Module: SIM800L for SMS communication and network monitoring
- LCD Display: 20x4 I2C interface for status and menu navigation
- Relay System: Dual-channel control for spray actuators
- Button Interface: 4-button navigation (WiFi reset + 3 menu controls)
- RTC Module: DS1302 for reliable timekeeping
- Audio/Visual: Buzzer and dual LED status indicators
The Smart-Sprayer includes a comprehensive notification system for operational awareness:
- SMS Alerts: Automatic notifications for spraying events (completion, postponement, errors)
- Retry Logic: Failed SMS messages are automatically retried up to 3 times
- Network Monitoring: GSM network disconnection triggers automatic reconnection attempts
- Commercial Feedback: Professional LED blinking patterns and industrial buzzer tones
- Status Indicators: Visual and audible feedback for all system operations
The project includes a detailed flowchart diagram showing the complete operational process:
diagram/SmartSprayer_Flowchart.md
This flowchart illustrates the step-by-step process from ESP32 button scheduling through automated spraying cycles, including decision points for weather checking, time validation, and level monitoring.
The ultrasonic sensor measures the distance from the sensor to the surface of the pesticide in the container. To calculate the fill percentage:
- Define a variable for the total height of the container (e.g.,
CONTAINER_HEIGHTin cm) - Measure the distance from the sensor to the liquid surface using the SR04 sensor
- Calculate the filled height:
filledHeight = CONTAINER_HEIGHT - measuredDistance - Calculate the percentage:
percentage = (filledHeight / CONTAINER_HEIGHT) * 100
This allows precise monitoring of pesticide levels to prevent running out during spraying operations.
- ESP32 development board (ESP32-WROOM-32 recommended) with built-in WiFi and Bluetooth
- HC-SR04 ultrasonic distance sensor (2 units)
- 20x4 I2C LCD display module
- GSM module (SIM800L or compatible)
- 2-channel relay module (5V or 12V based on application)
- Buzzer module (active/passive buzzer)
- LED indicators (2 units: OK and Error status)
- DS1302 RTC module (for accurate timekeeping)
- Push buttons (4 units: WiFi reset + 3 for menu navigation)
- SIM card for GSM module
- Power supply (5V for ESP32, appropriate voltage for relays)
- Jumper wires and breadboard for prototyping
- Antenna for GSM module
- Internet connection for WiFi and Firebase functionality
The system uses centralized pin definitions in PINS_CONFIG.h for easy modification:
| Component | Pin | Function | Notes |
|---|---|---|---|
| Ultrasonic Sensor 1 | GPIO 12 | Trig | Trigger pin for ultrasonic pulses |
| Ultrasonic Sensor 1 | GPIO 13 | Echo | Echo pin for distance measurement |
| Ultrasonic Sensor 2 | GPIO 14 | Trig | Trigger pin for second sensor |
| Ultrasonic Sensor 2 | GPIO 16 | Echo | Echo pin for second sensor |
| Relay Module | GPIO 4 | Relay 1 Control | Controls first spray actuator |
| Relay Module | GPIO 5 | Relay 2 Control | Controls second spray actuator |
| GSM Module | GPIO 10 | RX | Receive data from GSM module |
| GSM Module | GPIO 11 | TX | Transmit data to GSM module |
| LCD Display | GPIO 21 | SDA | I2C data line (default ESP32 I2C) |
| LCD Display | GPIO 22 | SCL | I2C clock line (default ESP32 I2C) |
| Buzzer | GPIO 17 | Control | Audio alert output |
| System OK LED | GPIO 18 | Status | Indicates system OK state |
| System Error LED | GPIO 19 | Status | Indicates system error state |
| WiFi Reset Button | GPIO 23 | Input | Triggers WiFi manager reset (hold 3s) |
| Menu Up Button | GPIO 25 | Input | Menu navigation up |
| Menu Down Button | GPIO 26 | Input | Menu navigation down |
| Menu Select Button | GPIO 27 | Input | Menu select/save |
| DS1302 CE | GPIO 32 | Output | RTC chip enable |
| DS1302 I/O | GPIO 33 | I/O | RTC data line |
| DS1302 CLK | GPIO 14 | Output | RTC serial clock |
- Arduino IDE 1.8.19 or later
- ESP32 board support package for Arduino IDE
LiquidCrystal_I2C(for LCD display control)SoftwareSerial(for GSM module communication)WiFiManager(for WiFi configuration)Firebase_ESP_Client(for Firebase integration)NTPClient(for time synchronization)HTTPClient(for weather API requests)ArduinoJson(for parsing weather API responses)Time(for time management)TimeAlarms(for scheduled alarms)RtcDS1302(for DS1302 RTC module)
- Install Arduino IDE from the official website
- Add ESP32 board support:
- Open Arduino IDE
- Go to File > Preferences
- Add
https://dl.espressif.com/dl/package_esp32_index.jsonto Additional Board Manager URLs - Tools > Board > Boards Manager > Search for ESP32 > Install
- Install required libraries:
- Sketch > Include Library > Manage Libraries
- Search and install the required libraries listed above
- Copy
source/esp32/SmartSprayer/FIREBASE_CREDENTIALS_template.htosource/esp32/SmartSprayer/FIREBASE_CREDENTIALS.h - Fill in your Firebase project credentials:
- WiFi SSID and password
- Firebase API key and database URL
- Service account credentials
- User credentials (optional)
- The
FIREBASE_CREDENTIALS.hfile is ignored by git to protect sensitive information
- Copy
source/esp32/SmartSprayer/GSM_RECIPIENTS_template.htosource/esp32/SmartSprayer/GSM_RECIPIENTS.h - Add your phone numbers to the recipients array
- Set the
numRecipientsvariable to the number of active recipients - The
GSM_RECIPIENTS.hfile is ignored by git to protect phone numbers
- Copy
source/esp32/SmartSprayer/WEATHER_CREDENTIALS_template.htosource/esp32/SmartSprayer/WEATHER_CREDENTIALS.h - Fill in your WeatherAPI credentials:
- API key from https://www.weatherapi.com/
- Location (e.g., "Manila" or city name)
- The
WEATHER_CREDENTIALS.hfile is ignored by git to protect your API key
The system uses WeatherAPI for current weather monitoring. Here's a sample API call and response:
API Call:
GET https://api.weatherapi.com/v1/current.json?key=64812e322c3f4b42af7135146252012&q=Manila&aqi=no
Sample Response:
{
"location": {
"name": "Manila",
"region": "Manila",
"country": "Philippines",
"lat": 14.6042,
"lon": 120.9822,
"tz_id": "Asia/Manila",
"localtime_epoch": 1766239111,
"localtime": "2025-12-20 21:58"
},
"current": {
"last_updated_epoch": 1766238300,
"last_updated": "2025-12-20 21:45",
"temp_c": 26.1,
"temp_f": 79.0,
"is_day": 0,
"condition": {
"text": "Partly cloudy",
"icon": "//cdn.weatherapi.com/weather/64x64/night/116.png",
"code": 1003
},
"wind_mph": 4.5,
"wind_kph": 7.2,
"wind_degree": 56,
"wind_dir": "ENE",
"pressure_mb": 1011.0,
"pressure_in": 29.85,
"precip_mm": 0.0,
"precip_in": 0.0,
"humidity": 84,
"cloud": 75,
"feelslike_c": 28.5,
"feelslike_f": 83.4,
"windchill_c": 25.2,
"windchill_f": 77.3,
"heatindex_c": 27.2,
"heatindex_f": 81.0,
"dewpoint_c": 21.1,
"dewpoint_f": 70.0,
"vis_km": 10.0,
"vis_miles": 6.0,
"uv": 0.0,
"gust_mph": 6.6,
"gust_kph": 10.6
}
}The system checks current.precip_mm and current.condition.text to determine if it's raining.
- Never commit
FIREBASE_CREDENTIALS.h,GSM_RECIPIENTS.h, orWEATHER_CREDENTIALS.hto version control - Use the provided templates to create your configuration files
- Regularly rotate API keys, passwords, and phone numbers
- Use Firebase security rules to protect your database
git clone https://github.com/qppd/Smart-Sprayer.git
cd Smart-SprayerRefer to the wiring diagrams in the wiring/ directory for complete circuit connections:
- Smart-Sprayer.fzz - Fritzing diagram file

The model/ directory contains 3D design files and reference images for the Smart-Sprayer hardware enclosure:
Board Case (Main Enclosure)
- Smart_Sprayer_Board_Case.stl - 3D model of the main board case for 3D printing
- Reference image of the board case design
Case Cover
- Smart_Sprayer_Board_Case_Cover.stl - 3D model of the case cover/lid
- Reference image of the case cover
Full Assembly Views
- Complete assembled system showing all components integrated in the enclosure with proper cable routing and sensor placement
- Alternative angle of the assembled system demonstrating full device configuration and component visibility
- Connect the ultrasonic sensor to GPIO 12 (Trig) and GPIO 13 (Echo)
- Wire the relay module to GPIO 4 and GPIO 5
- Connect GSM module to GPIO 10 (RX) and GPIO 11 (TX)
- Attach the I2C LCD to the default I2C pins (GPIO 21 SDA, GPIO 22 SCL)
- Connect the WiFi reset button to GPIO 23 (with pull-up resistor)
- Connect menu navigation buttons: Up to GPIO 25, Down to GPIO 26, Select to GPIO 27
- Connect DS1302 RTC: CE to GPIO 32, I/O to GPIO 33, CLK to GPIO 14
- Insert SIM card into GSM module and attach antenna
- Power the system with appropriate voltage sources
- Open
source/esp32/SmartSprayer/SmartSprayer.inoin Arduino IDE - Select ESP32 Dev Module from Tools > Board
- Choose the correct COM port
- Click Upload to flash the firmware
- Power On: Connect power to the ESP32 board
- System Initialization: LCD displays startup sequence and component status
- Ready State: System shows "System Ready" when all components are initialized
- Button Scheduling: Use the 4 buttons to set spray schedules and monitor status
The system uses 4 buttons for complete operation:
| Button | GPIO Pin | Function |
|---|---|---|
| WiFi Reset | GPIO 23 | Hold 3s to reset WiFi settings |
| Menu Up | GPIO 25 | Navigate menus up / increment values |
| Menu Down | GPIO 26 | Navigate menus down / decrement values |
| Menu Select | GPIO 27 | Select items / confirm settings |
- Enter Scheduling: Press any menu button when system is ready
- Navigate Menu: Use Up/Down buttons to select "Schedule Spray"
- Set Time: Use Up/Down buttons to adjust hour and minute
- Confirm: Press Select button to save the schedule
- Monitor: LCD displays scheduled time and system status
Once scheduled, the system operates automatically:
- Time Check: Compares current time with scheduled spray time
- Weather Validation: Checks for rain conditions before spraying
- Pump Activation: Activates relays when conditions are optimal
- Level Monitoring: Continuously monitors container levels during spraying
- Completion Feedback: Provides audio-visual confirmation when done
- Cycle Repeat: Returns to monitoring for next scheduled spray
- Normal Operation: System connects to saved WiFi network automatically
- Reset Mode: Hold WiFi reset button (GPIO 23) for 3 seconds during boot
- AP Mode: System creates "SmartSprayer-Setup" access point for configuration
- Web Portal: Connect to AP and open 192.168.4.1 in browser to configure WiFi
The system provides a serial diagnostics interface for advanced troubleshooting and configuration. Connect to the ESP32 using Arduino Serial Monitor at 9600 baud rate. This interface is primarily for maintenance and diagnostics - normal operation is fully automated through the button interface.
check-network: Queries GSM network registration statusget-distance1: Retrieves current distance measurement from ultrasonic sensor 1get-distance2: Retrieves current distance measurement from ultrasonic sensor 2get-level: Calculates and displays container fill level and percentagecheck-weather: Fetches current weather and checks for rainget-time: Retrieves and displays current formatted date/timewifi-reset: Resets WiFi settings and restarts in AP mode
operate-relay1_on/off: Manual relay control for testingbuzzer-beep: Test buzzer functionalityled-ok/error/warning/clear: Test LED indicatorstest-display: Display test information on LCDsend-sms: Send test SMS message
get-level
Distance: 45 cm, Filled: 55 cm, Percentage: 55 %
check-weather
Weather check: No rain currently - safe to spray
get-time
Current time: 2025-12-20 14:30:25
void initLCD(): Initializes the LCD displayvoid clearLCD(): Clears the LCD screenvoid setLCDText(String text, int x, int y): Displays text at specified coordinatesvoid setLCDText(double value, int x, int y): Displays numeric value at coordinatesvoid setLCDText(float value, int x, int y): Displays float value at coordinatesvoid setLCDText(int value, int x, int y): Displays integer value at coordinatesvoid setLCDText(char text, int x, int y): Displays character at coordinates
- Centralized pin definitions for all hardware components
- Easy to modify pin assignments without changing multiple files
void initBuzzer(): Initializes buzzer pinvoid buzzerOn(): Turns buzzer on continuouslyvoid buzzerOff(): Turns buzzer offvoid buzzerBeep(int duration_ms): Produces a beep for specified duration
void initLEDs(): Initializes LED pinsvoid setSystemOK(): Turns on OK LED, off error LEDvoid setSystemError(): Turns on error LED, off OK LEDvoid setSystemWarning(): Turns on both LEDsvoid clearSystemLEDs(): Turns off both LEDs
void initBUTTONS(): Initializes all 4 buttons with pull-up resistorsvoid setInputFlags(): Reads and debounces button statesvoid resolveInputFlags(): Processes button presses and calls appropriate actionsvoid inputAction(int buttonIndex): Handles button press actions (WiFi reset, menu navigation)void enterSchedulingMode(): Activates spray scheduling interfacevoid exitSchedulingMode(): Returns to main menuvoid scheduleSprayAlarm(int hour, int minute): Sets daily spray alarmvoid cancelSprayAlarm(): Removes existing spray alarm
void initRTC(): Initializes DS1302 RTC module and syncs with system timevoid syncRTCWithNTP(): Synchronizes RTC with NTP time (called once during setup)bool isRTCValid(): Checks if RTC time is validString getRTCDateTimeString(): Returns formatted RTC date/time stringvoid updateSystemTimeFromRTC(): Updates system time from RTC
void initGSM(): Initializes GSM module communicationvoid sendSMS(String number, String message): Sends SMS to specified numbervoid sendSMSToAll(String message): Sends SMS to all configured numbersvoid checkNetwork(): Checks GSM network registration status
void initRELAY(): Sets up relay control pinsvoid operateRELAY(uint16_t RELAY, boolean OPENED): Controls relay state
void initSR04(): Initializes ultrasonic sensor pinslong readDistance(): Returns distance measurement in centimeters from sensor 1 (used for container level monitoring)long readDistance2(): Returns distance measurement in centimeters from sensor 2float calculateFillLevel(long distance): Calculates filled height in container (container height - distance)float calculateFillPercentage(long distance): Calculates fill percentage (0-100%)
void initWIFI(): Initializes WiFi connection with auto-configuration portal
void initFIREBASE(): Initializes Firebase connection and streamsvoid updateDeviceCurrent(...): Updates current device state in Firebasevoid logDeviceData(...): Logs device data with timestampvoid sendSmartSprayerData(...): Sends Smart Sprayer data to Firebasevoid sendMessage(...): Sends FCM notificationvoid sendMessageToAll(...): Sends FCM to all registered devicesvoid handleStreams(): Processes Firebase real-time streamsbool isReady(): Checks Firebase connection status
void initNTP(): Initializes NTP time synchronizationvoid getNTPDate(): Retrieves and formats current date/timeunsigned long getNTPTimestamp(): Gets Unix timestamp from NTPunsigned long getNTPTimestampWithFallback(): NTP timestamp with automatic fallbackbool isNTPSynced(): Checks if NTP time is synchronizedString getFormattedDateTime(): Returns formatted date/time stringString getFormattedDateTimeWithFallback(): Formatted time with fallback indicationString getCurrentLogPrefix(): Provides timestamp prefix for logging
bool checkWeatherForRain(): Fetches current weather and returns true if it's raining
Smart-Sprayer/
├── .gitignore
├── LICENSE
├── README.md
├── FIREBASE_CREDENTIALS_template.h
├── diagram/
│ └── [circuit diagrams and schematics]
├── model/
│ ├── SmartSprayer_Board_Case.stl
│ ├── Smart_Sprayer_Board_Case.png
│ ├── Smart_Sprayer_Board_Case_Cover.stl
│ ├── Smart_Sprayer_Board_Case_Cover.png
│ ├── Smart_Sprayer_Full_View.png
│ └── Smart_Sprayer_Full_View_2.png
├── source/
│ └── esp32/
│ └── SmartSprayer/
│ ├── SmartSprayer.ino
│ ├── PINS_CONFIG.h
│ ├── PINS_CONFIG.h
│ ├── LCD_CONFIG.h
│ ├── GSM_CONFIG.h
│ ├── GSM_RECIPIENTS.h (ignored)
│ ├── GSM_RECIPIENTS_template.h
│ ├── RELAY_CONFIG.h
│ ├── SR04_CONFIG.h
│ ├── WIFI_CONFIG.h
│ ├── FIREBASE_CONFIG.h
│ ├── NTP_CONFIG.h
│ ├── WEATHER_CONFIG.h
│ ├── BUZZER_CONFIG.h
│ ├── LED_CONFIG.h
│ ├── BUTTON_CONFIG.h
│ ├── RTC_CONFIG.h
│ ├── WEATHER_CREDENTIALS.h (ignored)
│ ├── WEATHER_CREDENTIALS_template.h
│ ├── FIREBASE_CREDENTIALS.h (ignored)
│ └── FIREBASE_CREDENTIALS_template.h
└── wiring/
└── [wiring diagrams and instructions]
Edit GSM_CONFIG.h to modify:
- Phone numbers for SMS recipients
- GSM module pins (if different from defaults)
- Communication baud rate
Modify LCD parameters in LCD_CONFIG.h:
- I2C address (default: 0x27)
- Display dimensions (default: 20x4)
Adjust relay settings in RELAY_CONFIG.h:
- GPIO pins for relays
- Relay logic (active high/low)
Configure sensor parameters in SR04_CONFIG.h:
- Trigger and echo pins
- Measurement timing parameters
Configure WiFi reset button settings in BUTTON_CONFIG.h:
- Button pin assignment
- Debounce delay
- Hold time for WiFi reset trigger
- Ensure correct COM port selection in Arduino IDE
- Check USB cable and drivers
- Try different USB port
- Verify I2C connections and address
- Check power supply to LCD
- Confirm I2C pins (SDA: GPIO 21, SCL: GPIO 22)
- Check SIM card insertion and PIN status
- Verify antenna connection
- Ensure sufficient signal strength
- Check GSM module power supply
- Ensure clear line of sight for sensor
- Check voltage levels (5V required)
- Verify pin connections
- Test with known distances
- Confirm relay module power supply
- Check GPIO pin assignments
- Verify relay logic (normally open/closed)
- Ensure valid OpenWeatherMap API key in
WEATHER_CREDENTIALS.h - Check WiFi connection for API requests
- Verify location format (e.g., "Manila,PH")
- Monitor serial output for API error codes
Enable serial debugging by monitoring the Serial output at 9600 baud. The system provides detailed status messages during initialization and operation.
We welcome contributions to the Smart-Sprayer project. Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Maintain modular code structure
- Add comments for complex logic
- Test all changes thoroughly
- Update documentation for new features
- Follow Arduino coding standards
This project is licensed under the terms specified in the LICENSE file. See LICENSE for details.
- ESP32 community for microcontroller support
- Arduino framework developers
- Open-source library contributors
For questions, issues, or contributions, please use the GitHub repository's issue tracker or pull request system.
- Email: quezon.province.pd@gmail.com
- GitHub: github.com/qppd
- Portfolio: sajed-mendoza.onrender.com
- Facebook: facebook.com/qppd.dev
- Facebook Page: facebook.com/QUEZONPROVINCEDEVS
Created by qppd
This project is hosted on GitHub at: https://github.com/qppd/Smart-Sprayer