Dissolved Oxygen and Temperature using Arduino: Difference between revisions

From Sensors in Schools
Jump to navigation Jump to search
Line 375: Line 375:




== Arduino code DO and temperature
== Arduino code DO and temperature ==


<syntaxhighlight lang="c++">
<syntaxhighlight lang="c++">
Line 429: Line 429:
   }
   }


}</syntaxhighlight>  
}
 
</syntaxhighlight>


== Arduino code EC ==
== Arduino code EC ==

Revision as of 06:20, 8 March 2024

References

Arduino Code - Temperature data

  • Code executed using Cron
#!/usr/bin/env python3
# dweet data
import serial
import datetime
import time
import requests
import pandas as pd
import plotly.express as px

count = 0

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
    ser.reset_input_buffer()
    while count < 5:
        time.sleep(1)
        count += 1
        print(f'count is {count}')
        if ser.in_waiting > 0:
            print("Serial")
            line = ser.readline().decode('utf-8').rstrip()
            print(line)
            #print(f"Data separated using commas {line.split(',')}")
            #mylist = line.split(',')
            try:
                aq_temp = str(line)


            except:
                aq_temp = 0.0


            print(f'temperature is {aq_temp}')

            time.sleep(1)
            now = datetime.datetime.now()
            date_stamp = now.strftime("%Y-%m-%d %H:%M:%S")

            data = ""
            data = date_stamp + "," + str(line) + '\n'
            print(f'The data is =  {data}')

            f = open('/home/pi/Aquarium/aquarium_data.txt','a')
            f.write(data)
            f.close()
            print("Data saved")
      
            try:
                print("Preparing dweet")
                dweet_dict = {}
                dweet_dict.update({"aq_temp": str(aq_temp)})
                dweet_dict.update({"time": str(date_stamp)})
                url = "https://dweet.io/dweet/for/MPPS-Mernda-STEM-aquarium-4?"
                x = requests.post(url, json=dweet_dict)
                print(x.text)
                count = 6
            except:
                print("Dweet failed")
            # check dweet with - https://dweet.io/get/latest/dweet/for/3083-Bundoora-aquarium1
            
            
# Step 2: Read the data from the text file into a Pandas DataFrame
data = pd.read_csv('/home/pi/Aquarium/aquarium_data.txt')

# Step 3: Create a Plotly figure with two scatter plots
fig = px.scatter(data, x='datetime', y=['temperature'],
                 labels={'datetime': 'Date and Time', 'value': 'Temperature (°C)'},
                 title='Aquarium temperature')

# Step 4: Customize the plot layout
fig.update_layout(xaxis_title='Date and Time', yaxis_title='Temperature (°C)')

# Step 5: Save the plot as an HTML file
fig.write_html('/home/pi/Aquarium/temperature_plot_aquarium.html')

print("Aquarium plot saved as temperature_plot.html")

Arduino Code

  • Monitoring temperature and Dissolved Oxygen
  • Atlas sensor for Dissolved Oxygen
  • Onewire temperature sensor
#include <SoftwareSerial.h>                          
#include <OneWire.h>
#include <DallasTemperature.h>
#define rx 10                                          //define what pin rx is going to be
#define tx 11                                          //define what pin tx is going to be
#define ONE_WIRE_BUS 4               // Data wire is conntec to the Arduino digital pin 4

SoftwareSerial myserialDO(rx, tx);                      //define how the soft serial port is going to work

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature tempSensor(&oneWire);


String inputstring = "";                              //a string to hold incoming data from the PC
String sensorstring = "";                             //a string to hold the data from the Atlas Scientific product

void setup() {                                        //set up the hardware
  Serial.begin(9600);                                 //set baud rate for the hardware serial port_0 to 9600
  myserialDO.begin(9600);                               //set baud rate for the software serial port to 9600
  sensorstring.reserve(30);                           //set aside some bytes for receiving data from Atlas Scientific product
}


void loop() {                                         //here we go...


  if (myserialDO.available() > 0) {                     //if we see that the Atlas Scientific product has sent a character
    
    char inchar = (char)myserialDO.read();              //get the char we just received

    if (inchar == '\r') {                             //if the incoming character is a <CR>

      // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
      tempSensor.requestTemperatures(); 
      float temperatureValue = tempSensor.getTempCByIndex(0);
      Serial.print(sensorstring);                     
      Serial.print(",");
      Serial.println(String(temperatureValue, 1)); // Print with 1 decimal places
      sensorstring = "";
      delay(1000); // Delay for stability
    }
    else {
       sensorstring += inchar;                           //add the char to the var called sensorstring
    }
  }

}

Python code to read Temp and Dissolved Oxygen data

  • Code running constantly in the background
#!/usr/bin/env python3
# dweet data
import serial
import datetime
import time
import requests
import pandas as pd
import plotly.express as px

count = 0

