theflash
Posts: 5
Joined: Sun Oct 14, 2012 10:21 am

SHT 11 Python Problem

Thu Apr 16, 2015 6:53 pm

Hi,

Please help me because i am almost insane! :evil:

I am reading a lot of document about "How to use SHT11 on RPi" but i somehow could not manage it.
Here is my problem, i install rpiSht1x 1.2 and create aaa.py file which includes sample code:

Code: Select all

from sht1x.Sht1x import Sht1x as SHT1x
dataPin = 11
clkPin = 7
sht1x = SHT1x(dataPin, clkPin, SHT1x.GPIO_BOARD)
temperature = sht1x.read_temperature_C()
humidity = sht1x.read_humidity()
dewPoint = sht1x.calculate_dew_point(temperature, humidity)
print("Temperature: {} Humidity: {} Dew Point: {}".format(temperature, humidity, dewPoint)) 
But i have an Error like:

Code: Select all

ERROR:sht1x.Sht1x:nack2
Traceback (most recent call last):
  File "aaa.py", line 7, in <module>
    humidity = sht1x.read_humidity()
  File "/usr/local/lib/python2.7/dist-packages/rpiSht1x-1.2-py2.7.egg/sht1x/Sht1x.py", line 79, in read_humidity
    temperature = self.read_temperature_C()
  File "/usr/local/lib/python2.7/dist-packages/rpiSht1x-1.2-py2.7.egg/sht1x/Sht1x.py", line 68, in read_temperature_C
    self.__sendCommand(temperatureCommand)
  File "/usr/local/lib/python2.7/dist-packages/rpiSht1x-1.2-py2.7.egg/sht1x/Sht1x.py", line 105, in __sendCommand
    GPIO.setup(self.dataPin, GPIO.OUT)
RuntimeError: Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM) 
I have a SHT 11 board (not only sensor) which has only 4 connections (VDD,GND,SCK,DATA) and i plugged them to GPIO 2-6-7-11 (with proper write).

Where did i wrong?

mabnz
Posts: 2
Joined: Sun Jan 12, 2014 6:35 am

Re: SHT 11 Python Problem

Thu May 14, 2015 11:57 am

I think there's been a change in the python3-rpi.gpio package between v0.5.9-1 and v0.5.11 which has broken this, or has at the very least broken compatibility with rpiSht1x 1.2. It's nothing you've done wrong.

Anyway, I solved my error (which was very similar to yours) by editing /usr/local/lib/python2.7/dist-packages/rpiSht1x-1.2-py2.7.egg/sht1x/Sht1x.py:

Add at Line 105:

Code: Select all

    GPIO.setmode(gpioMode)
Modify line 103:

Code: Select all

  def __sendCommand(self, command, gpioMode = GPIO_BOARD):
Hope that helps.

clusty
Posts: 3
Joined: Sun Oct 21, 2012 2:36 pm

Re: SHT 11 Python Problem

Tue Aug 04, 2015 10:36 pm

This post just saved my life.
Not worth pushing the sh1x package update so the next guy does not have to bang his head?

ochikov
Posts: 5
Joined: Wed Mar 01, 2017 9:11 pm

Re: SHT 11 Python Problem

Wed Mar 01, 2017 9:13 pm

Hello,

Can somebody tell me how to access the .egg file? Steps by steps?

Thank you!

ochikov
Posts: 5
Joined: Wed Mar 01, 2017 9:11 pm

Re: SHT 11 Python Problem

Wed Mar 01, 2017 10:16 pm

Can I have a little more help. My lines looks different and I don't know where to add the code.

Code: Select all

'''
Created on Oct 5, 2012

@author: Luca Nobili

This modules reads Humidity and Temperature from a Sensirion SHT1x sensor. I has been tested
both with an SHT11 and an SHT15.

It is meant to be used in a Raspberry Pi and depends on this module (http://code.google.com/p/raspberry-gpio-python/).

The module raspberry-gpio-python requires root privileges, therefore, to run this module you need to run your script as root.


Example Usage:

>>> from sht1x.Sht1x import Sht1x as SHT1x
>>> sht1x = SHT1x(11,7)
>>> sht1x.read_temperature_C()
25.22
>>> sht1x.read_humidity()     
52.6564216

'''
import traceback
import sys
import time
import logging
import math

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

try:
    import RPi.GPIO as GPIO
except ImportError:
    logger.warning("Could not import the RPi.GPIO package (http://pypi.python.org/pypi/RPi.GPIO). Using a mock instead. Notice that this is useful only for the purpose of debugging this module, but will not give the end user any useful result.")
    import RPiMock.GPIO as GPIO
