조도센서 ISL29023 sample code

본 글은 linux에서 i2c dev를 사용한 조도 센서 ISL29023 예제 코드를 싣고 있다.
조도 데이터를 읽어오는데 복잡한 부분은 없고, i2c를 통해 초기 설정 후 데이터 레지스터에서 필요할 때마다 데이터를 읽어오면 된다.



[소스코드]

#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <memory.h>
#include <sys/types.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>

#define _isl29023_range 64000
#define _isl29023_range_reg_val 3
#define _isl29023_adc_bit 16
#define _isl29023_adc_bit_reg_val 0

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;
}

int isl29023_init(int fd)
{
uint8_t cmd[2] = {0,};
int res = _isl29023_adc_bit_reg_val;
int range = _isl29023_range_reg_val;
// disable before set set res and range.
// reg : reg val
//COMMAND-I 0x00 : OP2 OP1 OP0 RESERVED(2bits) FLAG PRST1 PRST0
cmd[0] = 0x00;// COMMAND I
cmd[1] = 0;
if(write(fd, cmd,2) != 2)
{
perror("isl29023_init fail :");
return -1;
}
// reg   : reg val
//COMMANDII 0x01  : 0 0 0 0 RES1 RES0 RANGE1 RANGE0
cmd[0] = 0x01;// COMMAND II
cmd[1] = (res << 2) | range;
if(write(fd, cmd,2) != 2)
{
perror("isl29023_init fail :");
return -1;
}
return 0;
}

int isl29023_read(int fd)
{
uint8_t cmd[2] = {0,};
uint8_t data[2] = {0,};
uint8_t lsb = 0;
uint8_t msb = 0;
int lux = 0;
if(fd<=0) return -1;

// reg : reg val
//COMMAND-I 0x00 : OP2 OP1 OP0 RESERVED(2bits) FLAG PRST1 PRST0
cmd[0] = 0x00;
cmd[1] = (5 << 5);

if(write(fd, cmd,2) != 2)
{
perror("isl29023_read _ opmode sel fail :");
return -1;
}
th_delay(10); // 10 ms
cmd[0] = 0x02; // DATA LSB
if(write(fd, cmd,1) != 1)
{
perror("isl29023_read lsb cmd write :");
return -1;
}
if(read(fd,data,1) != 1)
{
perror("isl29023_read lsb read :");
return -1;
}
lsb = data[0];
cmd[0] = 0x03; // DATA MSB
if(write(fd, cmd,1) != 1)
{
perror("isl29023_read msb cmd write :");
return lsb;
}
if(read(fd,data,1) != 1)
{
perror("isl29023_read msb read :");
return lsb;
}
msb = data[0];

lux = ((msb << 8) | lsb);
lux = (lux*_isl29023_range)>>_isl29023_adc_bit;

return lux;
}

int main(int argc, char *argv[])
{
int lux = 0;
int isl29023_fd = open_dev("/dev/i2c-1",0x44);
if(isl29023_fd>0)
{
isl29023_init(isl29023_fd);
lux = isl29023_read(isl29023_fd);
close(isl29023_fd);
}
return 0;
}



[관련 포스트]

댓글

이 블로그의 인기 게시물

간단한 cfar 알고리즘에 대해

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

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

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

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