Forum >Replies by Ventheris
userhead Ventheris
Replies (1)
  • You Reply:

    Hi, 

     

    I stumbled across your question while searching for solutions for using this exact sensor with a Pico. 

     

    Here's the Thonny code I pulled together that got the sensor working.

    The top of the code has an i2c scan and outputting the addresses located. 

    The binary address of mine is 64 - which is what's used in the code. 

    If yours is different, you can update it accordingly. 

     

    >> The biggest learning curve moment I had was converting the ‘0x00’ hex addresses into binary address ‘\x00’. I had the same EIO errors until I worked that out.

     

    This code loops endlessly while pulling temp and humidity readings from the sensor.

     

    I was holding the sensor in my hands, breathing on it to get the humidity and temperature to spike. 

     

    ##########THONNY SCRIPT###########

     

    def calcTempFromBinary(binary):
       int_val = int.from_bytes(binary, "big")
       tempCalc = 165 * (int_val / (2**16-1)) - 40
       return tempCalc

    def calcHumidityFromBinary(binary):
       int_val = int.from_bytes(binary, "big")
       humidityCalc = 100 * (int_val / (2**16-1))
       return humidityCalc

     

    import machine
    import time
    sda=machine.Pin(16)
    scl=machine.Pin(17)
    i2c=machine.I2C(0,sda=sda, scl=scl, freq=400000)
    #i2c=machine.I2C(0,sda=sda, scl=scl)

    print('Scan i2c bus...')
    devices = i2c.scan()

    if len(devices) == 0:
       print("No i2c device !")
    else:
       print('i2c devices found:',len(devices))

    for device in devices:
       print("Decimal address: ",device," | Hexa address: ",hex(device))

    addrDecimal = 64

    while True:
       
       time.sleep(5)         #sleep 5 seconds
       
       i2c.writeto(addrDecimal, '\x00')     #request temperature read
       time.sleep(0.3)         #delay to allow temperature read
       tempBinary = i2c.readfrom(addrDecimal, 2)   #read bits from i2c
       
       temp = calcTempFromBinary(tempBinary)   #pass temperature binary to function for converstion
       
       i2c.writeto(addrDecimal, '\x01')    #request humidity read
       time.sleep(0.3)         #delay to allow humidity read
       tempBinary = i2c.readfrom(addrDecimal, 2)  #read bits from i2c
       
       humidity = calcHumidityFromBinary(tempBinary) #pass humidity binary to function for conversion
       
       print(f'Temperature is:{temp}  Humidity is:{humidity}')

    ______________________________

    ##########THONNY SCRIPT###########