Files
Scanning the repository...
Last update 4 years 7 months
by Tommigems
Filesfirmware | |
---|---|
.. | |
.vscode | |
fatfs | |
.gitignore | |
Makefile | |
i2c.c | |
i2c.h | |
main.c | |
usart.c | |
usart.h |
i2c.c#include "i2c.h" #include <avr/io.h> /* Define bit rate */ #define SCL_CLK F_CPU/(16+ 2(TWBR)*pow(4,TWPS0) #define BITRATE(TWSR) ((F_CPU/SCL_CLK)-16)/(2*pow(4,(TWSR&((1<<TWPS0)|(1<<TWPS1))))) int I2C_transmit(char data) { TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN); // Enable TWI, Send START condition while (!(TWCR & (1<<TWINT))); // Wait for TWINT Flag set. This indicates that the START condition has been transmitted if ((TWSR & 0xF8) != 0x08) {return 0;} // Check value of TWI Status Register. Mask prescaler bits. If status different from START then return 0 TWDR = data; // Write SLA+W in TWI data register TWCR = (1<<TWINT) | (1<<TWEN); // Load SLA_W into TWDR Register. Clear TWINT bit in TWCR to start transmission of address while (!(TWCR & (1<<TWINT))); // Wait for TWINT Flag set. This indicates that the SLA+W has been transmitted, and ACK/NACK has been received if ((TWSR & 0xF8) != TWEA) {return 0;} // Check value of TWI Status Register. Mask prescaler bits. If status different from ack bit then return 0 TWDR = 0x18; TWCR = (1 << TWINT) | (1 << TWEN); // Load DATA into TWDR Register. Clear TWINT bit in TWCR to start transmission of data while (!(TWCR & (1 << TWINT))); // Wait for TWINT Flag set. This indicates that the DATA has been transmitted, and ACK/NACK has been received. if ((TWSR & data) != TWEA) {return 0;} // Check value of TWI Status Register. Mask prescaler bits. If status different from MT_DATA_ACK then return 0 TWCR = (1 << TWINT)|(1 << TWEN)|(1 << TWSTO); // Transmit STOP condition } char I2C_receive() { TWCR = (1 << TWEN) |(1 << TWINT)|(1 << TWEA); // Enable TWI, generation of ack while(!(TWCR&(1 << TWINT))); // Wait until TWI finish its current job return TWDR; // Return received data } void I2C_Init() // I2C initialize function { TWBR = BITRATE(TWSR=0x00); // Get bit rate register value by formula } int main(void) { I2C_Init(); for(;;) // continuous loop { char ReceivedData = I2C_receive(); I2C_transmit(ReceivedData); } }