36 static int8_t tx_byte_ctr;
37 static int8_t rx_byte_ctr;
39 static uint8_t* tx_buf_ptr;
40 static uint8_t* rx_buf_ptr;
43 volatile unsigned int i;
45 static inline void i2c_send_byte(
void) {
46 *I2CDR = *(tx_buf_ptr++);
49 static inline void i2c_recv_byte(
void) {
50 *(rx_buf_ptr++) = *I2CDR;
64 void i2c_receiveinit(uint8_t slave_address, uint8_t byte_ctr, uint8_t *rx_buf) {
72 rx_byte_ctr = byte_ctr;
80 #ifdef I2C_NON_BLOCKING
83 I2C_MSTA | I2C_MTX | I2C_RXAK;
86 *I2CDR = (slave_address & 0x7f) <<1 | 0x01;
88 #ifndef I2C_NON_BLOCKING
103 void i2c_transmitinit(uint8_t slave_address, uint8_t byte_ctr, uint8_t *tx_buf) {
111 tx_byte_ctr = byte_ctr;
119 #ifdef I2C_NON_BLOCKING
125 *I2CDR = (slave_address & 0x7f) <<1;
127 #ifndef I2C_NON_BLOCKING
135 #ifndef I2C_NON_BLOCKING
137 uint8_t i2c_receive() {
138 while(rx_byte_ctr > 0) {
140 while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) ;
142 if (rx_byte_ctr == 1) {
146 if (*I2CSR & I2C_MCF) {
150 if (*I2CSR & I2C_MAL) {
152 printf(
"*** ERROR I2C: Arbitration lost\n");
157 while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) ;
158 if (*I2CSR & I2C_RXAK) {
160 printf(
"*** ERROR I2C: No ack received\n");
162 if (*I2CSR & I2C_MAL) {
164 printf(
"*** ERROR I2C: Arbitration lost\n");
171 void i2c_transmit() {
172 while(tx_byte_ctr > 0) {
174 while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) ;
176 if (*I2CSR & I2C_RXAK) {
178 printf(
"*** ERROR I2C: No ack received\n");
181 if (*I2CSR & I2C_MCF) {
185 if (*I2CSR & I2C_MAL) {
187 printf(
"*** ERROR I2C: Arbitration lost\n");
195 while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) ;
196 if (*I2CSR & I2C_RXAK) {
198 printf(
"*** ERROR I2C: No ack received\n");
200 if (*I2CSR & I2C_MAL) {
202 printf(
"*** ERROR I2C: Arbitration lost\n");
215 void i2c_force_reset(
void) {
227 uint8_t i2c_transferred(
void) {
228 return (!i2c_busy() && rx_byte_ctr == 0 && tx_byte_ctr == 0);
235 uint8_t i2c_busy(
void) {
236 return ((*I2CSR & I2C_MBB) > 0);
253 #ifdef I2C_NON_BLOCKING
259 *GPIO_FUNC_SEL0 |= (0x01 << (I2C_SCL*2)) | (0x01 << (I2C_SDA*2));
261 *GPIO_PAD_PU_EN0 |= (0x01 << I2C_SCL) | (0x01 << I2C_SDA);
262 *GPIO_PAD_PU_SEL0 |= (0x01 << I2C_SCL) | (0x01 << I2C_SDA);
272 *I2CCKER = ~I2C_CKEN;
275 *GPIO_FUNC_SEL0 &= ~(0x01 << (I2C_SCL*2)) | (0x01 << (I2C_SDA*2));
277 *GPIO_PAD_PU_EN0 &= ~(0x01 << I2C_SCL) | (0x01 << I2C_SDA);
286 #ifdef I2C_NON_BLOCKING
287 void i2c_isr (
void) {
289 if (*I2CSR & I2C_MIF) {
290 if (*I2CSR & I2C_MCF) {
291 if (tx_buf_ptr != 0) {
292 if (*I2CSR & I2C_RXAK) {
294 printf(
"*** ERROR I2C: No ack received\n");
297 if (tx_byte_ctr > 0) {
303 if (rx_byte_ctr == 1) {
306 if (*I2CCR & I2C_MTX) {
310 }
else if (rx_byte_ctr > 0) {
318 if (*I2CSR & I2C_MAL) {
320 printf(
"*** ERROR I2C: Arbitration lost\n");
322 rx_byte_ctr = tx_byte_ctr = 0;
void i2c_enable(void)
Configure serial controller in I2C mode and set I2C speed.
void i2c_disable(void)
Configure serial controller in disabled mode.