]>
git.zerfleddert.de Git - rsbs2/blob - bmc/i2c.c
92c00cc2ea5d71a6995f509a09bfa376a9b662c8
2 #include <avr/interrupt.h>
8 #define TWCR_ACK TWCR = (1<<TWEN)|(1<<TWIE)|(1<<TWINT)|(1<<TWEA)|(0<<TWSTA)|(0<<TWSTO)|(0<<TWWC);
9 #define TWCR_NACK TWCR = (1<<TWEN)|(1<<TWIE)|(1<<TWINT)|(0<<TWEA)|(0<<TWSTA)|(0<<TWSTO)|(0<<TWWC);
10 #define TWCR_RESET TWCR = (1<<TWEN)|(1<<TWIE)|(1<<TWINT)|(1<<TWEA)|(0<<TWSTA)|(1<<TWSTO)|(0<<TWWC);
12 volatile unsigned char i2c_databuf
[24];
13 volatile uint8_t i2c_len
= 0x00;
14 static volatile uint8_t i2c_pos
= 0x00;
15 volatile uint8_t i2c_done
= 0x00;
20 TWAR
= BMC_ADDR
& 0xfe;
22 TWCR
&= ~((1<<TWSTA
) | (1<<TWSTO
));
23 TWCR
|= ((1<<TWEA
) | (1<<TWEN
) | (1<<TWIE
));
24 #ifdef __AVR_ATmega16__
27 #error "Don't know how to set pullups for this chip, please add support"
31 void i2c_send(unsigned char *buf
, int len
)
33 uint8_t old_TWCR
= TWCR
;
34 uint8_t old_SREG
= SREG
;
39 TWCR
= ((1<<TWINT
) | (1<<TWSTA
) | (1<<TWEN
)); /* Send start */
41 while(!(TWCR
& (1<<TWINT
))) {}
42 if ((TW_STATUS
& 0xf8) != TW_START
)
45 TWDR
= buf
[0]; /* SLA_W */
46 TWCR
= ((1<<TWINT
) | (1<<TWEN
));
48 while(!(TWCR
& (1<<TWINT
))) {}
49 if ((TW_STATUS
& 0xf8) != TW_MT_SLA_ACK
)
52 for(i
= 1; i
< len
; i
++) {
53 TWDR
= buf
[i
]; /* Send Data */
54 TWCR
= ((1<<TWINT
) | (1<<TWEN
));
56 while(!(TWCR
& (1<<TWINT
))) {}
57 if ((TW_STATUS
& 0xf8) != TW_MT_DATA_ACK
)
61 TWCR
= ((1<<TWINT
) | (1<<TWEN
) | (1<<TWSTO
));
62 while(TWCR
& (1<<TWSTO
)) {}
65 printf("I2C Data sent\n");
74 ISR (TWI_vect
, ISR_BLOCK
)
79 switch (TW_STATUS
& 0xf8) {
82 printf("I2C: Slave 0x%02x adressed\n", TWDR
);
85 i2c_databuf
[i2c_pos
] = TWDR
;
92 printf("I2C: Data received: 0x%02x\n", TWDR
);
94 if (i2c_pos
>= sizeof(i2c_databuf
)) {
99 i2c_databuf
[i2c_pos
] = TWDR
;
106 printf("I2C: STOP received\n");
116 printf("I2C: Unimplemented status 0x%02x\n", (TW_STATUS
& 0xf8));