tutoriales.com

Freshwater Aquarium Automation: Building an Arduino and Raspberry Pi Smart Tank

Discover how to transform your standard freshwater aquarium into an automated ecosystem. This comprehensive guide covers hardware selection, wiring, programming, and safety measures for monitoring and controlling your aquatic habitat.

Avanzado12 min read4 views
Report error

Introduction to Aquarium Automation 🌟

Maintaining a thriving freshwater aquarium requires consistency. From daily lighting schedules to precise temperature regulation and timed feeding, the manual upkeep can sometimes feel overwhelming. Automating these core systems not only saves time but also provides a more stable, stress-free environment for your fish and live plants. By combining the reliability of microcontrollers like Arduino with the processing power of a Raspberry Pi, you can build a custom, highly accurate smart aquarium controller tailored specifically to your setup.

In this tutorial, we will walk through the entire process of designing, building, and programming an automated freshwater aquarium system. Whether you want a sunrise-to-sunset lighting gradient, automated top-off systems, or remote temperature alerts, this guide gives you the blueprint to achieve professional-grade automation.


πŸ› οΈ Hardware Requirements and Materials

Before diving into construction, gathering the correct components is essential for safety and functionality. Aquarium environments involve water and electricity, meaning water-resistant sensors, isolated relays, and robust enclosures are non-negotiable.

Core Components List

ComponentPurposeSpecificationsEstimated Cost
Arduino Nano / MegaLocal sensor reading and actuator controlATmega328P or ATmega2560$5 - $25
Raspberry Pi 4Central dashboard, database, and web UI2GB to 4GB RAM model$45 - $65
DS18B20 SensorsWaterproof temperature monitoringStainless steel probe, waterproof$3 - $6
Real Time Clock (RTC)Accurate timekeeping during power lossDS3231 module with coin cell$4 - $8
4-Channel Relay ModuleSwitching high-voltage equipment (lights, pumps)5V relay board with optocoupler isolation$6 - $12
LCD Display (16x2)Local status and temperature readoutsI2C interface module attached$5 - $10
Peristaltic Pumps (12V)Automated liquid fertilizer or top-off dosingDC 12V stepper/gear motor$15 - $30 each
⚠️ Safety Warning: Always use optoisolated relay modules and waterproof probes. Keep all electronic connections away from water splashes, and use drip loops on all power cords.

πŸ“ System Architecture and Planning

Understanding how data flows through your smart aquarium is critical before plugging in any wires. The Arduino will sit at the edge, directly interfacing with physical sensors (like water temperature and float switches) and low-level actuators (such as heaters and powerheads). The Raspberry Pi acts as the brain, polling data from the Arduino, logging parameters to a database, and hosting a local web server for remote monitoring.

Smartphone Dashboard Local WiFi Router Raspberry Pi (System Hub & Server) Arduino Nano DS18B20 Temp Sensor Float Switches Relay Module WiFi WiFi USB / Serial GPIO / Data Lines

Key Responsibilities

  • Arduino: Real-time safety cutoffs, local display updates, precise PWM lighting fades, and immediate relay toggling.
  • Raspberry Pi: Long-term data logging, graphing historical trends, schedule management, and emergency push notifications.

πŸ”Œ Wiring and Circuit Assembly

Let's assemble the local sensor and control hub using the Arduino. We will wire the DS18B20 temperature sensor, the DS3231 Real-Time Clock, and a 4-channel relay module.

Step-by-Step Wiring Guide

Step 1: Power Setup: Connect the 5V and GND pins of the Arduino to a stable 5V external power supply, ensuring shared grounds across all modules.
Step 2: Temperature Sensor: Connect the DS18B20 data wire to Digital Pin 2 on the Arduino. Place a 4.7k ohm pull-up resistor between the 5V line and the data line.
Step 3: Real Time Clock: Connect the DS3231 module via I2C (SDA to Analog Pin 4, SCL to Analog Pin 5 on older boards, or dedicated SDA/SCL pins).
Step 4: Relay Board: Connect relay trigger pins (IN1 through IN4) to Arduino Digital Pins 4, 5, 6, and 7. Ensure the relay VCC is powered by an independent 5V source to prevent voltage drops.
πŸ“Œ Note: Double-check all pin configurations before applying mains power to relays. Never work on live 110V/220V circuits without disconnecting them from the wall outlet first.

πŸ’» Programming the Arduino Controller

Below is the foundational Arduino sketch that reads water temperature, checks safety thresholds, and responds to serial commands from the Raspberry Pi.

#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include <RTClib.h>

// Data wire is plugged into digital pin 2 on the Arduino
#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

RTC_DS3231 rtc;

// Relay control pins
const int heaterRelay = 4;
const int lightRelay = 5;
const int filterRelay = 6;
const int dosingRelay = 7;

// Target temperature in Celsius
const float targetTemp = 25.0;
const float tempTolerance = 0.5;

void setup() {
  Serial.begin(9600);
  sensors.begin();
  rtc.begin();

  pinMode(heaterRelay, OUTPUT);
  pinMode(lightRelay, OUTPUT);
  pinMode(filterRelay, OUTPUT);
  pinMode(dosingRelay, OUTPUT);

  // Ensure filters stay on by default
  digitalWrite(filterRelay, HIGH);
}

