37 static int8_t tx_byte_ctr;
38 static int8_t rx_byte_ctr;
40 static uint8_t* tx_buf_ptr;
41 static uint8_t* rx_buf_ptr;
44 volatile unsigned int i;
46 static inline void i2c_send_byte(
void) {
47 *I2CDR = *(tx_buf_ptr++);
50 static inline void i2c_recv_byte(
void) {
51 *(rx_buf_ptr++) = *I2CDR;
65 void i2c_receiveinit(uint8_t slave_address, uint8_t byte_ctr, uint8_t *rx_buf) {
73 rx_byte_ctr = byte_ctr;
81 #ifdef I2C_NON_BLOCKING
84 I2C_MSTA | I2C_MTX | I2C_RXAK;
87 *I2CDR = (slave_address & 0x7f) <<1 | 0x01;
89 #ifndef I2C_NON_BLOCKING
104 void i2c_transmitinit(uint8_t slave_address, uint8_t byte_ctr, uint8_t *tx_buf) {
112 tx_byte_ctr = byte_ctr;
120 #ifdef I2C_NON_BLOCKING
126 *I2CDR = (slave_address & 0x7f) <<1;
128 #ifndef I2C_NON_BLOCKING
136 #ifndef I2C_NON_BLOCKING
138 uint8_t i2c_receive() {
139 while(rx_byte_ctr > 0) {
141 while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) ;
143 if (rx_byte_ctr == 1) {
147 if (*I2CSR & I2C_MCF) {
151 if (*I2CSR & I2C_MAL) {
153 printf(
"*** ERROR I2C: Arbitration lost\n");
158 while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) ;
159 if (*I2CSR & I2C_RXAK) {
161 printf(
"*** ERROR I2C: No ack received\n");
163 if (*I2CSR & I2C_MAL) {
165 printf(
"*** ERROR I2C: Arbitration lost\n");
172 void i2c_transmit() {
173 while(tx_byte_ctr > 0) {
175 while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) ;
177 if (*I2CSR & I2C_RXAK) {
179 printf(
"*** ERROR I2C: No ack received\n");
182 if (*I2CSR & I2C_MCF) {
186 if (*I2CSR & I2C_MAL) {
188 printf(
"*** ERROR I2C: Arbitration lost\n");
196 while(!(*I2CSR & I2C_MCF) || !(*I2CSR & I2C_MIF)) ;
197 if (*I2CSR & I2C_RXAK) {
199 printf(
"*** ERROR I2C: No ack received\n");
201 if (*I2CSR & I2C_MAL) {
203 printf(
"*** ERROR I2C: Arbitration lost\n");
216 void i2c_force_reset(
void) {
228 uint8_t i2c_transferred(
void) {
229 return (!i2c_busy() && rx_byte_ctr == 0 && tx_byte_ctr == 0);
236 uint8_t i2c_busy(
void) {
237 return ((*I2CSR & I2C_MBB) > 0);
244 void i2c_enable(
void) {
254 #ifdef I2C_NON_BLOCKING
260 *GPIO_FUNC_SEL0 |= (0x01 << (I2C_SCL*2)) | (0x01 << (I2C_SDA*2));
262 *GPIO_PAD_PU_EN0 |= (0x01 << I2C_SCL) | (0x01 << I2C_SDA);
263 *GPIO_PAD_PU_SEL0 |= (0x01 << I2C_SCL) | (0x01 << I2C_SDA);
269 void i2c_disable(
void) {
273 *I2CCKER = ~I2C_CKEN;
276 *GPIO_FUNC_SEL0 &= ~(0x01 << (I2C_SCL*2)) | (0x01 << (I2C_SDA*2));
278 *GPIO_PAD_PU_EN0 &= ~(0x01 << I2C_SCL) | (0x01 << I2C_SDA);
287 #ifdef I2C_NON_BLOCKING
288 void i2c_isr (
void) {
290 if (*I2CSR & I2C_MIF) {
291 if (*I2CSR & I2C_MCF) {
292 if (tx_buf_ptr != 0) {
293 if (*I2CSR & I2C_RXAK) {
295 printf(
"*** ERROR I2C: No ack received\n");
298 if (tx_byte_ctr > 0) {
304 if (rx_byte_ctr == 1) {
307 if (*I2CCR & I2C_MTX) {
311 }
else if (rx_byte_ctr > 0) {
319 if (*I2CSR & I2C_MAL) {
321 printf(
"*** ERROR I2C: Arbitration lost\n");
323 rx_byte_ctr = tx_byte_ctr = 0;