From f4992929e9697c92d7ef0992b96e6050ad8edbd7 Mon Sep 17 00:00:00 2001 From: Jesse Chant <38460825+dsiee@users.noreply.github.com> Date: Sat, 20 Jul 2019 09:34:22 +1000 Subject: [PATCH] Prevent divide by zero errors in temp calculation If a black object or if it is low light causes R2 in _temperature_and_lux_dn40 to be zero the line for color temperature calculation will throw a divide by zero error. This can be repeated by running tcs34725_simpletest.py which prints lux and temp, disabling the LED by pulling LED pin to GND and placing something on the sensor to block ambient light (e.g. your finger). This can also occur, although less reliably, with a very black object with the LED on. Proposed fix is just an if to check if R2 is greater then zero. If it isn't use a small value in it's place to allow B2 to still be considered. --- adafruit_tcs34725.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/adafruit_tcs34725.py b/adafruit_tcs34725.py index a4eb251..3a51302 100644 --- a/adafruit_tcs34725.py +++ b/adafruit_tcs34725.py @@ -311,7 +311,11 @@ def _temperature_and_lux_dn40(self): lux = G1 / CPL # CT Calculations (DN40 3.4) - CT = CT_Coef * B2 / R2 + CT_Offset + # Prevent divide by zero errors. if r2 = 0 use a really small r2 to print offset + if R2 > 0: + CT = CT_Coef * B2 / R2 + CT_Offset + else: + CT = CT_Coef * B2 / 0.001 + CT_Offset return lux, CT