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 TWSR = 0; /* no prescaler */
17 TWBR = (uint8_t)TWBR_val;
21 uint8_t i2c_start(uint8_t address)
23 // reset TWI control register
25 // transmit START condition
26 TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
27 // wait for end of transmission
28 while( !(TWCR & (1<<TWINT)) );
30 // check if the start condition was successfully transmitted
31 if(((TW_STATUS & 0xF8) != TW_START) && ((TW_STATUS & 0xF8) != TW_REP_START)){ return 1; }
33 // load slave address into data register
35 // start transmission of address
36 TWCR = (1<<TWINT) | (1<<TWEN);
37 // wait for end of transmission
38 while( !(TWCR & (1<<TWINT)) );
40 // check if the device has acknowledged the READ / WRITE mode
41 uint8_t twst = TW_STATUS & 0xF8;
42 if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) return 1;
47 uint8_t i2c_write(uint8_t data)
49 // load data into data register
51 // start transmission of data
52 TWCR = (1<<TWINT) | (1<<TWEN);
53 // wait for end of transmission
54 while( !(TWCR & (1<<TWINT)) );
56 if( (TW_STATUS & 0xF8) != TW_MT_DATA_ACK ){ return 1; }
61 uint8_t i2c_read_ack(void)
64 // start TWI module and acknowledge data after reception
65 TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
66 // wait for end of transmission
67 while( !(TWCR & (1<<TWINT)) );
68 // return received data from TWDR
72 uint8_t i2c_read_nack(void)
75 // start receiving without acknowledging reception
76 TWCR = (1<<TWINT) | (1<<TWEN);
77 // wait for end of transmission
78 while( !(TWCR & (1<<TWINT)) );
79 // return received data from TWDR
83 uint8_t i2c_transmit(uint8_t address, uint8_t* data, uint16_t length)
85 if (i2c_start(address | I2C_WRITE)) return 1;
87 for (uint16_t i = 0; i < length; i++)
89 if (i2c_write(data[i])) return 1;
97 uint8_t i2c_receive(uint8_t address, uint8_t* data, uint16_t length)
99 if (i2c_start(address | I2C_READ)) return 1;
101 for (uint16_t i = 0; i < (length-1); i++)
103 data[i] = i2c_read_ack();
105 data[(length-1)] = i2c_read_nack();
112 uint8_t i2c_writeReg(uint8_t devaddr, uint8_t regaddr, uint8_t* data, uint16_t length)
114 if (i2c_start(devaddr | 0x00)) return 1;
118 for (uint16_t i = 0; i < length; i++)
120 if (i2c_write(data[i])) return 1;
128 uint8_t i2c_readReg(uint8_t devaddr, uint8_t regaddr, uint8_t* data, uint16_t length)
130 if (i2c_start(devaddr)) return 1;
134 if (i2c_start(devaddr | 0x01)) return 1;
136 for (uint16_t i = 0; i < (length-1); i++)
138 data[i] = i2c_read_ack();
140 data[(length-1)] = i2c_read_nack();
149 // transmit STOP condition
150 TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
151 // wait until stop condition is executed and bus released
152 while(TWCR & (1<<TWSTO));