Better comments and debug output in i2c

This commit is contained in:
Imbus 2024-03-24 02:35:21 +01:00
parent c43fae4e45
commit 19c7d6d0bc
2 changed files with 16 additions and 0 deletions

7
i2c.c
View file

@ -4,6 +4,7 @@
#include <util/delay.h>
#include <util/twi.h>
#include <stdint.h>
#include "uart.h" // DEBUG macro
void I2C_init() {
// Set the prescaler to 1
@ -17,23 +18,29 @@ uint8_t I2C_start(uint8_t addr) {
// Send the start condition
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
DEBUG("Waiting for start condition to be sent");
// Wait for the start condition to be sent
while (!(TWCR & (1 << TWINT)))
;
DEBUG("Start condition sent");
// Load the address of the slave device
TWDR = addr;
DEBUG("Sending address");
// Clear the TWINT bit to start the transmission
TWCR = (1 << TWINT) | (1 << TWEN);
DEBUG("Waiting for address to be sent");
// Wait for the address to be sent
while (!(TWCR & (1 << TWINT)))
;
DEBUG("Address sent");
// Get the status of the transmission
uint8_t status = TWSR & 0xF8;
DEBUG("Checking status");
// Return true if the slave acknowledged the address
return (status == TW_MT_SLA_ACK || status == TW_MR_SLA_ACK);
}

9
i2c.h
View file

@ -4,8 +4,17 @@
#define TW_WRITE 0
#define TW_READ 1
// Function to initialize I2C
void I2C_init();
// Function to send start condition
uint8_t I2C_start(uint8_t addr);
// Function to send stop condition
void I2C_stop();
// Write a byte to I2C bus
uint8_t I2C_write(uint8_t data);
// Read a byte from I2C bus
uint8_t I2C_read(uint8_t ack);