27 lines
1.2 KiB
C
27 lines
1.2 KiB
C
#include "header.h"
|
|
|
|
#define TWI_PRESCALE_VALUE 1 // can be 1, 4, 16, 64
|
|
#define TWI_FREQ 100000UL // 100kHz I2C
|
|
#define SLAVE_ADDRESS 42 // 22.3.3 : address 0000000 and 1111xxx are reserved, 42 is 0101010
|
|
|
|
void i2c_init(void) {
|
|
TWSR = TWI_PRESCALE_SET(TWI_PRESCALE_VALUE); // 22.9.3 : (Status Register) set prescaler
|
|
TWBR = ((F_CPU / TWI_FREQ) - 16) / (2 * TWI_PRESCALE_VALUE); // 22.9.1 : (Bit Rate Register) set SCL frequency (formula from datasheet, 22.5.2)
|
|
}
|
|
|
|
void i2c_start(void) {
|
|
TWCR = SEND_START_CONDITION; // 22.9.2 : (Control Register) send Start condition (22.7.1) ! writting 1 to TWINT clears it (set it to 0)
|
|
while (!(TEST(TWCR, TWINT))); // p225 example code : Wait for TWINT Flag set. This indicates that the START condition has been transmitted
|
|
|
|
uint8_t status = TWSR & 0b11111000; // Table 22-2. Status codes for Master Transmitter Mode
|
|
uart_printstr_itoa_base_endl(status, 2);
|
|
if (status != TW_START && status != TW_REP_START) {
|
|
TWCR = SEND_STOP_CONDITION;
|
|
return;
|
|
}
|
|
}
|
|
|
|
void i2c_stop(void) {
|
|
TWCR = SEND_STOP_CONDITION; // 22.9.2 : send stop condition
|
|
}
|