|
arduino IDEArduino
|
|
|
Tuya IoT Platform |
|
|
Tuya_TYDA_Install_V2.4.0 |
AquaMon - Aquaponics and Fish Tank Monitoring with Tuya IoT
Introduction
Do you love sea creatures? I don't think I would find a single person who would not fall in love with sea animals. Vibrant, spectacular colours, textures all over their body adapted for camouflaging, adapting to sea conditions and for attraction. Though I never had a chance to take a deep dive into the seas or oceans and experience the beauty, I enjoy it every day with my pet fish and a small aquarium. ?? Fish are ideal pets for people who don’t have a lot of time or space for other common pets. Whenever I am sad or on a hunt for new ideas the best thing I do is, watch fish in the aquarium. It really helped me in improving stress and getting a joyful moment amidst all the busy schedules of the day during the Covid Pandemic. It is also scientifically proved- "The hypnotic effect of watching fish swimming back and forth helps children calm down and relax... Watching fish not only lowers blood pressure and heart rate but reduces stress and anxiety, improving mood and helping us to feel calm and relaxed. A natural and therapeutic tool to help children suffering from conditions such as ADHD and autism." So, when your marine friends add so much value to your life what are you waiting for, take care of them properly so that they can thrive. You don't need a big budget for that, it can be built easily with these cheap boards- Arduino UNO and ESP8266. I am also going to show you how easy and fun it is to build a cool internet-connected gadget and mobile app with the Tuya IoT Platform.
You might have come across several such IoT based aquarium monitoring projects from simple to advanced ones but I made this project to help people with no or lesser technical knowledge to set up one such aquarium IoT device with Android and iOS apps having secure authorization built-in support as well.
What is Tuya and Why?
Tuya is a leading global IoT Cloud Platform that connects the intelligent needs of brands, OEMs, developers, and retail chains. The platform provides developers with a one-stop IoT PaaS-level solution that contains hardware development tools, global cloud services, and smart business platform development, Tuyaoffering comprehensive ecosystem empowerment from technology to marketing channels to build the world’s leading IoT Cloud Platform. Tuya is open to all, join as a beta tester and developer with their recent Arduino Library and Tuya Development kits release. Sign up and join the Tuya Developer Arduino Beta Test
I decided to use the IoT platform because it is simple, powerful and can run on cheap modules like Esp8266. Also, the IoT platform gives you a drag-and-drop MIT app inventor like feature to build your own IoT android and iOS mobile app on the go. So, your prototype can be the next smarter IoT product with the platform.
For more details on Tuya, check out my previous project on Introduction to Tuya IoT platform: https://steptostem.com/2021/08/getting-started-with-arduino-iot-control-with-tuya-iot-platform/
Let's build it
Hardware:
There are 3 sensors available to measure the key parameters in the fish tank such as temperature, pH and TDS. In addition, you can add many different actuators to automate tasks such as heating or cooling the water, feeding the fish, activating the pumps for water change or medicines administration, and controlling the intensity of the light to simulate the day/night circles. I will go into detail in this article.
1 / 2
pH sensor: pH measures the acidity or alkalinity of water. A pH value of 7 is neutral, with lower numbers increasing in acidity and higher numbers increasing in alkalinity. Many fish can thrive in a range of pH conditions, typically spanning 6.5 to 7.5 pH. However, some fish require specific pH conditions outside this range. However, pH can drift over time, so testing aquarium water regularly is important. Most of the time, if left alone, pH levels will decrease over time due to the addition of acids into the water. Where could these acids be coming from?
Here are a few common sources:
1. Carbon dioxide in the air dissolving in the tank2. Tannins leeching into the water from plant matter3. Waste digesting bacteria acidifying the tank through the nitrogen cycle
Unfortunately, there are no visible indications that any change has taken place, so frequent monitoring is the only way to ensure that water remains healthy and inhabitable.
TDS Sensor: TDS measures the total dissolved solids of the solution or the concentration of dissolved solid particles. In general, the higher the TDS value, the more soluble solids dissolved in water, and the less clean the water is. Therefore, TDS can be used as one of the references for reflecting the cleanliness of the water.
Temperature Sensor: Aquarium temperature is often the first thing people test for in-home aquariums and is critical for maintaining healthy metabolic functions in fish. Most fish are poikilothermic (meaning they don't regulate internal body temperature) but rather they rely on their environment so the temperature is an important factor.
Step 1: Connecting all sensors and modules
Hardware connections are as follows.
1 / 6
Step 2: Creating a new product on Tuya
I am going to use the Tuya IoT platform to develop a smart device from scratch. The simplicity and fast response time of the Tuya IoT cloud are amazing, all you need to do is set up function definitions, design an app panel and burn authorization firmware and your device is ready to go with Tuya Android and iOS app. Check the flow of any Tuya Product development below.
Check below, the steps on creating a new product on the Tuya IoT platform, if you haven't registered yet, register here. Then, go to the Tuya IoT Platform and click: Create ? Can't find the category?
Enter the required product information:
Protocol ? Wi-Fi
Power Type ? Standard Power Consumption
Create custom function definitions for your sensors with the below-shown data type and properties. Select the features you want to add to your product from Standard functions or create new ones (Custom) if not supported by Standard functions.
Standard functions indicate the functions provided by Tuya for their product categories. Since there are lots of built-in products, it is easy to find the functions you need. Also, you can create your specialized functions named Custom functions, depending on your project.
The data point (DP) is the abstract representation of a function, and each function has an ID and data type.
Data Point ID (DP ID): indicates the code of a data point (function). Tuya Cloud sends or receives data through data point IDs. I create three custom DP for TDS, pH and temp sensors and one standard switch DP for controlling any actuators (you can add more switches to control actuators like fish feeders, buffer solutions pumps, and water cooling fans).
1 / 2
Select standard Tuya ESP8266 module SDK in the hardware development section.
Step 3: Designing App Panel for our AquaMon device
In the device panel, select Blank panel and let's customize and beautify it.
You would be able to see all your DP UI elements which you can modify. In fact, there are lots of UI available for you to drag-and-drop and make a fantastic panel. Once it's ready, click on the release button.
I have also added chart and log elements for greater data summarization.
Once your panel is released you should be able to see and use it by scanning through Tuya IoT app on mobile,
Step 4: Authorizing ESP8266 with Tuya IoT firmware
To be able to use the NodeMCU ESP8266 as a Tuya product for this project, you need to flash and authorize it with the required firmware. To authorize the ESP8266, you have to send the product ID (PID) and your Tuya IoT account name (e-mail) to devops@tuya.com. After a while, they will send you a Token ID. Then, follow the steps below:
First, go to the Tuya PMS service page https://pms.tuya.com/en/login.and sign up for an account if you don't have one. Then, go to Production Manage ?Work Order Management ? Activation Code Verification. To activate the production certificate for the product, enter the Token ID. When the Token ID is confirmed, the ESP8266 is ready to be flashed and authorized. Remember only once ID can authorize from a single account. To check your activated Tokens go to Activation Code List in the Production Manage -> Work Order Management list.
You can download the cloud auth token burning application from the PMS console Software Download section or Download the installations package on Google drive https://drive.google.com/file/d/1SF-rM5qDLaPJiuMHrkqFauVyRXSSHMkj/view?usp=sharingfrom Tuya ESP8266 guide (link in the reference section) and log in with your PMS account.
Set the baud rate and test baud as shown in the above image. Also, click on Enter Token button and enter the token you got from the Tuya devops@tuya.com email reply.
Now, connect the NodeMCU V3 LoLin ESP8266 to the computer via a USB cable and select its port number, such as COM5. If you did not use it with the Arduino IDE or other compilers before, you may need to install its driver.Finally, click on flash to burn auth tokens. You would see a green box with success if nothing breaks.
Step 5: Programming and flashing Arduino
I will make this part simpler by going into details of the Tuya IoT Arduino library. First, import all required libraries to work with sensors and ESP8266 over Serial. Setup Tuya Serial connection,
SoftwareSerial conn(10, 11); // RX, TX
TuyaWifi my_device(&conn);
/* Current LED status */
unsigned char led_state = 0;
/* Connect network button pin */
int key_pin = 7;
Define and store all DP ids we made on the Tuya IoT platform while creating our new device.
/* Data point define */
#define DPID_Switch 101
#define DPID_Ph_Sensor_Data 112
#define DPID_TDS_Sensor_Data 113
#define DPID_Water_Temperature 114
/* Stores all DPs and their types. PS: array[][0]:dpid, array[][1]:dp type.
* dp type(TuyaDefs.h) : DP_TYPE_RAW,
* DP_TYPE_BOOL, DP_TYPE_VALUE, DP_TYPE_STRING, DP_TYPE_ENUM, DP_TYPE_BITMAP
*/
unsigned char dp_array[][2] =
{
{DPID_Switch, DP_TYPE_BOOL},
{DPID_Ph_Sensor_Data, DP_TYPE_VALUE},
{DPID_TDS_Sensor_Data, DP_TYPE_VALUE},
{DPID_Water_Temperature, DP_TYPE_VALUE},
};
Fill your PID from Tuya IoT console and firmware version like shown below,
unsigned char pid[] = {"2dhjbzgya8mk2sv3"};
unsigned char mcu_ver[] = {"3.1.4"};
In void setup( ) let us initialize all callbacks to the Tuya IoT cloud,
void setup()
{
Serial.begin(9600);
conn.begin(9600);
pinMode(key_pin, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
//Enter the PID and MCU software version
my_device.init(pid, mcu_ver);
//incoming all DPs and their types array, total DPs created (quantity)
my_device.set_dp_cmd_total(dp_array, 4);
//register DP download processing callback function
my_device.dp_process_func_register(dp_process);
//register upload all DP callback function
my_device.dp_update_all_func_register(dp_update_all);
delay(300);
last_time = millis();
}
In the loop part, we need to start the uart service to allow Arduino to receive and send data to ESP8266 over serial and ESP8266 in turn sends it to the Tuya IoT cloud.
First, check if the device is in network mode or not and connected to the cloud or not, you would be able to see the status via led, if led is stable it means it is connected to the cloud, if blinking it means in connection mode.
void loop(){
my_device.uart_service();
//Enter the connection network mode when Pin7 is pressed.
if (digitalRead(key_pin) == LOW) {
delay(80);
if (digitalRead(key_pin) == LOW) {
my_device.mcu_set_wifi_mode(SMART_CONFIG);
}
}
/* LED blinks when network is being connected */
if ((my_device.mcu_get_wifi_work_state() != WIFI_LOW_POWER) &&
(my_device.mcu_get_wifi_work_state() != WIFI_CONN_CLOUD) &&
(my_device.mcu_get_wifi_work_state() != WIFI_SATE_UNKNOW)) {
if (millis()- last_time >= 500) {
last_time = millis();
if (led_state == LOW) {
led_state = HIGH;
} else {
led_state = LOW;
}
digitalWrite(LED_BUILTIN, led_state);
}
}
Now, implement your program logic to send data to Tuya IoT cloud and App Panelmcu_dp_update(DPID, value, 1), send your data values like this if the device is connected to the cloud.
phVal = calcPhVal();
tdsVal = calcTDSVal();
wTemp = waterTemp();
/* report the pH, TDS and temperature data */
if ((my_device.mcu_get_wifi_work_state() == WIFI_CONNECTED) || (my_device.mcu_get_wifi_work_state() == WIFI_CONN_CLOUD))
{
my_device.mcu_dp_update(DPID_Switch, true, 1);
my_device.mcu_dp_update(DPID_Ph_Sensor_Data, phVal, 1);
my_device.mcu_dp_update(DPID_TDS_Sensor_Data, tdsVal, 1);
my_device.mcu_dp_update(DPID_Water_Temperature, wTemp, 1);
}
delay(500);
}
We also have the dp_process() function but it is to be used when you want to receive commands and take control over Arduino pins, like controlling actuators, just implement a switch case and do required actions based on the triggered char dpid value. Check the previous tutorial here on the usage of dp_process(),
/**
* @description: DP download callback function.
* @param {unsigned char} dpid
* @param {const unsigned char} value
* @param {unsigned short} length
* @return {unsigned char}
*/
unsigned char dp_process(unsigned char dpid,const unsigned char value[], unsigned short length){
/* all DP only report, if you want to take actions based upon user interactions with app modify dp_process*/
return SUCCESS;
}
At last update all values, it ensures that all your data values are updated continuously, you can try skipping mcu_dp_update(DPID, value, 1) in void loop() since we already got a dp_update_all() function running continuously to update all values but make sure those variables are global.
/**
* @description: Upload all DP status of the current device.
* @param {*}
* @return {*}
*/
void dp_update_all(void)
{
my_device.mcu_dp_update(DPID_Switch, true, 1);
my_device.mcu_dp_update(DPID_Ph_Sensor_Data, phVal, 1);
my_device.mcu_dp_update(DPID_TDS_Sensor_Data, tdsVal, 1);
my_device.mcu_dp_update(DPID_Water_Temperature, wTemp, 1);
}
Let's have a look at the app, it's amazing and so simple with Tuya to build your own smart IoT gadgets.
1 / 2
References:
Firmware burning guide: GitHub - GITOLEO/Tuya-ESP8266-firmware-burningauthorizations-guide
/**
* Project: AquaMon (Aquarium Monitoing to help you understand your marine friends needs)
* Author: Sumit
**/
#include <OneWire.h>
#include <DallasTemperature.h>
#include <TuyaWifi.h>
#include <SoftwareSerial.h>
// Data wire is plugged into digital pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire device
OneWire oneWire(ONE_WIRE_BUS);
// Pass oneWire reference to DallasTemperature library
DallasTemperature sensors(&oneWire);
#define PHPin A2 //pH meter Analog output to Arduino Analog Input 0
#define Offset 41.02740741 //deviation compensate
#define samplingInterval 20
#define publishInterval 500
#define ArrayLenth 40 //times of collection
int pHArray[ArrayLenth]; //Store the average value of the sensor feedback
int pHArrayIndex = 0;
#define TDSPin A3
SoftwareSerial conn(10, 11); // RX, TX
TuyaWifi my_device(&conn);
/* Current LED status */
unsigned char led_state = 0;
/* Connect network button pin */
int key_pin = 7;
/* Data point define */
#define DPID_Switch 101
#define DPID_Ph_Sensor_Data 112
#define DPID_TDS_Sensor_Data 113
#define DPID_Water_Temperature 114
/* Stores all DPs and their types. PS: array[][0]:dpid, array[][1]:dp type.
* dp type(TuyaDefs.h) : DP_TYPE_RAW,
* DP_TYPE_BOOL, DP_TYPE_VALUE, DP_TYPE_STRING, DP_TYPE_ENUM, DP_TYPE_BITMAP
*/
unsigned char dp_array[][2] =
{
{DPID_Switch, DP_TYPE_BOOL},
{DPID_Ph_Sensor_Data, DP_TYPE_VALUE},
{DPID_TDS_Sensor_Data, DP_TYPE_VALUE},
{DPID_Water_Temperature, DP_TYPE_VALUE},
};
unsigned char pid[] = {"2dhjbzgya8mk2sv3"};
unsigned char mcu_ver[] = {"3.1.4"};
/* last time */
unsigned long last_time = 0;
int phVal = 0;
int tdsVal = 0;
int wTemp = 0;
void setup()
{
Serial.begin(9600);
conn.begin(9600);
sensors.begin(); // Start up the library
//Initialize networking keys.
pinMode(key_pin, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
//Enter the PID and MCU software version
my_device.init(pid, mcu_ver);
//incoming all DPs and their types array, DP numbers
my_device.set_dp_cmd_total(dp_array, 4);
//register DP download processing callback function
my_device.dp_process_func_register(dp_process);
//register upload all DP callback function
my_device.dp_update_all_func_register(dp_update_all);
delay(300);
last_time = millis();
}
void loop()
{
my_device.uart_service();
//Enter the connection network mode when Pin7 is pressed.
if (digitalRead(key_pin) == LOW) {
delay(80);
if (digitalRead(key_pin) == LOW) {
my_device.mcu_set_wifi_mode(SMART_CONFIG);
}
}
/* LED blinks when network is being connected */
if ((my_device.mcu_get_wifi_work_state() != WIFI_LOW_POWER) &&
(my_device.mcu_get_wifi_work_state() != WIFI_CONN_CLOUD) &&
(my_device.mcu_get_wifi_work_state() != WIFI_SATE_UNKNOW)) {
if (millis()- last_time >= 500) {
last_time = millis();
if (led_state == LOW) {
led_state = HIGH;
} else {
led_state = LOW;
}
digitalWrite(LED_BUILTIN, led_state);
}
}
phVal = calcPhVal();
tdsVal = calcTDSVal();
wTemp = waterTemp();
/* report the pH, TDS and temperature data */
if ((my_device.mcu_get_wifi_work_state() == WIFI_CONNECTED) || (my_device.mcu_get_wifi_work_state() == WIFI_CONN_CLOUD))
{
my_device.mcu_dp_update(DPID_Switch, true, 1);
my_device.mcu_dp_update(DPID_Ph_Sensor_Data, phVal, 1);
my_device.mcu_dp_update(DPID_TDS_Sensor_Data, tdsVal, 1);
my_device.mcu_dp_update(DPID_Water_Temperature, wTemp, 1);
}
delay(500);
}
/**
* @description: DP download callback function.
* @param {unsigned char} dpid
* @param {const unsigned char} value
* @param {unsigned short} length
* @return {unsigned char}
*/
unsigned char dp_process(unsigned char dpid,const unsigned char value[], unsigned short length){
/* all DP only report, if you want to take actions based upon user interactions with app modify dp_process*/
return SUCCESS;
}
/**
* @description: Upload all DP status of the current device.
* @param {*}
* @return {*}
*/
void dp_update_all(void)
{
my_device.mcu_dp_update(DPID_Switch, true, 1);
my_device.mcu_dp_update(DPID_Ph_Sensor_Data, phVal, 1);
my_device.mcu_dp_update(DPID_TDS_Sensor_Data, tdsVal, 1);
my_device.mcu_dp_update(DPID_Water_Temperature, wTemp, 1);
}
double avergearray(int* arr, int number) {
int i;
int max, min;
double avg;
long amount = 0;
if (number <= 0) {
//Serial.println("Error number for the array to avraging!/n");
return 0;
}
if (number < 5) { //less than 5, calculated directly statistics
for (i = 0; i < number; i++) {
amount += arr[i];
}
avg = amount / number;
return avg;
} else {
if (arr[0] < arr[1]) {
min = arr[0]; max = arr[1];
}
else {
min = arr[1]; max = arr[0];
}
for (i = 2; i < number; i++) {
if (arr[i] < min) {
amount += min; //arr<min
min = arr[i];
} else {
if (arr[i] > max) {
amount += max; //arr>max
max = arr[i];
} else {
amount += arr[i]; //min<=arr<=max
}
}//if
}//for
avg = (double)amount / (number - 2);
}//if
return avg;
}
double calcPhVal()
{
static unsigned long samplingTime = millis();
static unsigned long publishTime = millis();
static float pHValue, voltage;
if (millis() - samplingTime > samplingInterval)
{
pHArray[pHArrayIndex++] = analogRead(PHPin);
if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
voltage = avergearray(pHArray, ArrayLenth) * 5.0 / 1024;
pHValue = -19.18518519 * voltage + Offset;
samplingTime = millis();
}
if (millis() - publishTime > publishInterval) //Every 800 milliseconds, publish value
{
Serial.print("Voltage:");
Serial.print(voltage, 2);
Serial.print(" pH value: ");
Serial.println(pHValue, 2);
publishTime = millis();
return pHValue;
}
}
double calcTDSVal()
{
int sensorValue = analogRead(TDSPin);
float Voltage = sensorValue*5/1024.0; //Convert analog reading to Voltage
float tdsValue=(133.42/Voltage*Voltage*Voltage - 255.86*Voltage*Voltage + 857.39*Voltage)*0.5; //Convert voltage value to TDS value
Serial.print("TDS Value = ");
Serial.print(tdsValue);
Serial.println(" ppm");
delay(100);
return tdsValue;
}
double waterTemp()
{
sensors.requestTemperatures();
float wTemp = sensors.getTempCByIndex(0);
Serial.print("temp: ");
Serial.println(wTemp);
delay(100);
return wTemp;
}
AquaMon - Aquaponics and Fish Tank Monitoring with Tuya IoT
- Comments(0)
- Likes(3)
- 0 USER VOTES
- YOUR VOTE 0.00 0.00
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
More by vilaksh01
- Predictive Maintenance Of Compressor Water Pumps An ordinary resident of a metropolis rarely thinks about how water enters taps or central heating pi...
- Unlock Passwords With Tinyml-based Digit Recognition Story? IntroductionThe active development of smart gadgets with touch interfaces is trending nowaday...
- Handmade Drawing Recognition Interface As From My Smartphone StoryIntroductionI was inspired by such features on our smartphones. My smartphone “Vivo V7” has a f...
- Recognizing MNIST-based Handwritten Digits on M5Stack Core2 IntroductionIn my previous experiment, I had great fun adding handmade drawing gestures for our M5St...
- Tuya Link SDK IoT Smart Environment Sensing And Humidifier IntroductionI had been exploring the Tuya IoT platform for the past few months and they never fail t...
- Tuya IoT Cloud Smart Weather Lamp IntroductionHello everybody, ever felt like having a smart home device to visually show/signal you t...
- Getting Started With Arduino IoT Control With Tuya Introduction:I have always enjoyed using Arduino UNO since it was my first programmable board but it...
- Coronavirus - India cases tracker Today everyone is gazing at their phone to keep track of the coronavirus in their country but we ten...
- CliSensio - Climate Sensing and Insect Infestation Control Overview:Climate Change, is a highly debated high school topic, but do we really care about it? We s...
- AI For truck APS Failure Detection on a $4 MCU IntroductionThe automotive industry is among the pioneers to adopt cutting-edge technologies, machin...
- New Era Farming with TensorFlow on Lowest Power Consumption Overview:This project demonstrates how to build a device using TensorFlow and Artemis module to solv...
- TinyML Gearbox Fault Prediction on a $4 MCU StoryIs it possible to make an AI-driven system that predicts gearbox failure on a simple $4 MCU? Ho...
- AREC - Agricultural Records On Electronic Contracts Objective:One of the biggest reasons behind the growth of fake products in the agrochemical industry...
- AquaMon - Aquaponics and Fish Tank Monitoring with Tuya IoT IntroductionDo you love sea creatures? I don't think I would find a single person who would not fall...
-
-
-
kmMiniSchield MIDI I/O - IN/OUT/THROUGH MIDI extension for kmMidiMini
124 0 0 -
DIY Laser Power Meter with Arduino
173 0 2 -
-
-
Box & Bolt, 3D Printed Cardboard Crafting Tools
163 0 2 -