if __name__ == '__main__':
    ser = serial.Serial('/dev/ttyUSB1', 9600, timeout=1)
    ser.reset_input_buffer()
    while True:
        count = count + 1
        time.sleep(0.1)
        if ser.in_waiting > 0:
            try:
                line = ser.readline().decode('utf-8').rstrip()
            except:
                line = "0,0"
            print(f"Data separated using commas {line.split(',')}")
            mylist = line.split(',')
            print(f'My list {mylist}')
            try:
                dissolvedOxygen = float(mylist[0])
                temperature = float(mylist[1])


            except:
                dissolvedOxygen = 0.0
                temperature = 0.0


            print(f'dissolvedOxygen is {dissolvedOxygen} and temp is {temperature}')

            
            time.sleep(1)
            
            now = datetime.datetime.now()
            date_stamp = now.strftime("%Y-%m-%d %H:%M:%S")

            data = ""
            data = date_stamp + "," + str(dissolvedOxygen) + "," + str(temperature) + '\n'
            print(f'The data is =  {data}')

            if count > 2000:
                f = open('/home/pi/Aquarium/aquarium_DO_temp.txt','a')
                f.write(data)
                f.close()
                print("Data saved")
      
                try:
                    print("Preparing dweet")
                    dweet_dict = {}
                    dweet_dict.update({"dissolvedOx": str(dissolvedOxygen)})
                    dweet_dict.update({"temp": str(temperature)})

                    dweet_dict.update({"time": str(date_stamp)})
                    url = "https://dweet.io/dweet/for/3083-Bundoora-aquarium1?"
                    x = requests.post(url, json=dweet_dict)
                    print(x.text)
                except:
                    print("Dweet failed")
                count = 0
                # check dweet with - https://dweet.io/get/latest/dweet/for/3083-Bundoora-aquarium1
                
                # Step 2: Read the data from the text file into a Pandas DataFrame
                data = pd.read_csv('/home/pi/Aquarium/aquarium_DO_temp.txt')

                # Step 3: Create a Plotly figure with two scatter plots
                fig = px.scatter(data, x='datetime', y=['temperature','dissolvedOxygen'],
                                 labels={'datetime': 'Date and Time', 'value': 'Temperature (°C)'},
                                 title='Aquarium temperature and DO')

                # Step 4: Customize the plot layout
                fig.update_layout(xaxis_title='Date and Time', yaxis_title='Temperature (°C)')

                # Step 5: Save the plot as an HTML file
                fig.write_html('/home/pi/Aquarium/temperature_plot_DO_aquarium.html')

                print("Aquarium plot saved as temperature_plot.html")


Python code DO EC temp and Chem

#!/usr/bin/env python3
# dweet data
import serial
import datetime
import time
import requests
import pandas as pd
import plotly.express as px
from water_variables import *

count = 0
conductivity = 0.0

if __name__ == '__main__':
    # dissolved oxygen
    ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
    ser.reset_input_buffer()
    
    # conductivity
    serEC = serial.Serial('/dev/ttyUSB1', 9600, timeout=1)
    serEC.reset_input_buffer()
    
    while True:
        count = count + 1
        time.sleep(0.1)
        
        if serEC.in_waiting > 0:
            time.sleep(0.1)
            try:
                lineEC = serEC.readline().decode('utf-8').rstrip()
                #print(f'line {lineEC}')
            except:
                lineEC = "0"    
            try:
                conductivity = lineEC

            except:
                conductivity = 0.0
            print(f'Conductivity is {conductivity}')
            print(f'pH is {pH}')
            print(f'count is {count}')
            
        
        if ser.in_waiting > 0:
            time.sleep(0.1)
            try:
                line = ser.readline().decode('utf-8').rstrip()
            except:
                line = "0,0"
            #print(f"Data separated using commas {line.split(',')}")
            mylist = line.split(',')
            #print(f'My list {mylist}')
            try:
                dissolvedOxygen = float(mylist[0])
                temperature = float(mylist[1])


            except:
                dissolvedOxygen = 0.0
                temperature = 0.0
                
            now = datetime.datetime.now()
            date_stamp = now.strftime("%Y-%m-%d %H:%M:%S")

            print(f'dissolvedOxygen - {dissolvedOxygen}, temp - {temperature}, time - {date_stamp}')
            print()

            time.sleep(0.3)
            
            now = datetime.datetime.now()
            date_stamp = now.strftime("%Y-%m-%d %H:%M:%S")

            data = ""
            data = date_stamp + "," + str(dissolvedOxygen) + "," + str(temperature) + "," + str(conductivity) + "," +\
                   str(pH) + "," + str(ammonia) + "," + str(nitrite) + "," + \
                   str(nitrate) + '\n'
            #print(f'The data is =  {data}')

            if count > 3000 and dissolvedOxygen != 0:
                f = open('/home/pi/Aquarium/aquarium_DO_EC_temp_chem.txt','a')
                f.write(data)
                f.close()
                print("Data saved")
      
                try:
                    print("Preparing dweet")
                    dweet_dict = {}
                    dweet_dict.update({"disOx": str(dissolvedOxygen)})
                    dweet_dict.update({"temp": str(temperature)})
                    dweet_dict.update({"cond": str(conductivity)})
                    dweet_dict.update({"pH": str(pH)})
                    dweet_dict.update({"amm": str(ammonia)})
                    dweet_dict.update({"nitrite": str(nitrite)})
                    dweet_dict.update({"nitrate": str(nitrate)})
                    dweet_dict.update({"time": str(date_stamp)})
                    url = "https://dweet.io/dweet/for/3083-Bundoora-aquarium1?"
                    #https://dweet.io/get/latest/dweet/for/3083-Bundoora-aquarium1?
                    x = requests.post(url, json=dweet_dict)
                    print(x.text)
                except:
                    print("Dweet failed")
                count = 0
                # check dweet with - https://dweet.io/get/latest/dweet/for/3083-Bundoora-aquarium1
                
                # Step 2: Read the data from the text file into a Pandas DataFrame
                data = pd.read_csv('/home/pi/Aquarium/aquarium_DO_EC_temp_chem.txt')

                # Step 3: Create a Plotly figure with two scatter plots
                fig = px.scatter(data, x='datetime', y=['temperature','dissolvedOxygen'],
                                 labels={'datetime': 'Date and Time', 'value': 'Temperature (°C)'},
                                 title='Aquarium temperature and DO')

                # Step 4: Customize the plot layout
                fig.update_layout(xaxis_title='Date and Time', yaxis_title='Temperature (°C)')

                # Step 5: Save the plot as an HTML file
                fig.write_html('/home/pi/Aquarium/temperature_plot_DO_EC_chem_aquarium.html')

                print("Aquarium plot saved as temperature_plot.html")