except:
    logger.warning("Could not import the RPi.GPIO package (http://pypi.python.org/pypi/RPi.GPIO). Using a mock instead. Notice that this is useful only for the purpose of debugging this module, but will not give the end user any useful result.")
    import RPiMock.GPIO as GPIO
    traceback.print_exc(file=sys.stdout)
 
#   Conversion coefficients from SHT15 datasheet
D1 = -40.0  # for 14 Bit @ 5V
D2 =  0.01 # for 14 Bit DEGC

C1 = -2.0468       # for 12 Bit
C2 =  0.0367       # for 12 Bit
C3 = -0.0000015955 # for 12 Bit
T1 =  0.01      # for 14 Bit @ 5V
T2 =  0.00008   # for 14 Bit @ 5V


class Sht1x(object):
    GPIO_BOARD = GPIO.BOARD
    GPIO_BCM = GPIO.BCM

    def __init__(self, dataPin, sckPin, gpioMode = GPIO_BOARD):
        self.dataPin = dataPin
        self.sckPin = sckPin
        self.gpioMode = gpioMode

#    I deliberately will not implement read_temperature_F because I believe in the
#    in the Metric System (http://en.wikipedia.org/wiki/Metric_system)

    def read_temperature_C(self):
        temperatureCommand = 0b00000011

        self.__sendCommand(temperatureCommand)
        self.__waitForResult()
        rawTemperature = self.__getData16Bit()
        self.__skipCrc()
        GPIO.cleanup([self.dataPin, self.sckPin])

        return rawTemperature * D2 + D1

    def read_humidity(self):
        return self.read_temperature_C_and_humidity()[1]

    def read_temperature_C_and_humidity(self):
        # get current temperature for humidity correction
        temperature = self.read_temperature_C()
        humidity = self._read_humidity(temperature)
        return temperature, humidity

    def _read_humidity(self, temperature):
        humidityCommand = 0b00000101
        self.__sendCommand(humidityCommand)
        self.__waitForResult()
        rawHumidity = self.__getData16Bit()
        self.__skipCrc()
        GPIO.cleanup([self.dataPin, self.sckPin])
#        Apply linear conversion to raw value
        linearHumidity = C1 + C2 * rawHumidity + C3 * rawHumidity * rawHumidity
#        Correct humidity value for current temperature
        return (temperature - 25.0 ) * (T1 + T2 * rawHumidity) + linearHumidity            

    def calculate_dew_point(self, temperature, humidity):
        if temperature > 0:
            tn = 243.12
            m = 17.62
        else:
            tn = 272.62
            m = 22.46
        return tn * (math.log(humidity / 100.0) + (m * temperature) / (tn + temperature)) / (m - math.log(humidity / 100.0) - m * temperature / (tn + temperature))

    def __sendCommand(self, command):
        #Transmission start
        GPIO.setmode(self.gpioMode)
        GPIO.setup(self.dataPin, GPIO.OUT)
        GPIO.setup(self.sckPin, GPIO.OUT)
                
        GPIO.output(self.dataPin, GPIO.HIGH)
        self.__clockTick(GPIO.HIGH)
        GPIO.output(self.dataPin, GPIO.LOW)
        self.__clockTick(GPIO.LOW)
        self.__clockTick(GPIO.HIGH)
        GPIO.output(self.dataPin, GPIO.HIGH)
        self.__clockTick(GPIO.LOW)

        for i in range(8):
            GPIO.output(self.dataPin, command & (1 << 7 - i))
            self.__clockTick(GPIO.HIGH)
            self.__clockTick(GPIO.LOW)     
        
        self.__clockTick(GPIO.HIGH)
        
        GPIO.setup(self.dataPin, GPIO.IN)
        
        ack = GPIO.input(self.dataPin)
        logger.debug("ack1: %s", ack)
        if ack != GPIO.LOW:
            logger.error("nack1")
        
        self.__clockTick(GPIO.LOW)
        
        ack = GPIO.input(self.dataPin)
        logger.debug("ack2: %s", ack)
        if ack != GPIO.HIGH:
            logger.error("nack2")        
            
    def __clockTick(self, value):
        GPIO.output(self.sckPin, value)
#       100 nanoseconds 
        time.sleep(.0000001)
        
    def __waitForResult(self):
        GPIO.setup(self.dataPin, GPIO.IN)

        for i in range(100):
#            10 milliseconds
            time.sleep(.01)
            ack = GPIO.input(self.dataPin)
            if ack == GPIO.LOW:
                break
        if ack == GPIO.HIGH:
            raise SystemError
            
    def __getData16Bit(self):
        GPIO.setup(self.dataPin, GPIO.IN)
        GPIO.setup(self.sckPin, GPIO.OUT)
#        Get the most significant bits
        value = self.__shiftIn(8)
        value *= 256
