Sending Aquarium Data via Serial to Raspberry Pi: Difference between revisions
Jump to navigation
Jump to search
(Created page with "= Python - Splitting Data and Try and Except Statements = <syntaxhighlight lang="python"> #!/usr/bin/env python3 # dweet data import serial import datetime import time import requests if __name__ == '__main__': ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1) ser.reset_input_buffer() while True: time.sleep(0.1) if ser.in_waiting > 0: line = ser.readline().decode('utf-8').rstrip() print(f"Data separated using comm...") |
|||
| Line 1: | Line 1: | ||
= Python | = Python code to receive Arduino Data = | ||
* This python code receives data from the Arduino, saves and Dweets the data. | |||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
Revision as of 09:33, 8 November 2023
Python code to receive Arduino Data
- This python code receives data from the Arduino, saves and Dweets the data.
#!/usr/bin/env python3
# dweet data
import serial
import datetime
import time
import requests
if __name__ == '__main__':
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
ser.reset_input_buffer()
while True:
time.sleep(0.1)
if ser.in_waiting > 0:
line = ser.readline().decode('utf-8').rstrip()
print(f"Data separated using commas {line.split(',')}")
mylist = line.split(',')
try:
salinity = float(mylist[0])
pH = float(mylist[1])
phosphate = float(mylist[2])
ammonium = float(mylist[3])
nitrite = float(mylist[4])
nitrate = float(mylist[5])
temperature = float(mylist[6])
distance = float(mylist[7])
except:
salinity = 0.0
pH = 0.0
phosphate = 0.0
ammonium = 0.0
nitrite = 0.0
nitrate = 0.0
temperature = 0.0
distance = 0.0
print(f'salinity is {salinity} and pH is {pH}')
print(f'phosphate is {phosphate} and ammonium is {ammonium}')
print(f'nitrite is {nitrite} and nitrate is {nitrate}')
print(f'temperature is {temperature} and distance is {distance}')
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({"salinity": str(salinity)})
dweet_dict.update({"pH": str(pH)})
dweet_dict.update({"phosphate": str(phosphate)})
dweet_dict.update({"ammonium": str(ammonium)})
dweet_dict.update({"nitrite": str(nitrite)})
dweet_dict.update({"nitrate": str(nitrate)})
dweet_dict.update({"temperature": str(temperature)})
dweet_dict.update({"distance": str(distance)})
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")
# check dweet with - https://dweet.io/get/latest/dweet/for/3083-Bundoora-aquarium1