Use this forum to chat about hardware specific topics for the ESP8266 (peripherals, memory, clocks, JTAG, programming)

User avatar
By picstart
#11768 I don't know exactly what the lua read I2C write I2C expects for the address of the I2C device
Some I2C functions like read and write use the full 8 bit address and mask the bit of the address that indicates read or write.
Others take a 7 bit address and set or clear the read/write bit.
Manufacturers of I2C devices can give a 7bit address or an 8 bit address.

If the interface is working pull ups and level 3.3v or 5v is correct then it just might be an addressing 7 or 8 bit issue
User avatar
By alnitak
#11800 Thanks all for your comments. turns out I needed to add a delay between issuing the command to the htu board and then reading the register. Here's the updated module code:

Code: Select allhtu21df= {
     dev_addr = 0x40,
     id = 0,
     init = function (self, sda, scl)
               self.id = 0
               i2c.setup(self.id, sda, scl, i2c.SLOW)
     end,
     read_reg = function(self, dev_addr, reg_addr)
          i2c.start(self.id)
          i2c.address(self.id, dev_addr ,i2c.TRANSMITTER)
          i2c.write(self.id,reg_addr)
          i2c.stop(self.id)
          i2c.start(self.id)
          i2c.address(self.id, dev_addr,i2c.RECEIVER)
          tmr.delay(50000) --wait for measurment
          c=i2c.read(self.id,2)
          i2c.stop(self.id)
          return c
    end,
   

    readTemp = function(self)
          h, l = string.byte(self:read_reg(0x40, 0xE3), 1, 2)
          h1=bit.lshift(h,8)
          rawtemp = bit.band(bit.bor(h1,l),0xfffc)
          temp = ((rawtemp/65536)*175.72)-46.85
          return temp
    end,
    readHum = function(self)
          h,l = string.byte(self:read_reg(0x40,0xE5),1,2)
          h1=bit.lshift(h,8)
          rawhum = bit.band(bit.bor(h1,1),0xfffc)
          hum = ((rawhum/65536)*125.0)-6.0
          return hum
     end
     }


and here's the test code:

Code: Select allrequire('htu21df')                 --call for new created HTU21df Module Driver
          sda=3 --GPIO2               --  declare your I2C interface PIN's
          scl=4 --GPIO0
         
          htu21df:init(sda, scl)      -- initialize I2C 
          htu21df:read_reg(0x40,0xe7) --check the status reg
          temp = htu21df:readTemp()   -- read temperature
          print(temp)                 -- print it
          hum = htu21df:readHum()
          print(hum)


works like a charm. Stay tuned for the dweet.io solution