Skip to content

KDsudheera/greenhouse-ai-fancontroller

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

12 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🌱 Greenhouse AI Fan Controller

An intelligent IoT system that uses machine learning to automatically control greenhouse ventilation based on real-time temperature and humidity data

Machine Learning IoT Flutter Firebase Platform Simulator

πŸ“Š Project Overview

This project implements a complete AI-powered greenhouse fan control system with three main components:

  1. 🧠 AI Model - TensorFlow Lite model trained on 17,521 sensor samples
  2. πŸ”§ ESP32 Controller - Hardware simulation with real sensor integration
  3. πŸ“± Flutter Mobile App - Real-time monitoring and AI-powered control

🎯 Key Features

  • Intelligent Fan Control: AI decides when to turn fan ON/OFF based on environmental conditions
  • Real-time Monitoring: Live temperature and humidity tracking
  • Dual Control Modes: AI automatic mode or manual override
  • Cloud Integration: Firebase real-time database for seamless communication
  • Hardware Simulation: Complete Wokwi simulation for testing without physical hardware
  • Production Ready: Robust error handling and offline capabilities

πŸš€ Quick Demo

Real-time AI Predictions:

🌑️ Temperature: 25.8Β°C | πŸ’§ Humidity: 78.5%
🧠 AI Prediction: 0.387 (38.7% confidence) β†’ πŸŒ€ Fan: OFF

🌑️ Temperature: 32.1Β°C | πŸ’§ Humidity: 85.2% 
🧠 AI Prediction: 0.782 (78.2% confidence) β†’ πŸŒ€ Fan: ON

System Architecture:

πŸ“± Flutter App          πŸ”₯ Firebase          πŸ”§ ESP32 + Sensors
β”œβ”€β”€ AI Model            β”œβ”€β”€ Real-time DB      β”œβ”€β”€ DHT22 (Temp/Humidity)
β”œβ”€β”€ Dashboard UI        β”œβ”€β”€ Authentication    β”œβ”€β”€ Relay Module (Fan)
β”œβ”€β”€ Manual Controls     └── Data Sync         └── WiFi Connection
└── Live Monitoring     ↕️ Bidirectional      ↕️ Sensor Data

πŸ› οΈ How to Run This Project

Prerequisites

  1. Development Environment:

  2. Hardware (Optional - for physical deployment):

    • ESP32 Development Board
    • DHT22 Temperature/Humidity Sensor
    • 5V Relay Module
    • Jumper wires and breadboard

Step 1: Clone the Repository

git clone https://github.com/KDsudheera/greenhouse-ai-fancontroller.git
cd greenhouse-ai-fancontroller

Step 2: Set Up Firebase

  1. Create Firebase Project:

    • Go to Firebase Console
    • Click "Create a project"
    • Enable Realtime Database (start in test mode)
    • Enable Authentication β†’ Email/Password
  2. Configure Firebase for Flutter:

    cd flutter_app
    
    # Install Firebase CLI (if not installed)
    npm install -g firebase-tools
    
    # Login and configure
    firebase login
    flutter pub global activate flutterfire_cli
    flutterfire configure
  3. Set up Database Rules:

    {
      "rules": {
        ".read": "auth != null",
        ".write": "auth != null"
      }
    }

Step 3: Configure ESP32 Credentials

  1. Copy the example config:

    cd esp32-controller
    cp include/config.h.example include/config.h
  2. Edit include/config.h with your credentials:

    // WiFi Configuration
    #define WIFI_SSID "your-wifi-name"
    #define WIFI_PASSWORD "your-wifi-password"
    
    // Firebase Configuration  
    #define API_KEY "your-firebase-api-key"
    #define DATABASE_URL "https://your-project-default-rtdb.firebaseio.com/"
    #define USER_EMAIL "your-email@example.com"
    #define USER_PASSWORD "your-password"

Step 4: Run the ESP32 Simulation

  1. Using Wokwi (Recommended for testing):

    cd esp32-controller
    
    # Upload to Wokwi and run simulation
    # Open diagram.json in Wokwi.com
    # Click "Start Simulation"
  2. Using Physical Hardware:

    cd esp32-controller
    
    # Compile and upload
    pio run --target upload
    
    # Monitor serial output
    pio device monitor

Step 5: Run the Flutter App

  1. Install dependencies:

    cd flutter_app
    flutter pub get
  2. Run on Android device/emulator:

    # Check connected devices
    flutter devices
    
    # Run the app
    flutter run
  3. Enable Developer Options (for physical device):

    • Settings β†’ About Phone β†’ Tap "Build Number" 7 times
    • Settings β†’ Developer Options β†’ Enable "USB Debugging"

