44 lines
No EOL
1.1 KiB
C
44 lines
No EOL
1.1 KiB
C
#include <avr/io.h>
|
|
#include <util/delay.h>
|
|
#include "i2c.h"
|
|
|
|
void initI2C() {
|
|
// Set the prescaler to 1
|
|
TWSR &= ~(1 << TWPS0);
|
|
TWSR &= ~(1 << TWPS1);
|
|
// Set the bit rate to 100kHz
|
|
TWBR = ((F_CPU / 100000) - 16) / 2;
|
|
}
|
|
|
|
void I2C_start() {
|
|
// Send the start condition
|
|
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
|
|
// Wait for the start condition to be sent
|
|
while (!(TWCR & (1 << TWINT)))
|
|
;
|
|
}
|
|
|
|
void I2C_stop() {
|
|
// Send the stop condition
|
|
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
|
|
// Wait for the stop condition to be sent
|
|
while (TWCR & (1 << TWSTO));
|
|
}
|
|
|
|
void I2C_write(uint8_t data) {
|
|
// Load the data into the data register
|
|
TWDR = data;
|
|
// Start transmission of data
|
|
TWCR = (1 << TWINT) | (1 << TWEN);
|
|
// Wait for the data to be sent
|
|
while (!(TWCR & (1 << TWINT)));
|
|
}
|
|
|
|
uint8_t I2C_read(uint8_t ack) {
|
|
// Enable TWI, generate ACK (if ack = 1) and clear TWI interrupt flag
|
|
TWCR = (1 << TWINT) | (1 << TWEN) | (ack << TWEA);
|
|
// Wait until TWI finish its current job (read operation)
|
|
while (!(TWCR & (1 << TWINT)));
|
|
// Return received data
|
|
return TWDR;
|
|
} |