Mixed up sensor readings

So I’m trying to read some sensors from the grovepi with python.
I’m not really sure why, but the reading from the moisture sensor keeps getting mixed up with the reading from the light sensor…

import time
import grovepi
import math

moisture_sensor = 1
light_sensor = 2
temp_humidity_sensor = 4

def read_sensor():
                moisture = grovepi.analogRead(moisture_sensor)
                light = grovepi.analogRead(light_sensor)
                [temp,humidity] = grovepi.dht(temp_humidity_sensor,0)
                if math.isnan(temp) or math.isnan(humidity):
                        return [-1,-1,-1,-1]
                return [moisture,light,temp,humidity]
        except IOError as TypeError:
                        return [-1,-1,-1,-1]

moisture = grovepi.analogRead(moisture_sensor)
light = grovepi.analogRead(light_sensor)
[temp,humidity] = grovepi.dht(temp_humidity_sensor,0)

The ouput is:

[211, 762, 21.0, 34.0]





So in the first instance it’s getting the right value but when I’m trying to get the value again, it shows the same value for moisture and light. When I put the print(read_sensor()) behind the other print functions the first ones are right and the last one is not working.

Any ideas why this is happening and how to fix it would be greatly appreciated!

hello @gollium

Have you tried with a little delay between the two analogRead calls?
time.sleep(0.5) will work, but you can also probably get a smaller delay.

Let me know if it helps,

Thanks so much for the reply :). I wrote individual functions for the readings and that worked. But I will try your solution too as soon as I get my hands back on the pi!

1 Like

there’s always a small delay between the call to analogRead and actually getting the answer, and it’s done asynchronously so sometimes they get served in reversed order.
A small delay usually fixes that, the actual value will depend on the sensor (some are fast to answer, and others are a tad slower)