Python code - Chem variables

# water_variables.py file from which variables to be imported 
pH = 7.0
ammonia = 0.0
nitrite = 0.25
nitrate = 10.0


Arduino code DO and temperature

#include <SoftwareSerial.h>                          
#include <OneWire.h>
#include <DallasTemperature.h>
#define rx 10                                          //define what pin rx is going to be
#define tx 11                                          //define what pin tx is going to be
#define ONE_WIRE_BUS 4               // Data wire is conntec to the Arduino digital pin 4

SoftwareSerial myserialDO(rx, tx);                      //define how the soft serial port is going to work

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature sensor 
DallasTemperature tempSensor(&oneWire);


String inputstring = "";                              //a string to hold incoming data from the PC
String sensorstring = "";                             //a string to hold the data from the Atlas Scientific product

void setup() {                                        //set up the hardware
  Serial.begin(9600);                                 //set baud rate for the hardware serial port_0 to 9600
  myserialDO.begin(9600);                               //set baud rate for the software serial port to 9600
  sensorstring.reserve(30);                           //set aside some bytes for receiving data from Atlas Scientific product
}


void loop() {                                         //here we go...


  if (myserialDO.available() > 0) {                     //if we see that the Atlas Scientific product has sent a character
    
    char inchar = (char)myserialDO.read();              //get the char we just received

    if (inchar == '\r') {                             //if the incoming character is a <CR>

      // Call sensors.requestTemperatures() to issue a global temperature and Requests to all devices on the bus
      tempSensor.requestTemperatures(); 
      float temperatureValue = tempSensor.getTempCByIndex(0);
      Serial.print(sensorstring);                     
      Serial.print(",");
      Serial.println(String(temperatureValue, 1)); // Print with 1 decimal places
      sensorstring = "";
      delay(50); // Delay for stability
    }
    else {
       sensorstring += inchar;                           //add the char to the var called sensorstring
    }
    delay(50);
  }

}

Arduino code EC

//This code was written to be easy to understand.
//Modify this code as you see fit.
//This code will output data to the Arduino serial monitor.
//Type commands into the Arduino serial monitor to control the EC circuit.
//This code was written in the Arduino 2.0 IDE
//This code was last tested 10/2022


#include <SoftwareSerial.h>                           //we have to include the SoftwareSerial library, or else we can't use it
#define rx 2                                          //define what pin rx is going to be
#define tx 3                                          //define what pin tx is going to be

SoftwareSerial myserialEC(rx, tx);                      //define how the soft serial port is going to work


String inputstring = "";                              //a string to hold incoming data from the PC
String sensorstring = "";                             //a string to hold the data from the Atlas Scientific product
boolean input_string_complete = false;                //have we received all the data from the PC
boolean sensor_string_complete = false;               //have we received all the data from the Atlas Scientific product




void setup() {                                        //set up the hardware
  Serial.begin(9600);                                 
  myserialEC.begin(9600);
  delay(500);                            

  inputstring.reserve(10);                            //set aside some bytes for receiving data from the PC
  sensorstring.reserve(30);
  myserialEC.println("K,0.1");  //set conductivit probe to K0.1 
  
}


void loop() {                                         //here we go...


  if (myserialEC.available() > 0) {                     //if we see that the Atlas Scientific product has sent a character
    char inchar = (char)myserialEC.read();              //get the char we just received
    sensorstring += inchar;                           //add the char to the var called sensorstring
    if (inchar == '\r') {                             //if the incoming character is a <CR>
      sensor_string_complete = true;                  //set the flag
      Serial.println(sensorstring);                   //send that string to the PC's serial monitor


      sensorstring = "";                                //clear the string
      sensor_string_complete = false; 
    }
  }

}