1 /* Library made by: g4lvanix
2 * Github repository: https://github.com/g4lvanix/I2C-master-lib
8 #include "i2c_master.h"
10 #define F_SCL 400000UL // SCL frequency
12 #define TWBR_val ((((F_CPU / F_SCL) / Prescaler) - 16 ) / 2)
16 TWBR = (uint8_t)TWBR_val;
19 uint8_t i2c_start(uint8_t address)
21 // reset TWI control register
23 // transmit START condition
24 TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
25 // wait for end of transmission
26 while( !(TWCR & (1<<TWINT)) );
28 // check if the start condition was successfully transmitted
29 if((TWSR & 0xF8) != TW_START){ return 1; }
31 // load slave address into data register
33 // start transmission of address
34 TWCR = (1<<TWINT) | (1<<TWEN);
35 // wait for end of transmission
36 while( !(TWCR & (1<<TWINT)) );
38 // check if the device has acknowledged the READ / WRITE mode
39 uint8_t twst = TW_STATUS & 0xF8;
40 if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) return 1;
45 uint8_t i2c_write(uint8_t data)
47 // load data into data register
49 // start transmission of data
50 TWCR = (1<<TWINT) | (1<<TWEN);
51 // wait for end of transmission
52 while( !(TWCR & (1<<TWINT)) );
54 if( (TWSR & 0xF8) != TW_MT_DATA_ACK ){ return 1; }
59 uint8_t i2c_read_ack(void)
62 // start TWI module and acknowledge data after reception
63 TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
64 // wait for end of transmission
65 while( !(TWCR & (1<<TWINT)) );
66 // return received data from TWDR
70 uint8_t i2c_read_nack(void)
73 // start receiving without acknowledging reception
74 TWCR = (1<<TWINT) | (1<<TWEN);
75 // wait for end of transmission
76 while( !(TWCR & (1<<TWINT)) );
77 // return received data from TWDR
81 uint8_t i2c_transmit(uint8_t address, uint8_t* data, uint16_t length)
83 if (i2c_start(address | I2C_WRITE)) return 1;
85 for (uint16_t i = 0; i < length; i++)
87 if (i2c_write(data[i])) return 1;
95 uint8_t i2c_receive(uint8_t address, uint8_t* data, uint16_t length)
97 if (i2c_start(address | I2C_READ)) return 1;
99 for (uint16_t i = 0; i < (length-1); i++)
101 data[i] = i2c_read_ack();
103 data[(length-1)] = i2c_read_nack();
110 uint8_t i2c_writeReg(uint8_t devaddr, uint8_t regaddr, uint8_t* data, uint16_t length)
112 if (i2c_start(devaddr | 0x00)) return 1;
116 for (uint16_t i = 0; i < length; i++)
118 if (i2c_write(data[i])) return 1;
126 uint8_t i2c_readReg(uint8_t devaddr, uint8_t regaddr, uint8_t* data, uint16_t length)
128 if (i2c_start(devaddr)) return 1;
132 if (i2c_start(devaddr | 0x01)) return 1;
134 for (uint16_t i = 0; i < (length-1); i++)
136 data[i] = i2c_read_ack();
138 data[(length-1)] = i2c_read_nack();
147 // transmit STOP condition
148 TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);