由于机器挂了两个I2C所以应用层也需要操作两个
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <string.h>
#include <sys/ioctl.h>
#include <linux/i2c-dev.h>
#include "log/log.h"
#include "include/root.h"
#include "24c256.h"
int fd_eeprom[MAXNUM_E2P] = {-1, -1};
int i2c_init(unsigned int port)
{
int fd;
int addr=0x52;
if(port >= MAXNUM_E2P)
return 1;
if(-1 != fd_eeprom[port])
close(fd_eeprom[port]);
fd = open("/dev/i2c-0",O_RDWR);
if(fd==-1)
{
print_log(LOGLVL_ERROR,"cann't open i2c device");
return 1;
}
print_log(LOGLVL_DEBUG,"open i2c device\n");
fd_eeprom[port] = fd;
eep_rcvst[port].len = 0;
memset(&eep_rcvst[port].buf[0],0,SIZE_I2C_RCVBUF);
if(ioctl(fd,I2C_SLAVE_FORCE,addr)<0 ) printf("error\n");
if(ioctl(fd,I2C_TIMEOUT,1)<0) printf("error\n");
if(ioctl(fd,I2C_RETRIES,10)<0) printf("error\n");
return 0;
}
void appi2c_close(unsigned int port)
{
if((port >= MAXNUM_E2P) || (-1 == fd_eeprom[port]))
return;
close(fd_eeprom[port]);
fd_eeprom[port] = -1;
}
//buf[0] address message
//buf[1]开始是真正的内容
int appi2c_write(unsigned int port,int addr, unsigned char *buf, int len)
{
int fd;
unsigned char write_buf[SIZE_I2C_RCVBUF];
memset(write_buf,0,sizeof(write_buf));
if(port >= MAXNUM_E2P)
return 1;
fd = fd_eeprom[port];
if(fd< 0)
return 1;
write_buf[0]=(addr>>8)&0xff;
write_buf[1]=addr&0xff;
memcpy(&write_buf[2],buf,len);
if( write(fd,write_buf,len+2)!=len+2)
{
printf("error,i2c write\n");
}
return 0;
}
int appi2c_recv(unsigned int port, int addr, int len)
{
int fd, rtn;
char address[2];
if(port >= MAXNUM_E2P)
return -1;
fd = fd_eeprom[port];
if(fd < 0)
return -1;
memset(&eep_rcvst[port].buf[0],0,SIZE_I2C_RCVBUF);
address[0]=(addr>>8)&0xff;
address[1]=addr&0xff;
if(write(fd,address,2)!=2)
{
printf("error,i2c write\n");
}
if(eep_rcvst[port].len>= 0)
{
eep_rcvst[port].len = 0;
rtn = read(fd,eep_rcvst[port].buf,len);
if((rtn<0)||(rtn > SIZE_I2C_RCVBUF))
{
printf("error,i2c read,rtn=%d\n",rtn);
return 0;
}
eep_rcvst[port].len = rtn;
}
if(eep_rcvst[port].len > len)
rtn = len;
else
rtn = eep_rcvst[port].len;
// memcpy(buf, &eep_rcvst[port].buf[eep_rcvst[port].head], rtn);
// app_sleep(200);
return rtn;
}