Step 6: Test the Complete System

  1. Verify ESP32 Connection:

    • Check serial monitor for "Connected to Firebase"
    • Verify sensor readings in console
  2. Check Firebase Data:

    • Open Firebase Console β†’ Realtime Database
    • Look for /climate_data updates every 10 seconds
  3. Test Flutter App:

    • Open the app and verify real-time data display
    • Toggle between AI mode and Manual mode
    • Check AI predictions in the console

πŸ“ Project Structure

greenhouse-ai-fancontroller/
β”œβ”€β”€ README.md                           # This file
β”œβ”€β”€ esp32-controller/                   # ESP32 microcontroller code
β”‚   β”œβ”€β”€ src/main.cpp                   # Main ESP32 application
β”‚   β”œβ”€β”€ include/
β”‚   β”‚   β”œβ”€β”€ config.h.example           # Configuration template
β”‚   β”‚   └── README                     # Include directory info
β”‚   β”œβ”€β”€ data/
β”‚   β”‚   └── grenhouse_model.tflite     # AI model for ESP32 (backup)
β”‚   β”œβ”€β”€ platformio.ini                 # PlatformIO configuration
β”‚   β”œβ”€β”€ diagram.json                   # Wokwi simulation diagram
β”‚   └── wokwi.toml                     # Wokwi project settings
β”œβ”€β”€ flutter_app/                       # Mobile application
β”‚   β”œβ”€β”€ lib/
β”‚   β”‚   β”œβ”€β”€ main.dart                  # Main Flutter app
β”‚   β”‚   β”œβ”€β”€ firebase_options.dart      # Firebase configuration
β”‚   β”‚   └── [models/screens/services/] # App architecture (future)
β”‚   β”œβ”€β”€ assets/
β”‚   β”‚   └── grenhouse_model.tflite     # AI model for mobile inference
β”‚   β”œβ”€β”€ android/                       # Android-specific configuration
β”‚   β”œβ”€β”€ pubspec.yaml                   # Flutter dependencies
β”‚   └── firebase.json                  # Firebase project settings
β”œβ”€β”€ docs/
β”‚   └── greenhouse.ipynb               # AI model training notebook
└── assets/                           # Additional project assets

🧠 AI Model Details

Training Data

  • Dataset Size: 17,521 samples
  • Features: Temperature (20.9Β°C - 90.5Β°C), Humidity (31.69% - 100%)
  • Target: Binary classification (Fan ON/OFF)
  • Training Method: Google Colab with TensorFlow

Model Architecture

model = Sequential([
    Dense(16, activation='relu', input_shape=(2,)),
    Dense(8, activation='relu'),
    Dense(1, activation='sigmoid')
])

Performance Metrics

  • Accuracy: 98% on test data
  • Model Size: 2KB (optimized for mobile)
  • Inference Time: <10ms on mobile device
  • Real-world Validation: Excellent uncertainty handling

Normalization (Important!)

# Input normalization used in training
temperature_normalized = (temp - 20.9) / (90.5 - 20.9)
humidity_normalized = (humidity - 31.69) / (100.0 - 31.69)

πŸ”§ Hardware Configuration

Wokwi Simulation (Default)

  • ESP32 DevKit V1
  • DHT22 Sensor β†’ GPIO 4
  • LED (Fan Indicator) β†’ GPIO 5
  • WiFi Connection β†’ Simulated

Physical Hardware Setup

ESP32 DevKit V1:
β”œβ”€β”€ DHT22 Sensor
β”‚   β”œβ”€β”€ VCC β†’ 3.3V
β”‚   β”œβ”€β”€ GND β†’ GND
β”‚   └── DATA β†’ GPIO 4
β”œβ”€β”€ Relay Module (Fan Control)
β”‚   β”œβ”€β”€ VCC β†’ 5V
β”‚   β”œβ”€β”€ GND β†’ GND
β”‚   └── IN β†’ GPIO 5
└── Power Supply β†’ USB/External 5V

πŸ”₯ Firebase Data Structure

Real-time Database Schema

{
  "climate_data": {
    "temperature_c": 25.8,
    "humidity_percent": 78.5,
    "timestamp": "1642678800",
    "fan_status": false,
    "last_updated": "2025-01-15T10:30:00Z"
  },
  "fan_on": true,
  "current_fan_status": false,
  "ai_predictions": {
    "last_confidence": 0.387,
    "last_decision": "OFF",
    "prediction_count": 1247
  }
}

Security Rules

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",
    "climate_data": {
      ".validate": "newData.hasChildren(['temperature_c', 'humidity_percent'])"
    }
  }
}

πŸ“± Flutter App Features

