습도 온도 센서 SHT3x sample code

본 글은 linux에서 i2c dev를 사용한 습도 온도 센서 SHT3x의 예제 코드를 싣고 있다.
SHT3x의 자료는 아래 링크에서 찾아볼 수 있다.


본들의 예제 코드는 single shot mode에서 온도 습도 데이터를 읽어오며, single shot mode에서의 커맨드와 온도 습도 변환 공식은 아래와 같이 datasheet를 참조 했다.


[소스 코드]

#include <pthread.h>
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <string.h>

#include <sys/types.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>

int open_dev(char *name, int address)
{
int fd = open(name,O_RDWR);
if(fd <= 0)
{
perror("i2c open ");
return 0;
}
if (ioctl(fd, I2C_SLAVE, address)<0)
{
perror("i2c set address ");
close(fd);
return 0;
}
return fd;
}


uint8_t crc8(const uint8_t* data, uint8_t len)
{
  uint8_t crc = 0xff;
  uint8_t byteCtr = 0;
  
  for (byteCtr = 0; byteCtr < len; ++byteCtr) 
  {
uint8_t bit = 0;
    crc ^= (data[byteCtr]);
    for (bit = 8; bit > 0; --bit) 
    {
      if (crc & 0x80) 
      {
        crc = (crc << 1) ^ 0x31;
      } 
      else
      {
        crc = (crc << 1);
      }
    }
  }
  return crc;
}


int sht3x_read(int fd, float *pTemperature ,float *pHumidity)
{
float Humidity = -1;
float Temperature = -999;
// -- conversion parameters
// T_OUT = A + B * (T_IN  / C) Celsius
float mA = -45;
float mB = 175;
float mC = 65535; // (2^16) - 1
// RH_OUT = X * (RH_IN / Y)
float mX = 100;
float mY = 65535; // (2^16) - 1

uint8_t cmd[2] = {0,};
uint8_t data[6] = {0,};
uint16_t val = 0;

cmd[0] = 0x2c;
cmd[1] = 0x0d;
if(write(fd, cmd,2) != 2)
{
perror("sht3x_read i2c write :");
return -1;
}
if(read(fd,data,6) != 6)
{
perror("sht3x_read i2c read :");
return -1;
}
if (crc8(data+0, 2) != data[2] || crc8(data+3, 2) != data[5]) 
{
printf("sht3x_read crc err\n");
return -1;
}
// calculate  Temperature and Humidity
val = (data[0] << 8) + data[1];
Temperature = mA + mB * (val / mC);
if(pTemperature) *pTemperature = Temperature;

val = (data[3] << 8) + data[4];
Humidity = mX * (val / mY);
if(pHumidity) *pHumidity = Humidity;
return 0;
}


int main(int argc, char *argv[])
{
float Temperature;
float Humidity;
int sht3x_fd = open_dev("/dev/i2c-2",0x45);
if(sht3x_fd>0)
{
sht3x_read(sht3x_fd, &Temperature,&Humidity);
close(sht3x_fd);
}
return 0;
}


[관련 포스트]

댓글

이 블로그의 인기 게시물

간단한 cfar 알고리즘에 대해

windows에서 간단하게 크롬캐스트(Chromecast)를 통해 윈도우 화면 미러링 방법

쉽게 설명한 파티클 필터(particle filter) 동작 원리와 예제

base64 인코딩 디코딩 예제 c 소스

간단한 칼만 필터(Kalman Filter) 소스 코드와 사용 예제