#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#include <HX711.h> // For Load Cell
#include <ESP32Servo.h>
//#include <ESP8266WiFi.h>
// Pin Definitions
#define DHT_PIN 15
#define RELAY_WATER 12
#define RELAY_AUGER 14
#define RELAY_PRESSURE 25
#define LOAD_CELL_DOUT 2
#define LOAD_CELL_SCK 4
#define Servo_Pin 27
Servo servo;
float position = 0.0; // position of fifth servo motor
int direction = 1; // direction for fifth servo motor
// LCD Display (I2C)
LiquidCrystal_I2C lcd(0x27, 20, 4);
// Sensors and Load Cell
DHT dht(DHT_PIN, DHT22);
HX711 scale;
// Timer Variables
unsigned long lastFeedTime = 0;
const unsigned long feedInterval = 30 * 1000; // 1 hour in milliseconds
// Function Declarations
void dispenseFood();
void sprayWater();
void activatePressureJet();
void setup() {
Serial.begin(9600);
// Initialize LCD and Sensors
lcd.init();
lcd.backlight();
dht.begin();
scale.begin(LOAD_CELL_DOUT, LOAD_CELL_SCK);
// Relay Pins Setup
pinMode(RELAY_WATER, OUTPUT);
pinMode(RELAY_AUGER, OUTPUT);
pinMode(RELAY_PRESSURE, OUTPUT);
pinMode(Servo_Pin,OUTPUT);
// Initial State
digitalWrite(RELAY_WATER, LOW);
digitalWrite(RELAY_AUGER, LOW);
digitalWrite(RELAY_PRESSURE, LOW);
lcd.setCursor(0, 0);
lcd.print("Fish Feeder Init");
delay(2000);
servo.attach(Servo_Pin);
}
void loop() {
// Get current time
unsigned long currentTime = millis();
// Automatic Feeding every hour
if (currentTime - lastFeedTime >= feedInterval) {
for (int i = 0; i < 3; i++) {
dispenseFood();
sprayWater();
activatePressureJet();
}
lastFeedTime = currentTime;
}
// Update LCD
lcd.setCursor(0, 1);
lcd.print("Feeding...");
}
void dispenseFood() {
lcd.setCursor(0, 2);
lcd.print("Dispensing Food...");
digitalWrite(RELAY_AUGER, HIGH);
delay(5000); // Adjust this to match 10kg food dispense time
digitalWrite(RELAY_AUGER, LOW);
}
void sprayWater() {
lcd.setCursor(0, 2);
lcd.print("Spraying Water...");
digitalWrite(RELAY_WATER, HIGH);
delay(60000); // 1 minutes
digitalWrite(RELAY_WATER, LOW);
}
void activatePressureJet() {
lcd.setCursor(0, 2);
lcd.print("Activating Jet...");
digitalWrite(RELAY_PRESSURE, HIGH);
servomove();
delay(10000); // 10 seconds of jet activation
digitalWrite(RELAY_PRESSURE, LOW);
}
void servomove(){
// ------------------------------------------
// Servo motor 5
// Using math to slow down the servo near the endpoints.
// The position is a float variable to be able to move
// really slow near the endpoints.
// ------------------------------------------
//for (pos = 0; pos <= 180; pos += 1)
float step;
step = (90.0 - fabs(90.0 - position)) / 90.0;
step = 0.1 + (pow( step, 1.5) * 5); // make a steep curve, with 0.1 as minimum
if( direction > 0)
{
position += step;
if( position >= 180.0)
{
position = 180.0;
direction = -1;
}
}
else
{
position -= step;
if( position <= 0.0)
{
position = 0.0;
direction = 1;
}
}
int angle5 = int( position);
Serial.print("servo position ");
Serial.println(position);
servo.write( angle5);
}