SHT21 is a neat little temperature and humidity sensor from Sensirion and I have used it in a couple of my Arduino projects before. Given that the Vcc is 3 V for these sensors, interfacing with a 5V ATMega chip would require an I2C level translator (or alternatively, you could run the MCU at a lower clock frequency and use the lower Vcc). Since TI’s MSP430G2 series MCU runs at lower voltages natively, it is actually a lot cleaner to interface these 3V powered I2C devices.

Also, no external pull-up resistors on the SCL/SDA lines are needed since we can utilize the internal pull-up resistors. The following is the code for getting the temperature and humidity readings from SHT21 using MSP430G2231. You may need to disconnect the LED on the P1.6 pin for the I2C to work correctly as I discussed previously. If you are not familiar with I2C programming with MSP430, you can take a look at my earlier post. Please refer to the SHT21 datasheet for more information on the protocol details.


#include <msp430g2231.h>

unsigned char I2CAddr = 0x40;
unsigned char CMD_GET_TEMPERATURE = 0xE3;
unsigned char CMD_GET_HUNIDITY = 0xE5;

int readData() {
	int t;

	i2c_start();
	i2c_write8(I2CAddr << 1  | 1);
	t = i2c_read8(0x0) << 8;
	t |= i2c_read8(0x0);
	t &= ~0x3;  // clear status bits
	i2c_read8(0x0); // ignore CRC
	i2c_stop();

	return t;
}

float getTemperature() {
	i2c_start();
	i2c_write8(I2CAddr << 1);
	i2c_write8(CMD_GET_TEMPERATURE);
	i2c_stop();

	int t = readData();
	float tc = -46.85 + 175.72 / 65536.0 * (float) t;

	return tc;
}

float getHumidity() {
	i2c_start();
	i2c_write8(I2CAddr << 1);
	i2c_write8(CMD_GET_HUNIDITY);
	i2c_stop();

	int t = readData();
	float rh = -6 +125.0 / 65536.0 * (float) t;

	return rh;
}

float temp, hum;
void main(void) {
	WDTCTL = WDTPW + WDTHOLD;

	i2c_init();

	temp = getTemperature();
	hum = getHumidity();
}

Download: I2C_SHT21_2231.zip

Be Sociable, Share!