Skip to content

Commit

Permalink
Add i2c (UNSTABLE)
Browse files Browse the repository at this point in the history
  • Loading branch information
LDprg committed Feb 15, 2022
1 parent 8414e45 commit b252828
Show file tree
Hide file tree
Showing 2 changed files with 116 additions and 0 deletions.
90 changes: 90 additions & 0 deletions uno_def.c
Original file line number Diff line number Diff line change
Expand Up @@ -113,4 +113,94 @@ void usart_win_cursor(bool on)
usart_setstr("\e[?25h");
else
usart_setstr("\e[?25l");
}

void i2c_init(unsigned long clock, bool pullup)
{
TWBR = ((F_CPU/clock) - 16)/2;

INPUT(A5);
INPUT(A4);

if(pullup)
{
ON(A5);
ON(A4);
}
else
{
OFF(A5);
OFF(A4);
}
}

void i2c_twi_start()
{
TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
while (!(TWCR & (1<<TWINT)));
}

void i2c_twi_tx(uint8_t data, I2C_ACK ack)
{
TWDR = data;
TWCR = (1<<TWINT)|(1<<TWEN);
if (ack) TWCR |= (1<<TWEA);
while (!(TWCR & (1<<TWINT)));
}

void i2c_twi_tx16(uint16_t data, I2C_ACK ack)
{
i2c_twi_tx(data>>8, NACK);
i2c_twi_tx((uint8_t)data, NACK);
}

uint8_t i2c_twi_rx(I2C_ACK ack)
{
TWCR = (1<<TWINT)|(1<<TWEN);
if (ack) TWCR |= (1<<TWEA);
while (!(TWCR & (1<<TWINT)));
return TWDR;
}

void i2c_twi_stop()
{
TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void i2c_tx(uint8_t address, uint8_t data, I2C_ACK ack)
{
i2c_twi_start();

//address &= 0b00000001 & WRITE;

i2c_twi_tx(address, ACK);
i2c_twi_tx(data, ack);

i2c_twi_stop();
}

uint8_t i2c_rx(uint8_t address, I2C_ACK ack)
{
uint8_t data = 0;
i2c_twi_start();

//address &= 0b00000001 & READ;

i2c_twi_tx(address, ACK);
data = i2c_twi_rx(ack);

i2c_twi_stop();
return data;
}

void i2c_tx16(uint8_t address, uint16_t data, I2C_ACK ack)
{
i2c_twi_start();

//address &= 0b00000001 & WRITE;

i2c_twi_tx(data>>8, NACK);
i2c_twi_tx((uint8_t)data, NACK);

i2c_twi_stop();
}
26 changes: 26 additions & 0 deletions uno_def.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#define UNO_DEF_H_

#include "glob_def.h"
#include "stdint.h"
#include <util/setbaud.h>

// LED
Expand Down Expand Up @@ -173,4 +174,29 @@ void usart_setint(int i, BASE base);

void usart_win_cursor(bool onoff);

typedef enum
{
READ = 1,
WRITE = 0,
} I2C_RW;

typedef enum
{
ACK = 0,
NACK = 1,
} I2C_ACK;

void i2c_init(unsigned long clock, bool pullup);

void i2c_twi_start();
void i2c_twi_tx(uint8_t data, I2C_ACK ack);
void i2c_twi_tx16(uint16_t data, I2C_ACK ack);
uint8_t i2c_twi_rx(I2C_ACK ack);
void i2c_twi_stop();

void i2c_tx(uint8_t address, uint8_t data, I2C_ACK ack);
uint8_t i2c_rx(uint8_t address, I2C_ACK ack);

void i2c_tx16(uint8_t address, uint16_t data, I2C_ACK ack);

#endif /* UNO_DEF_H_ */

0 comments on commit b252828

Please sign in to comment.