Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1251

Python • list/dict error - not understanding

$
0
0
Hello everyone. Back in 2022, I had issues with inserting data into a database. The data came from temperature sensors wired to an arduino thus the arduino was wired to a pi 3b. We solved the issue, or so I thought, please see viewtopic.php?t=335506.

I fired up the project recently as I currently have time to further work on it and it is giving me KeyError messages to the last piece of data from the arduino...
Image (shows a broken link so I will manually type it out :|

['HotFluidTemp', ' 69.12']
2 (again, ONLY a print statement to show it advanced - NOT part of the data set)
['RightTankTemp', ' 63.72']
['LeftTankTemp', ' 63.61']
['AirTemp', ' 71.73']
here (print statement showing it was now in the ProcessData module)
Traceback (most recent call last):
File "/home/$$$$/server/test_ard-pi_connect.py", line 106, in <module> ProcessData(results)
File "/home/$$$$/server/test_ard-pi_connect.py", line 44, in ProcessData
print(results[HOT_FLUID_TEMP], results[AIR_TEMP], results[LEFT_TANK_TEMP], results[RIGHT_TANK_TEMP])
KeyError: 'AirTemp'

As shown, there are 8 pieces of data in list format. What I read on the realpython.com website (https://realpython.com/python-keyerror/ ... 20another.), the beginning piece of data, HotFluidTemp, should be [0], 69.12 [1], RightTankTemp [2] and so on. Once the program reads the last 2 pieces...it should take that data to the ProcessData module and process it....I think I am making this too complicated sooooooo.....

Here is my raspberry code:

Code:

#! /usr/bin/env python3import serialimport mariadbimport timeimport RPi.GPIO as GPIOif __name__=='__main__':ser=serial.Serial('/dev/ttyACM0', 9600, timeout=1)ser.reset_input_buffer()GPIO.setmode(GPIO.BCM)GPIO.setwarnings(False)TRIG = 2#pin 3ECHO = 3#pin 5rly = 4#pin 7well = 17#pin 11GPIO.setup(TRIG, GPIO.OUT)GPIO.setup(ECHO, GPIO.IN)GPIO.setup(rly, GPIO.OUT)GPIO.setup(well, GPIO.OUT)GPIO.output(TRIG, False)time.sleep(2)HOT_FLUID_TEMP = "HotFluidTemp"#HotFluidTemp is being passed to the pi from the Arduino with a numeric value alsoRIGHT_TANK_TEMP = "RightTankTemp"#RightTankTemp is from the ArduinoLEFT_TANK_TEMP = "LeftTankTemp"#LeftTankTemp is from the ArduinoAIR_TEMP = "AirTemp"#AirTemp is from the ArduinoFIRST_LABEL = HOT_FLUID_TEMPLAST_LABEL = AIR_TEMPdef ProcessData(results):try:print("Connecting...")conn=mariadb.connect(user="$$$$$$$$$$$$$$$", password="**********************", host="localhost", port=#####, database="heater")cur=conn.cursor()print("Sending data to database...")cur.execute("INSERT INTO heater (hot_fluid_temp, air_temp, left_tank_temp, right_tank_temp) VALUES (%s, %s, %s, %s)", (results[HOT_FLUID_TEMP], results[AIR_TEMP], results[LEFT_TANK_TEMP], results[RIGHT_TANK_TEMP]))print(results[HOT_FLUID_TEMP], results[AIR_TEMP], results[LEFT_TANK_TEMP], results[RIGHT_TANK_TEMP])conn.commit()conn.close()except mariadb.Error as e:print("Error connecting to MariaDB Platform: {e}",e)exit(1)def Webpage(rtt, at):print("webpage")file = open("/var/www/html/data.txt","w")file.write(rtt)file.close()file = open("/air.txt","w")file.write(at)#print(results[AIR_TEMP])file.close()#time.sleep(600)#def WaterLevel():#GPIO.output(TRIG, True)#time.sleep(0.00001)#GPIO.output(TRIG, False)##while GPIO.input(ECHO)==0:#pulse_start = time.time()##while GPIO.input(ECHO)==1:#pulse_stop = time.time()##pulse_time = pulse_stop - pulse_start##distance = (pulse_time * 17150) / 2.54 #convert cm to inches#time.sleep(1)##if distance <= 7:#GPIO.output(rly, True)#else:#GPIO.output(rly, False)#if distance >= 20:#GPIO.output(well, True)#else:#GPIO.output(well, False)results = Nonewhile True:line=ser.readline().decode('utf-8').rstrip()parts=line.split("=")print(parts)if line=="":continueif parts[0] == FIRST_LABEL:results = {}results[parts[0]] = parts[1]if results == None:continueif parts[0] == LAST_LABEL:ProcessData(results)#WaterLevel()rtt = results[3] #Here is where I have tried results[RIGHT_TANK_TEMP] and neither workat = results[7]#I tried results[AIR_TEMP] as well...still get errorWebpage(rtt, at)#I also tried Webpage(results[RIGHT_TANK_TEMP], results[AIR_TEMP]) also and nothing
*note: the print statements are for my decoding only. Once up and running properly, I will comment them out.

In the screenshot, it clearly shows 8 pieces of data, in 4 sets. Once the pi has the final set, it should jump to the ProcessData module (it does), tell me it's connecting (it does), but then crashes...saying the KeyError - AirTemp (notice lower case as if the problem is with the Arduino variable and not the pi variable assigned).

The scope of this project is to take temperature readings from the arduino (which is controlling much more than just temps btw), insert them into the assigned database, drop 2 variables into text folders so my php program will pick them up and display them on the according website, and then check the water level using an ultrasonic sensor (we are now into the more rainy season so even though I have an overflow pipe installed, during the winter I had to install a third particle filter and it sits 1/4" lower than the bottom of the pipe inlet therefore possible overflow at the filter. My design is to have the sensor trigger at a set level, the pi turns on a relay that will in turn open a 12v valve to release water to keep the system from overflowing...in theory :roll: )

I'm not understanding why or how this KeyError is being caused. The data is in pairs. Thanks in advance :)

Statistics: Posted by Osprey72 — Tue Apr 16, 2024 5:15 pm



Viewing all articles
Browse latest Browse all 1251

Trending Articles