void loop() {
  // Request temperature readings
  sensors.requestTemperatures();
  float currentTemp = sensors.getTempCByIndex(0);

  // Temperature safety control
  if (currentTemp < (targetTemp - tempTolerance)) {
    digitalWrite(heaterRelay, HIGH); // Turn heater on
  } else if (currentTemp > (targetTemp + tempTolerance)) {
    digitalWrite(heaterRelay, LOW);  // Turn heater off
  }

  // Print telemetry for Raspberry Pi
  Serial.print("TEMP:");
  Serial.print(currentTemp);
  Serial.print("\n");

  // Check for incoming serial commands from Raspberry Pi
  if (Serial.available() > 0) {
    String command = Serial.readStringUntil('\n');
    command.trim();
    
    if (command == "LIGHT_ON") {
      digitalWrite(lightRelay, HIGH);
    } else if (command == "LIGHT_OFF") {
      digitalWrite(lightRelay, LOW);
    }
  }

  delay(2000);
}

🌐 Setting Up the Raspberry Pi Dashboard

With the Arduino managing real-time hardware safety, the Raspberry Pi will run a Python script using Flask and SQLite to log data and present a clean browser-based control panel.

Installing Python Dependencies

Open your Raspberry Pi terminal and install the required libraries for serial communication and web hosting:

sudo apt update && sudo apt upgrade -y
sudo apt install python3-pip python3-serial python3-flask -y

Python Flask Application Script

Create a file named app.py on your Raspberry Pi:

import serial
from flask import Flask, render_template_string, redirect, url_for

app = Flask(__name__)

# Configure serial port (adjust /dev/ttyUSB0 or /dev/ttyACM0 as needed)
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)

latest_temp = "Loading..."

@app.route('/')
Index():
    Global latest_temp
    If ser.in_waiting > 0:
        Line = ser.readline().decode('utf-8').strip()
        If line.startswith("TEMP:"):
            Latest_temp = line.split(":")[1]
            
    Template = '''
    <!doctype html>
    <html lang="en">
      <head>
        <title>Smart Aquarium Dashboard</title>
        <style>
          body { font-family: Arial, sans-serif; text-align: center; background: #f0f4f8; margin-top: 50px; }
          .card { background: white; padding: 20px; border-radius: 8px; display: inline-block; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
          .btn { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; text-decoration: none; display: inline-block; margin: 5px; }
          .btn-off { background: #dc3545; }
        </style>
      </head>
      <body>
        <div class="card">
          <h1>🐟 Smart Aquarium Controller</h1>
          <h2>Water Temperature: {{ temp }} &deg;C</h2>
          <p>
            <a href="/light/on" class="btn">Turn Lights ON</a>
            <a href="/light/off" class="btn btn-off">Turn Lights OFF</a>
          </p>
        </div>
      </body>
    </html>
    '''
    Return render_template_string(template, temp=latest_temp)

@app.route('/light/<state>')
Def control_light(state):
    If state == 'on':
        Ser.write(b'LIGHT_ON\n')
    Elif state == 'off':
        Ser.write(b'LIGHT_OFF\n')
    Return redirect(url_for('index'))

If __name__ == '__main__':
    App.run(host='0.0.0.0', port=5000, debug=False)

πŸ§ͺ Calibration, Testing, and Maintenance

Once your code is deployed and wiring is secured, thorough testing prevents catastrophic failures before livestock enters the tank.

Pre-Deployment Checklist

πŸ’‘ Tip: Always perform a "dry run" test in a bucket of tap water for at least 48 hours before installing any equipment into a fully stocked aquarium.
  • Temperature Accuracy: Compare your DS18B20 probe against a trusted glass aquarium thermometer.
  • Fail-Safe Testing: Unplug the temperature sensor while the system is running to verify that the heater relay defaults to the OFF position.
  • Power Outage Simulation: Unplug the main power supply and restore it to ensure the Real-Time Clock maintains the correct time and relays resume safe states.

πŸ” Frequently Asked Questions

What happens if the Raspberry Pi loses internet connection? The core automation loops run locally on the Arduino. Even if the Raspberry Pi or your home Wi-Fi network goes offline, the Arduino will continue monitoring water temperature and executing emergency safety cutoffs independently.
Can I add automated top-off (ATO) to this system? Yes! You can easily wire an optical or mechanical float switch to an available digital pin on the Arduino and connect a small 12V DC pump to the fourth relay channel to automatically replace evaporated water.
Is 12V safe around freshwater aquariums? Low voltage DC (12V or 5V) is vastly safer around water than mains electricity (110V/220V). However, always protect exposed solder joints with heat shrink tubing and marine-grade silicone potting compound to prevent electrolysis and corrosion.

Conclusion & Next Steps πŸš€

Congratulations! You have successfully built the foundation of an automated freshwater aquarium ecosystem. By blending microcontrollers with single-board computers, you now possess a custom dashboard to monitor water parameters and control lighting schedules remotely. From here, you can expand your system by adding pH probes, turbidity sensors, or automated fish feeders to achieve ultimate peace of mind.

Related tutorials

Comments (0)

No comments yet. Be the first!