Main Dashboard

  • Real-time Sensor Data: Live temperature and humidity display
  • AI Prediction Status: Current confidence level and decision
  • Fan Control: Manual override toggle
  • Connection Status: ESP32 and Firebase connectivity indicators

AI Integration

  • On-device Inference: TensorFlow Lite model runs locally
  • Uncertainty Handling: Shows confidence levels (0.3-0.7 typical)
  • Smart Decisions: Appropriate hesitation in borderline conditions

User Interface

// Key UI Components
β”œβ”€β”€ Temperature Card β†’ Real-time display with trend
β”œβ”€β”€ Humidity Card β†’ Percentage with visual indicator  
β”œβ”€β”€ AI Status Card β†’ Prediction confidence and decision
β”œβ”€β”€ Fan Control Toggle β†’ Manual override capability
└── Connection Status β†’ System health indicators

πŸ” Troubleshooting

Common Issues

  1. ESP32 Won't Connect to WiFi:

    // Check config.h credentials
    // Verify WiFi network is 2.4GHz (not 5GHz)
    // Check serial monitor for connection attempts
  2. Firebase Authentication Fails:

    # Verify credentials in config.h
    # Check Firebase Console β†’ Authentication β†’ Users
    # Ensure email/password auth is enabled
  3. Flutter Build Errors:

    flutter clean
    flutter pub get
    flutter run
  4. AI Model Not Loading:

    # Verify grenhouse_model.tflite exists in flutter_app/assets/
    # Check pubspec.yaml has assets configuration
    # Confirm file path in main.dart

Performance Optimization

  1. ESP32 Memory Issues:

    • Monitor serial output for heap usage
    • Reduce Firebase update frequency if needed
    • Enable watchdog timer for stability
  2. Flutter Performance:

    • Use release build for production: flutter run --release
    • Monitor AI inference time in debug logs
    • Optimize Firebase listeners

πŸ“Š Performance Metrics

System Performance

  • Response Time: < 1 second from sensor to AI decision
  • Update Frequency: 10 seconds (configurable)
  • Memory Usage:
    • ESP32: 84% Flash, 14.8% RAM
    • Flutter: ~50MB with TensorFlow Lite
  • Power Consumption: Optimized with smart fan control

AI Model Performance

  • Training Accuracy: 98%
  • Real-world Confidence Range: 0.3-0.7 (realistic uncertainty)
  • Inference Speed: <10ms on mobile
  • Model Size: 2KB (efficient for IoT deployment)

🎯 Use Cases

Educational Applications

  • IoT Development: Complete embedded system with cloud integration
  • Machine Learning: Real-world AI deployment on mobile devices
  • Flutter Development: Professional mobile app with real-time features
  • Firebase Integration: Modern backend-as-a-service implementation

Practical Applications

  • Greenhouse Automation: Actual agricultural use
  • Home Automation: Smart ventilation control
  • Research Projects: Environmental monitoring system
  • Portfolio Projects: Demonstrates full-stack IoT capabilities

πŸš€ Future Enhancements

Potential Improvements

  • Multi-sensor Support: Add soil moisture, light sensors
  • Data Analytics: Historical trends and insights
  • Push Notifications: Alert system for critical conditions
  • Schedule Control: Time-based automation rules
  • Energy Monitoring: Track power consumption
  • Multiple Zones: Control multiple greenhouse sections

Advanced Features

  • Edge AI: Run AI model on ESP32 directly
  • Over-the-Air Updates: Remote firmware updates
  • Mesh Networking: Multiple ESP32 communication
  • Voice Control: Integration with smart assistants

πŸ“– Citation

If you use this project in your research or commercial applications, please cite:

Greenhouse AI Fan Controller
https://github.com/KDsudheera/greenhouse-ai-fancontroller
An intelligent IoT system using machine learning for greenhouse automation

🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ“ž Contact & Support

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸŽ‰ Acknowledgments

  • TensorFlow Team for TensorFlow Lite mobile inference
  • Firebase Team for real-time database services
  • Flutter Team for cross-platform mobile development
  • PlatformIO Team for embedded development platform
  • Wokwi Team for excellent hardware simulation

⭐ If This Project Helped You

If this project was useful for your learning or development:

  • ⭐ Star this repository
  • πŸ”„ Share with others interested in IoT + AI
  • πŸ› Report issues to help improve the project
  • 🀝 Contribute improvements or new features

Built with ❀️ for the IoT and AI community

"Smart agriculture starts with intelligent automation" πŸŒ±πŸ€–

About

🌱 Intelligent IoT greenhouse fan controller using AI/ML for automated climate control. Features ESP32 + DHT22 sensors, real-time Firebase integration, Flutter mobile app with TensorFlow Lite on-device inference, and Wokwi simulation. Complete full-stack solution demonstrating IoT + AI integration.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors