#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <strings.h>
#include <linux/i2c-dev.h>
#include <linux/i2c.h>
#include <stdlib.h>
#include <stdint.h>
unsigned char slave_address = 0x2A; /* 设备地址 */
static int iic_write(int i2c_fd, unsigned int reg_address, unsigned int reg_val)
{
struct i2c_rdwr_ioctl_data work_queue;
int ret;
work_queue.nmsgs = 2;
work_queue.msgs = (struct i2c_msg *)malloc(work_queue.nmsgs * sizeof(struct i2c_msg));
if (!work_queue.msgs)
{
printf("msgs memery alloc error\n");
close(i2c_fd);
return 0;
}
if ((work_queue.msgs[0].buf = (unsigned char *)malloc(2 * sizeof(unsigned char))) == NULL)
{
printf("buf memery alloc error...\n");
close(i2c_fd);
return 0;
}
(work_queue.msgs[0]).len = 2;
(work_queue.msgs[0]).flags = 0;
(work_queue.msgs[0]).addr = slave_address;
(work_queue.msgs[0]).buf[0] = reg_address;
(work_queue.msgs[0]).buf[1] = reg_val;
work_queue.nmsgs = 1;
ioctl(i2c_fd, I2C_RDWR, (unsigned long)&work_queue);
if (ret < 0)
{
printf("Error during I2C_RDWR ioctl with error code: %d\n", ret);
return 0;
}
free(work_queue.msgs[0].buf);
free(work_queue.msgs);
return 1;
}
static int iic_read(int i2c_fd, unsigned int reg_address)
{
struct i2c_rdwr_ioctl_data work_queue;
unsigned char val;
int ret;
work_queue.nmsgs = 2;
work_queue.msgs = (struct i2c_msg *)malloc(work_queue.nmsgs * sizeof(struct i2c_msg));
if (!work_queue.msgs)
{
printf("Memery alloc error\n");
close(i2c_fd);
return 0;
}
val = (unsigned char)reg_address;
(work_queue.msgs[0]).len = 1;
(work_queue.msgs[0]).flags = 0;
(work_queue.msgs[0]).addr = slave_address;
(work_queue.msgs[0]).buf = &val;
(work_queue.msgs[1]).len = 1;
(work_queue.msgs[1]).flags = 1;
(work_queue.msgs[1]).addr = slave_address;
(work_queue.msgs[1]).buf = &val;
ret = ioctl(i2c_fd, I2C_RDWR, (unsigned long)&work_queue);
if (ret < 0)
{
printf("Error during I2C_RDWR ioctl with error code: %d\n", ret);
return 0;
}
free(work_queue.msgs);
return val;
}
/*****************************************************************************
延时函数(ms)
******************************************************************************/
void _alpu_delay_ms(unsigned int i)
{
usleep(2000 * i);
}
int main(void)
{
int i_Temp;
char s_Dev[] = "/dev/i2c-0";
unsigned char device_addr = 0x2A; /* 设备地址 */
int i_File = open(s_Dev, O_RDWR);
if (i_File < 0)
{
printf("open failed [%s]\n", s_Dev);
perror(s_Dev);
return 0;
}
printf("open ok ![%s]\n", s_Dev);
i_Temp = ioctl(i_File, I2C_TIMEOUT, 1); //超时时间
if (i_Temp < 0)
perror("ioctl error1");
i_Temp = ioctl(i_File, I2C_RETRIES, 2); //重复次数
if (i_Temp < 0)
perror("ioctl error2");
while (1)
{
usleep(1000 * 1000); // 休眠一秒
// iic_write(i_File, 0x55, 0xAA);
int res = iic_read(i_File, 0xAA);
printf("[%.2X]\n", res);
uint32_t vocvalue = res;
float voc_value = (float)(vocvalue * 5) / 200;
printf("采集值为:[%0.3f]\r\n", voc_value);
}
// _i2c_read(0x55, 0xAA);
return 1;
}
运行结果