This commit is contained in:
Олег Бородин
2025-01-18 13:25:14 +02:00
parent 4b289d1c46
commit 9ae1e7bc07
10 changed files with 137 additions and 27115 deletions

56
i2c.c
View File

@@ -3,7 +3,10 @@
uint8_t i2c_error;
#define SET_TWBR (F_CPU/F_I2C-16UL)/(PSC_I2C*2UL)
void i2c_init(void) {
i2c_error = 0;
switch (PSC_I2C) {
case 4:
TWSR = 0x1;
@@ -18,28 +21,28 @@ void i2c_init(void) {
TWSR = 0x00;
break;
}
TWBR = (uint8_t) SET_TWBR;
TWBR = (uint8_t)SET_TWBR;
TWCR = (1 << TWEN);
}
void i2c_send_addr(uint8_t i2c_addr) {
void i2c_start(void) {
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
uint16_t timeout = F_CPU / F_I2C * 2.0;
while ((TWCR & (1 << TWINT)) == 0 && timeout != 0) {
timeout--;
if (timeout == 0) {
while ((TWCR & (1 << TWINT)) == 0) {
if (--timeout == 0) {
i2c_error |= (1 << I2C_ERR_START);
return;
}
};
TWDR = i2c_addr;
}
void i2c_write(uint8_t byte) {
TWDR = byte;
TWCR = (1 << TWINT) | (1 << TWEN);
timeout = F_CPU / F_I2C * 2.0;
while ((TWCR & (1 << TWINT)) == 0 && timeout != 0) {
timeout--;
if (timeout == 0) {
i2c_error |= (1 << I2C_ERR_SENDADRESS);
uint16_t timeout = F_CPU / F_I2C * 2.0;
while ((TWCR & (1 << TWINT)) == 0) {
if (--timeout == 0) {
i2c_error |= (1 << I2C_ERR_WRITE);
return;
}
};
@@ -47,29 +50,15 @@ void i2c_send_addr(uint8_t i2c_addr) {
void i2c_stop(void) {
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
while (TWCR & (1 << TWSTO));
}
void i2c_send_data(uint8_t byte) {
TWDR = byte;
TWCR = (1 << TWINT) | (1 << TWEN);
uint16_t timeout = F_CPU / F_I2C * 2.0;
while ((TWCR & (1 << TWINT)) == 0 && timeout != 0) {
timeout--;
if (timeout == 0) {
i2c_error |= (1 << I2C_ERR_BYTE);
return;
}
};
}
uint8_t i2c_read_ack(void) {
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWEA);
uint16_t timeout = F_CPU / F_I2C * 2.0;
while ((TWCR & (1 << TWINT)) == 0 && timeout != 0) {
timeout--;
if (timeout == 0) {
while ((TWCR & (1 << TWINT)) == 0) {
if (--timeout == 0) {
i2c_error |= (1 << I2C_ERR_READACK);
return 0;
}
@@ -77,14 +66,11 @@ uint8_t i2c_read_ack(void) {
return TWDR;
}
uint8_t i2c_read_nack(void) {
TWCR = (1 << TWINT) | (1 << TWEN);
uint16_t timeout = F_CPU / F_I2C * 2.0;
while ((TWCR & (1 << TWINT)) == 0 && timeout != 0) {
timeout--;
if (timeout == 0) {
uint16_t timeout = F_CPU / F_I2C * 4.0;
while ((TWCR & (1 << TWINT)) == 0) {
if (--timeout == 0) {
i2c_error |= (1 << I2C_ERR_READNACK);
return 0;
}