HYT271 Temperature & Humidity sensor

I know, it’s not perfect but it’s working…

/************************************************
*												*
*		HYT271									*
*		ing. Roger D'Joos						*
*												*
*		version 1.0								*
*		Beerware :-)							*
*/
#include "Wire.h"
#define address	0x28

byte LowByte1;
byte HighByte1;
byte LowByte2;
byte HighByte2;
unsigned int Answer1;
unsigned int Answer2;
float Humidity = 0.0;
float Temperature = 0.0;
float tMin = 0.0;
float tMax = 0.0;
float hMin= 0.0;
float hMax = 0.0;
boolean First;

void setup()
{
	Wire.begin();
	Serial.begin(9600);
	First = true;
}

void loop()
{
	while (1 == 1)
	{
		ReadData();
		CalcTempHum();
		DispTempHum();
		delay(30000);
	}
}
void ReadData()
{
	Wire.beginTransmission(address);
	Wire.requestFrom(address, 4);
	if (Wire.available())
	{
		HighByte1 = Wire.read();
		LowByte1 = Wire.read();
		HighByte2 = Wire.read();
		LowByte2 = Wire.read();
	}
	Wire.endTransmission();
}
void CalcTempHum()
{
	HighByte1 = HighByte1 & 0x3F;
	Answer1 = HighByte1 << 8 | LowByte1;
	Humidity = Answer1 / 163.84;
	Answer2 = HighByte2 << 8 | LowByte2 & 0xFC;
	Temperature = ((Answer2 / 65536.0) * 165.0) - 40.0;
	if (First)
	{
		tMin = Temperature;
		tMax = Temperature;
		hMin = Humidity;
		hMax = Humidity;
		First = false;
	}
	if (Temperature < tMin) tMin = Temperature;
	if (Temperature > tMax) tMax = Temperature;
	if (Humidity < hMin) hMin = Humidity;
	if (Humidity > hMax) hMax = Humidity;
}
void DispTempHum()
{
	Serial.print("Humidity: ");
	Serial.print(Humidity, 2);
	Serial.println("");
	Serial.print("Temperature: ");
	Serial.print(Temperature, 2);
	Serial.println("");
	Serial.print("Min. temperature: ");
	Serial.print(tMin, 2);
	Serial.print("     Max. temperature: ");
	Serial.print(tMax, 2);
	Serial.println("");
	Serial.print("Min.humidity:     ");
	Serial.print(hMin, 2);
	Serial.print("     Max.humidity:     ");
	Serial.print(hMax, 2);
	Serial.println("");
}

Suggestions are welcome :slight_smile:

Thanks for sharing, it is a good first version

  1. wrap it in a class like - http://arduino.cc/playground/Main/DHTLib - something like
class HYT271 
{
public:
    HYT271 (uint8_t address) { _address = address; }

    int read();
    double getHumidity();
    double getTemperature();

private:
    uint8_t _address;
    double _temperature;
    double _humidity;
};

tip: move the min and max outside the class.

  1. post a link to the datasheet

  2. loop() is already called repeatedly

void loop()
{
	ReadData();
	CalcTempHum();
	DispTempHum();
	delay(30000);
}
  1. more efficient
	if (Temperature < tMin) tMin = Temperature; 
	else if (Temperature > tMax) tMax = Temperature;
  1. The boolean first is not needed if you initialze the two vars e.g. min =999 and max = -999 get the idea?

your turn :wink:

found a detailed datasheet of internals e.g. setting other address: