2 #include <avr/interrupt.h>
3 #include "poppy-com/hal/atmega328p/hal.h"
4 #include "poppy-com/inc/i2c_slave.h"
13 TWBR = ((MAINCLOCK / SCLFREQ) - 16) / 2;
14 TWSR &= ~(1<<TWPS1) & ~(1<<TWPS0);
15 TWAR = (0x0A << 1) | (1<<TWGCE);
17 TWCR = ((1 << TWEA) | (1 << TWEN) | (1 << TWIE));
20 unsigned char i2c_transmit(com_state_t type) {
23 TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
26 TWCR = (1 << TWINT) | (1 << TWEN) | (1<<TWEA);
29 TWCR = (1 << TWINT) | (1 << TWEN);
32 TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
36 while (!(TWCR & (1 << TWINT)));
43 unsigned char i2cAddr(
unsigned char addr,
msg_dir_t dir) {
47 addr = (addr << 1) | TW_READ;
49 addr = (addr << 1) | TW_WRITE;
51 if (n++ >= MAX_TRIES)
return 1;
52 status = i2c_transmit(START);
53 if ((status != TW_START) & (status != TW_REP_START)) {
54 ctx.
status.master_write = TRUE;
59 switch (i2c_transmit(DATA)) {
78 unsigned char i2cWrite(
unsigned char data) {
79 if (TWCR & (1<<TWINT)) {
81 if (i2c_transmit(DATA) != TW_MT_DATA_ACK) {
82 ctx.
status.master_write = TRUE;
86 ctx.
status.master_write = TRUE;
92 unsigned char i2cRead(
unsigned char ack_enable,
unsigned char *data) {
94 if (i2c_transmit(DATA) != TW_MR_DATA_ACK) {
95 ctx.
status.master_read = TRUE;
99 if (i2c_transmit(DATA_NACK) != TW_MR_DATA_NACK) {
100 ctx.
status.master_read = TRUE;
125 case TW_SR_GCALL_ACK:
126 TWCR |= (1<<TWINT)|(1<<TWEA);
137 case TW_SR_GCALL_DATA_ACK:
146 TWCR |= (1<<TWINT)|(1<<TWSTO);
147 ctx.
status.unexpected_state = TRUE;
151 TWCR |= (1<<TWINT)|(1<<TWSTO);
160 void id_update(
unsigned char id) {
162 TWAR = (ctx.
id << 1) | (1 << TWGCE);
169 unsigned char crc(
unsigned char* data,
unsigned char size) {
171 unsigned int crc = 0xFFFF;
174 x = crc >> 8 ^ *data++;
176 crc = (crc << 8) ^ ((
unsigned int)(x << 12))
177 ^ ((
unsigned int)(x <<5))
180 return (
unsigned char)crc;
msg_dir_t
Message direction enum.