Math domain error

I’m helping high school students set up a network of sensors to run irrigation in an experimental citrus grove. We started by using the analog temperature sensor. It works fine, however, after a few minutes, it always crashes with an error in the grovepi library. It’s a long error message that ends with:
math domain error line 102 in temp

All that I added to the sample code were a couple of fudge factors in the “print” line to calibrate to fahrenheit.

I really want to use grovepi for this project but I cannot use it if it cannot run reliably for weeks without crashing. I cannot get 5 minutes without a crash.

Any ideas?

Hi,
Can you paste the whole error along with the program code that you are using. It’ll help a lot to debug the problem.

The GrovePi does throw errors sometimes but with proper error handling, it can become pretty stable.

-Karan

I’m not in front of the Pi right now to type the error message, but the above was basically the whole thing except for the line in the code that referred to “temp” which caused the error. The line in the code mathematically could not cause the error. Here’s the code:

import grovepi
import time
import sys

sensor = 0

while True:
  try:
    temp = int(-2.47*(grovepi.temp(sensor))+137)
    print temp, "degrees Fahrenheit"
    time.sleep(1)
    sys.stderr.write("x1b[2Jx1b[H")
  except IOError:
    print "Error"

Occasionally, I see “Error” pop up on the output screen. It’s maybe one out of ever 50 readings or so. But it doesn’t interfere with the program. I finally figured out how to keep the computer monitor to stop falling asleep.

OK, here’s the full error message:

Traceback (most recent call last):
File: "grove_termperature_sensoredit.py"
line 9 in <module>
temp = int(-2.47*(grovepi.temp(sensor)+137))
File: “/home/pi/GrovePi/Software/Python/grovepi.py”, line 102 in temp
t = (float)(1/(math.log(resistance/10000)/3975+1/298.15)-273.15)
ValueError: math domain error

Line 9 in my program is referring to line 102 in the grovepi library and causing the math domain error. The only error that I see possible is that if the resistance is either 0 or 10,000, then there would be a divide by zero error. So, this must be a thermistor and the resistance is converted to temperature. I don’t know what the resistance values are since it’s converted by the library before being sent to the program.

Hi,
The GrovePi sometimes is unable to read the values off the sensor and trows the math error.

Does adding an exception handler for the math error help, e.g.:

except ValueError:
    print &quot;Math Error&quot;

-Karan

I’ll give it a shot. I have to say that the last time, it lasted several hours before the error without me changing anything, so it is highly variable. I’ll add the error handler and leave it for a while.

That worked perfectly, thanks!