Forum Discussion
Altera_Forum
Honored Contributor
19 years agosome sample code
// I2C REGISTERS# define I2C_PRERLO 0# define I2C_PRERHI 1# define I2C_CTR 2# define I2C_TXR 3# define I2C_RXR 3# define I2C_CR 4# define I2C_SR 4 # define CTR_EN BIT7# define CTR_IEN BIT6 # define CR_STA BIT7# define CR_STO BIT6# define CR_RD BIT5# define CR_WR BIT4# define CR_NACK BIT3 // # define CR_NC1 BIT2# define CR_NC2 BIT1# define CR_IACK BIT0 # define SR_RXNACK BIT7# define SR_BUSY BIT6# define SR_AL BIT5# define SR_NC1 BIT4# define SR_NC2 BIT3# define SR_NC3 BIT2# define SR_TIP BIT1# define SR_IF BIT0 # define I2C_WR 0# define I2C_RD BIT0 int32_t i2c_init(void); int32_t i2c_write_byte(uint8_t ctrl,uint8_t data,uint8_t *i2c_status); int32_t i2c_read_byte(uint8_t ctrl,uint8_t *data,uint8_t *i2c_status); // write and read time is about 25us for one byte // we have to make timeout longer because of interrupts# define I2C_TIMEOUT (1000*50) // 40us (50 cputicks/us) int32_t i2c_init(void) { IOWR(I2C_MASTER_0_BASE,I2C_CTR,0x00); // disable i2c IOWR(I2C_MASTER_0_BASE,I2C_PRERLO,24); // sclk = 400khz IOWR(I2C_MASTER_0_BASE,I2C_PRERHI,0); // sclk = 400khz IOWR(I2C_MASTER_0_BASE,I2C_CTR,CTR_EN); // enable i2c return 0; }; int32_t i2c_write_byte(uint8_t ctrl,uint8_t data,uint8_t *i2c_status) { int32_t err=0; uint8_t status=0; uint32_t t1=0; char temp[10]; IOWR(I2C_MASTER_0_BASE,I2C_TXR,data); // IOWR(I2C_MASTER_0_BASE,I2C_CR,ctrl | CR_WR); // status=IORD(I2C_MASTER_0_BASE,I2C_SR); alt_timestamp_start(); while(!(status&SR_IF)) { status=IORD(I2C_MASTER_0_BASE,I2C_SR); t1=alt_timestamp(); if(t1>I2C_TIMEOUT) { printf("***ERROR I2C write byte timeout:status:0x%02x %s\r\n",status,binTostr(temp,status)); err=-1; break; } } if(status&SR_RXNACK) { printf("***ERROR I2C write byte ack failed:0x%02x %s\r\n",status,binTostr(temp,status)); err=-1; } // printf("I2C write byte time:%05d\r\n",t1/50); IOWR(I2C_MASTER_0_BASE,I2C_CR,CR_IACK); // *i2c_status=status; return err; } // normally ctrl = CR_ACK int32_t i2c_read_byte(uint8_t ctrl,uint8_t *data,uint8_t *i2c_status) { int32_t err=0; uint8_t status=0; uint32_t t1=0; char temp[10]; IOWR(I2C_MASTER_0_BASE,I2C_CR,ctrl | CR_RD); status=IORD(I2C_MASTER_0_BASE,I2C_SR); alt_timestamp_start(); while(!(status&SR_IF)) { status=IORD(I2C_MASTER_0_BASE,I2C_SR); t1=alt_timestamp(); if(t1>I2C_TIMEOUT) { printf("***ERROR I2C read byte timeout:status:0x%02x %s\r\n",status,binTostr(temp,status)); err=-1; break; } } // printf("I2C read byte time:%05d\r\n",t1/50); IOWR(I2C_MASTER_0_BASE,I2C_CR,CR_IACK); // *data=IORD(I2C_MASTER_0_BASE,I2C_RXR); *i2c_status=status; return err; }