#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include "./typedef.h"
#define CHIP_ADDR 0x57
void I2c_Init(PS_SYS_REG p_sys_reg)
{
PS_PIO p_pio_a = p_sys_reg->PioA;
U32 mask = 0x400000;
p_pio_a->PIO_IDR = mask;
p_pio_a->PIO_PPUER = mask;
p_pio_a->PIO_MDDR = mask;
p_pio_a->PIO_CODR = mask;
p_pio_a->PIO_OER = mask;
p_pio_a->PIO_PER = mask;
}
int I2c_Device(int fd, U8 addr, U8 attr, PS_SYS_REG p_sys_reg)
{
int rtn;
if(attr) p_sys_reg->PioA->PIO_SODR = 0x400000;
else p_sys_reg->PioA->PIO_CODR = 0x400000;
rtn = ioctl(fd, I2C_TENBIT, 0);
if(rtn < 0) return 70000;
rtn = ioctl(fd, I2C_SLAVE, addr);
if(rtn < 0) return 70000;
return 0;
}
int Edid_Read(int fd, U8 *buf, U8 ex_addr, U8 in_addr, PS_SYS_REG p_sys_reg)
{
int rtn=0;
volatile int i;
p_sys_reg->PioA->PIO_SODR = 0x400000;
rtn = ioctl(fd, I2C_TENBIT, 0);
if(rtn < 0) return 70000;
rtn = ioctl(fd, I2C_SLAVE, ex_addr);
if(rtn < 0) return 70000;
rtn = write(fd,&in_addr,1);
if (rtn != 1){
printf("Can't write i2c in_addr %d\n", in_addr);
return 0x70004;
}
rtn = read(fd,buf,128);
if(rtn!=128) rtn = 0x70002;
for(i=0; i<1000000; i++);
return rtn;
}
int Eeprom_Read(int fd, char *buf, U8 addr, int count, PS_SYS_REG p_sys_reg)
{
int rtn=0;
volatile int i;
p_sys_reg->PioA->PIO_CODR = 0x400000;
rtn = ioctl(fd, I2C_TENBIT, 0);
if(rtn < 0) return 70000;
rtn = ioctl(fd, I2C_SLAVE, 0x56);
if(rtn < 0) return 70000;
rtn = write(fd,&addr,1);
if (rtn != 1){
printf("Can't write i2c addr %d\n", addr);
return 0x70002;
}
rtn = read(fd,buf,count);
if(rtn!=count) rtn = 0x70003;
for(i=0; i<1000000; i++);
return rtn;
}
int Eeprom_Write(int fd, char *buf, U8 addr, int count, PS_SYS_REG p_sys_reg)
{
int rtn=0;
char *s_buf;
volatile int i;
p_sys_reg->PioA->PIO_CODR = 0x400000;
rtn = ioctl(fd, I2C_TENBIT, 0);
if(rtn < 0) return 70000;
rtn = ioctl(fd, I2C_SLAVE, 0x56);
if(rtn < 0) return 70000;
s_buf=malloc(8);
for(; count>=4; count-=4)
{
memcpy(s_buf+1, buf, 4);
s_buf[0]=addr;
rtn = write(fd,s_buf,5);
if(rtn != 5) rtn = 0x70001;
for(i=0; i<100000; i++);
buf+=4;
addr+=4;
}
if(count)
{
memcpy(s_buf+1, buf, count);
s_buf[0]=addr;
rtn = write(fd,s_buf,count+1);
if(rtn != count+1) rtn = 0x70001;
for(i=0; i<100000; i++);
}
return rtn;
}
int I2c_Write(int fd, char *buf, U8 addr, int count, PS_SYS_REG p_sys_reg)
{
int rtn=0;
char *s_buf;
volatile int i;
s_buf=malloc(count+1);
memcpy(s_buf+1,buf,count);
s_buf[0]=addr;
rtn = write(fd,s_buf,count+1);
if(rtn != count+1) rtn = 0x70001;
for(i=0; i<1000000; i++);
return rtn;
}
int I2c_Read(int fd, char *buf, U8 addr, int count, PS_SYS_REG p_sys_reg)
{
int rtn;
volatile int i;
rtn = write(fd,&addr,1);
if (rtn != 1){
printf("Can't write i2c addr %d\n", addr);
return 0x70002;
}
rtn = read(fd,buf,count);
if(rtn!=count) rtn = 0x70003;
for(i=0; i<1000000; i++);
return rtn;
}