0

I'm using raspberry pi 3 b+ and si7021 to get temperature and humidity. But now I have a problem that I don't know how to use wiringpi correctly.

This is my code:

import sys
import time
import wiringpi

I2C_ADDR = 0x40
SI7021_REG_NO_HOLD_HUMIDITY = 0xF5
SI7021_REG_NO_HOLD_TEMPERATURE = 0xF3


wiringpi.wiringPiSetup()
fd = wiringpi.wiringPiI2CSetup(0x40)
#fd = wiringpi.wiringPiI2CSetupInterface("/dev/i2c-0", I2C_ADDR)
while True:
    try:
        print(wiringpi.wiringPiI2CWriteReg8(fd,0x40,0xF3))
        time.sleep(0.3)
        print(fd, wiringpi.wiringPiI2CReadReg8(fd, 0x40))
       # print(wiringpi.wiringPiI2CRead(0x40))
        time.sleep(0.5)
    except KeyboardInterrupt:
        sys.exit(0)

The problem is I will always get 0 or negative value after wiringpi.wiringPiI2CWriteReg8(fd,0x40,0xF3) and wiringpi.wiringPiI2CReadReg8(fd, 0x40) executed. According to their manual, this means an error.

I'm quite sure that my connection is correct since I can use i2cget to get a correct value. Can someone tell me what is wrong in my code? Thanks in advance.

  • Why don't you use the Linux kernel driver for your chip: https://elixir.bootlin.com/linux/latest/source/drivers/iio/humidity/si7020.c? – 0andriy Jan 20 '23 at 17:20
  • @0andriy Thank you for your response. I'm studying Iot so I prefer to program by myself instead of using some libraries off the shelf. But whatever, thank you for your help! – someonewating Jan 21 '23 at 19:19
  • Drivers in the kernel are written on purpose, but good luck with your studies! – 0andriy Jan 21 '23 at 21:46

1 Answers1

0

The slave address that is mentioned in the datasheet is already passed to the wiringpi library in the wiringPiI2CSetup(0x40) call. You do not need to repeat it, it is implicitly passed as fd. Given the wiringpi documentation you‘re trying to set register 0x40 to value 0xF3. Instead you should use wiringPiI2CWrite to issue the command. And similarly use wiringPiI2CRead afterwards.

Grimaldi
  • 131
  • 4
  • Hi there. Thank you for your reply. I tried your advice, but it still doesn't work, the result of `wiringPiI2CWrite` is 0 while the result of `wiringPiI2CRead` is -1 as usual. – someonewating Jan 20 '23 at 00:28
  • What does `errno` tell you? – Grimaldi Jan 23 '23 at 06:50
  • This is the weirdest part because it only replies a number without anything else. I didn't even know it was an error number before I checked wiringpi's website. – someonewating Jan 24 '23 at 10:46
  • C libraries have the convention to return a boolean (ok or not ok) and then use a side channel like `errno` to convey further info. So what does `errno` say? According to the datasheet, I‘d expect a NACK error, as you‘re querying in „no hold“ mode. Repeat until you get the measurement value (p. 19ff) – Grimaldi Jan 24 '23 at 16:58