-->
Page 3 of 3

Re: i2c problems with nodemcu

PostPosted: Sun May 08, 2016 12:25 pm
by Ultrasonic
I modified the original coding slightly. Now it works on my ESP8266-12 with SCL connected to GPIO2 and SDA connected to GPIO0. Both pins are pulled up to VCC with a 2,2kOhm resistor.

Things I changed:
- added a delay of 100ms between the transmitt and the receive command
- read always 3 bytes (2 data bytes + 1 checksum byte)

Code: Select all-- Driver for the Humidity- and Temperature-Sensor HTU21D
htu21df = {

    CMD_TEMP_HOLD = 0xE3,
    CMD_TEMP_NO_HOLD = 0xF3,

    CMD_HUMIDITY_HOLD = 0xE5,
    CMD_HUMIDITY_NO_HOLD = 0xF5,

    address = 0x40,
    id = 0,

    -- Initialise the I2C-Bus
    -- Parameters:
    --   sda - IO-Index of the SDA pin
    --   scl - IO-Index of the SCL pin
    init = function (self, sda, scl)
       self.id = 0
       i2c.setup(self.id, sda, scl, i2c.SLOW)
    end,

    -- Returns the value of the register with the given address
    -- Parameters:
    --   reg_addr - Address of the register to read
    read_reg = function(self, reg_addr)
     
        i2c.start(self.id)
        i2c.address(self.id, self.address, i2c.TRANSMITTER)
        i2c.write(self.id, reg_addr)
        i2c.stop(self.id)

        tmr.delay(100000) -- wait for 100ms
         
        i2c.start(self.id)
        i2c.address(self.id, self.address, i2c.RECEIVER)
        c = i2c.read(self.id, 3)
        i2c.stop(self.id)
         
        return c
    end,

    -- Returns the measured temperature
    readTemp = function(self)
        h, l = string.byte(self:read_reg(self.CMD_TEMP_HOLD), 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,

    -- Returns the measured humidity
    readHum = function(self)
        h,l = string.byte(self:read_reg(self.CMD_HUMIDITY_HOLD), 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
}


sda = 3                     --GPIO0               --  declare your I2C interface PIN's
scl = 4                     --GPIO2

htu21df:init(sda, scl)      -- initialize I2C

temp = htu21df:readTemp()   -- read temperature
print(temp)                 -- print it

hum = htu21df:readHum()     -- read humidity
print(hum)                  -- print it