Dissolved Oxygen and Temperature using Arduino

From Sensors in Schools
Revision as of 19:37, 28 February 2024 by EdmondLascaris (talk | contribs)
Jump to navigation Jump to search

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")