Files
hugo LAMY 28f0617e48 m06e00 ok
2025-03-16 10:43:33 +01:00

26 lines
1.1 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 0x38 // doc AHT20, 7.3 : address of thermistor
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
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
}