Arduino icon indicating copy to clipboard operation
Arduino copied to clipboard

I2C not working well

Open Andreotti100 opened this issue 10 years ago • 6 comments

I tested a simple GY-21 temperature/humidity sensor with I2C protocol. It does not work very well. Sometimes I get a reading, so I know the ports are right. I used 5.1K pull-up resistors on the SDA and SCL pins 4 and 5.

Is there a way to improve that? A test with the Arduino Uno worked very well.

Here's my code:

#include <Wire.h> // Wire.h
#include <SI7021.h> // SI7021.h


SI7021 sensor;

void setup() {
  Serial.begin(115200);
  Serial.println("");
  Serial.println("Sensor init");
#if defined(ARDUINO_ARCH_ESP8266)
  Serial.println("For ESP8266");
  // sensor.ESPbegin(4, 5, 400000);
  sensor.ESPbegin(4, 5, 0);
  delay(1000);
#else
  sensor.begin();
#endif
  Serial.println("Init done");
  // this driver should work for SI7020 and SI7021, this returns 20 or 21
  int deviceid = sensor.getDeviceId();
  Serial.print("device ID: ");
  Serial.println(deviceid);
  if (deviceid == 20) Serial.println("SI7020"); else if (deviceid == 21) Serial.println("SI7021");
  Serial.println("");
}


void loop() {

    // temperature is an integer in hundredths
    float temperature = float(sensor.getCelsiusHundredths()) / 100;
    Serial.print("Temperatuur celsius: ");
    Serial.println(temperature);

    // humidity is an integer representing percent
    int humidity = sensor.getHumidityPercent();
    Serial.print("Luchtvochtigheid: ");
    Serial.println(humidity);

    delay(5000);
    Serial.println("");
}

Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.

Andreotti100 avatar Dec 06 '15 23:12 Andreotti100

Which si7021 library are you using, there are a few floating around.

jeffryr avatar Dec 07 '15 15:12 jeffryr

I tried these two:

https://forum.pjrc.com/threads/29237-Si7021-Humidity-and-Temperature-Sensor-Library and https://github.com/mlsorensen/SI7021

Andreotti100 avatar Dec 07 '15 16:12 Andreotti100

typically these devices need some time to take the measurement, neither of these libs seem to include any delay between writing the 'measure' command and reading the result. I have delay(75) in my code and it works reliably.

mtnbrit avatar Dec 07 '15 17:12 mtnbrit

A delay of 25 or higher does the trick, many thanks!

Andreotti100 avatar Dec 07 '15 18:12 Andreotti100

My code:

void SI7021::_command(byte * cmd, byte * buf ) { _writeReg(cmd, sizeof cmd); delay(25); _readReg(buf, sizeof buf); }

Andreotti100 avatar Dec 07 '15 18:12 Andreotti100

Closing as resolved.

devyte avatar Oct 19 '17 06:10 devyte