uint32_t i2c_dataread(uint16_t addrs, uint16_t byte_val) { uint8_t addrs_count = 2, re_read_limit = 0; uint8_t Read_Write_Error = 0; uint8_t byte_count = 0; uint8_t re_write_limit = 0; //For re-writing address byte uint32_t read_value = 0, hold_time = 0; uint8_t data_byte[4] = {0, 0, 0, 0}, addr_byte[2] = {0, 0}; //addr_byte[0] =(addrs >> 8) & 0xFF; addr_byte[0] =(addrs >> 0) & 0xFF; if((addrs >= 65535) && (byte_val > 1)) { Read_Write_Error = 1; } i2c_start(WRITE_BIT); for(byte_count = 1;((byte_count < addrs_count) && !Read_Write_Error); byte_count++) { //Waiting to enable the MSTPENDING bit to be set internally in status register //then only write possible in MSTCTL register while((I2C4->STAT & 0x01U) == 0) { hold_time++; if(hold_time > 1000) { hold_time = 0; break; } } // PRINTF("write hold_time %d\n", hold_time); if(I2C4->STAT == 0x805U) //Checks MASTER ready to transmitt or not { I2C4->MSTDAT = addr_byte[byte_count-1]; //Writing address bytes as msb and lsb I2C4->MSTCTL = 0x01U; } else { i2c_Stop(); delay1ms() re_write_limit++; byte_count = 0; if(re_write_limit > 4) { Read_Write_Error = 1; } i2c_start(WRITE_BIT); } } i2c_start(READ_BIT); hold_time = 0; for(byte_count = 1; ((byte_count < (byte_val+1)) && !Read_Write_Error); byte_count++) { //Waiting to enable the MSTPENDING bit to be set internally in status register //then only write possible in MSTCTL register while((I2C4->STAT & 0x01U) == 0) { hold_time++; if(hold_time > 1000) { hold_time = 0; break; } } // PRINTF("write hold_time %d\n", hold_time); if(I2C4->STAT == 0x803U) //Checks MASTER ready to receive or not { data_byte[byte_count-1] = I2C4->MSTDAT; I2C4->MSTCTL = 0x01U; } else { i2c_Stop(); delay1ms() if(re_read_limit > 4) { Read_Write_Error = 1; } re_read_limit++; byte_count = 0; //Re-send start condition with read bit if master is other than pending and receive status i2c_start(READ_BIT); } } i2c_Stop(); read_value = 0; //(((byte_val-1)-byte_count)*8) - logic is for shifting data_byte values and retun as a complete no of bytes readed // here (bytes_val - 1) - is for 0 to 3(if 4 bytes) - no. of bytes - 1 // (- byte_count) - is for getting 0 when writing msb as first byte // * 8 means left shifting 8 bytes from actual byte value for(byte_count = 0; byte_count < byte_val; byte_count++) { read_value = read_value + (data_byte[byte_count]<<(((byte_val-1)-byte_count)*8)); // PRINTF("0x%2x\t", data_byte[byte_count]); } // PRINTF("\r\n\r\n"); return read_value; }