#        Send the required ack
        GPIO.setup(self.dataPin, GPIO.OUT)
        GPIO.output(self.dataPin, GPIO.HIGH)
        GPIO.output(self.dataPin, GPIO.LOW)
        self.__clockTick(GPIO.HIGH)
        self.__clockTick(GPIO.LOW)
#        Get the least significant bits
        GPIO.setup(self.dataPin, GPIO.IN)
        value |= self.__shiftIn(8)
        
        return value
    
    def __shiftIn(self, bitNum):
        value = 0
        for i in range(bitNum):
            self.__clockTick(GPIO.HIGH)
            value = value * 2 + GPIO.input(self.dataPin)
            self.__clockTick(GPIO.LOW)
        return value
     
    def __skipCrc(self):
#        Skip acknowledge to end trans (no CRC)
        GPIO.setup(self.dataPin, GPIO.OUT)
        GPIO.setup(self.sckPin, GPIO.OUT)
        GPIO.output(self.dataPin, GPIO.HIGH)
        self.__clockTick(GPIO.HIGH)
        self.__clockTick(GPIO.LOW)
    
    def __connectionReset(self):
        GPIO.setup(self.dataPin, GPIO.OUT)
        GPIO.setup(self.sckPin, GPIO.OUT)
        GPIO.output(self.dataPin, GPIO.HIGH)
        for i in range(10):
            self.__clockTick(GPIO.HIGH)
            self.__clockTick(GPIO.LOW)

# The waiting version is supposed to cater for this part of the data sheet:
# Important: To keep self heating below 0.1 degree C, SHT1x
# should not be active for more than 10% of the time - e.g.
# maximum one measurement per second at 12bit accuracy
# shall be made.
class WaitingSht1x(Sht1x):
    def __init__(self, dataPin, sckPin):
        super(WaitingSht1x, self).__init__(dataPin, sckPin)
        self.__lastInvocationTime = 0

    def read_temperature_C(self):
        self.__wait()        
        return super(WaitingSht1x, self).read_temperature_C()
    
    def read_humidity(self):
        temperature = self.read_temperature_C()
        self.__wait()
        return super(WaitingSht1x, self)._read_humidity(temperature)
    
    def read_temperature_and_Humidity(self):
        temperature = self.read_temperature_C()
        self.__wait()
        humidity = super(WaitingSht1x, self)._read_humidity(temperature)
        return (temperature, humidity)
            
    def __wait(self):
        lastInvocationDelta = time.time() - self.__lastInvocationTime
#        if we queried the sensor less then a second ago, wait until a second is passed
        if lastInvocationDelta < 1:
            time.sleep(1 - lastInvocationDelta)
        self.__lastInvocationTime = time.time()
        
def main():
    sht1x = WaitingSht1x(11, 7)
    print(sht1x.read_temperature_C())
    print(sht1x.read_humidity())
    aTouple = sht1x.read_temperature_and_Humidity()
    print("Temperature: {} Humidity: {}".format(aTouple[0], aTouple[1]))
    print(sht1x.calculate_dew_point(20, 50))
    
if __name__ == '__main__':
    main()

ochikov
Posts: 5
Joined: Wed Mar 01, 2017 9:11 pm

Re: SHT 11 Python Problem

Sun Mar 05, 2017 2:58 pm

Anybody?

niin
Posts: 1
Joined: Thu Oct 12, 2017 6:57 pm

Re: SHT 11 Python Problem

Thu Oct 12, 2017 7:59 pm

ochikov wrote:
Sun Mar 05, 2017 2:58 pm
Anybody?
On Raspberry P 2 Model B

Code: Select all

sudo apt-get update
sudo apt-get install python3  python3-pip
sudo pip3 install rpiSht1x
after that command is installed also RPi.GPIO version 0.6.3 (the last at this moment)

First solution: edit the file
/usr/local/lib/python3.4/dist-packages/sht1x/Sht1x.py
as mabnz suggest at line 103 and at line 105:

Second solution, you can downgrade to version 0.5.10 of RPi.GPIO as follows

Code: Select all

sudo pip3 uninstall RPi.GPIO
sudo pip3 install https://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.5.10.tar.gz#md5=f1c67de40bf99e0612d75538b06a2181
seems that the problem occurs at version 0.5.11 and up of RPi.GPIO
(GPIO.cleanup() unsets the current pin mode).

Third solution: edit the file
/usr/local/lib/python3.4/dist-packages/sht1x/Sht1x.py
and comment line 72

Code: Select all

#        GPIO.cleanup()

Return to “Interfacing (DSI, CSI, I2C, etc.)”

Who is online

Users browsing this forum: No registered users and 11 guests