read temperature from DHT11, using pi4j

前端 未结 6 2097
甜味超标
甜味超标 2021-02-06 12:55

I\'m trying to read temperature data from a DHT11 temperature sensor, using pi4j. I followed the code written in c and python in this site: http://www.uugear.com/portfolio/dht11

6条回答
  •  悲&欢浪女
    2021-02-06 13:05

    Eric Smith's excellent code works fine for me with two small mods, First I edited this line:

    if (counter > 16)
    

    To:

    if (counter > 30)
    

    According to specs of dht11, the "1" bit is transmitted when the delay of the "Gpio.HIGH" is about 70us, and "0" bit is transmitted if the delay is 26-28us. It is clear that Java takes some time to execute, so it is safe to assume that if the delay is more than 30us the data must be "1". But this might be different value if the execution time of Java program is different in your machine (perhaps the processor of pi is faster/slower, there is more background programs etc). Therefore, the 30 is not necessarily the right value for every situation.

    According to specs 1, it can be also noted that sender (raspberry pi, called MCU in the specs), should also send Gpio.HIGH for at least 18ms. After that, the MCU should send 20-40 us "Gpio.HIGH". I tested with System.nanoTime() how much time it takes for the Java to execute setting the Gpio.Pinmode to the "Input". It took something like 20us, so I added:

    Gpio.delayMicroseconds(7);
    

    ...just to be sure that the Pin is HIGH for at least 20us so that the Sensor can register that signal and start sending its temperature and humidity data. After these changes, the temperature data is read almost always right, the success rate is something like 90%. Im not sure can the modifications work with another system, but hopefully these kind of modifications can make other experiments more successful!

    (p.s. I also made the eternal loop so that the class is created everytime over and over again when the method is called.)

提交回复
热议问题