]>
cvs.zerfleddert.de Git - rsbs2/blob - bmc/i2c.c
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;
17 #define I2C_FREQ 20000UL
21 /* SCLf = F_CPU / (16 + 2 * TWBR * 4^TWPS)
23 * TWBR = (F_CPU/(2 * SCL)) - 8
25 TWBR
= (F_CPU
/(2*I2C_FREQ
))-8;
26 TWAR
= BMC_ADDR
& 0xfe;
28 TWCR
&= ~((1<<TWSTA
) | (1<<TWSTO
));
29 TWCR
|= ((1<<TWEA
) | (1<<TWEN
) | (1<<TWIE
));
30 #ifdef __AVR_ATmega16__
33 #error "Don't know how to set pullups for this chip, please add support"
37 void i2c_send(unsigned char *buf
, int len
)
39 uint8_t old_TWCR
= TWCR
;
40 uint8_t old_SREG
= SREG
;
45 TWCR
= ((1<<TWINT
) | (1<<TWSTA
) | (1<<TWEN
)); /* Send start */
47 while(!(TWCR
& (1<<TWINT
))) {}
48 if (TW_STATUS
!= TW_START
) {
50 printf("I2C: error sending START\n");
55 TWDR
= buf
[0]; /* SLA_W */
56 TWCR
= ((1<<TWINT
) | (1<<TWEN
));
58 while(!(TWCR
& (1<<TWINT
))) {}
59 if (TW_STATUS
!= TW_MT_SLA_ACK
) {
61 printf("I2C: error sending SLA_W\n");
66 for(i
= 1; i
< len
; i
++) {
67 TWDR
= buf
[i
]; /* Send Data */
68 TWCR
= ((1<<TWINT
) | (1<<TWEN
));
70 while(!(TWCR
& (1<<TWINT
))) {}
71 if (TW_STATUS
!= TW_MT_DATA_ACK
) {
73 printf("I2C: error sending DATA byte %d\n", i
);
80 printf("I2C Data sent\n");
84 TWCR
= ((1<<TWINT
) | (1<<TWEN
) | (1<<TWSTO
));
85 while(TWCR
& (1<<TWSTO
)) {}
89 TWCR
= old_TWCR
| (1<<TWINT
);
92 ISR (TWI_vect
, ISR_BLOCK
)
100 printf("I2C: Slave 0x%02x adressed\n", TWDR
);
103 i2c_databuf
[i2c_pos
] = TWDR
;
110 printf("I2C: Data received: 0x%02x\n", TWDR
);
112 if (i2c_pos
>= sizeof(i2c_databuf
)) {
117 i2c_databuf
[i2c_pos
] = TWDR
;
124 printf("I2C: STOP received\n");
134 printf("I2C: TW_NO_INFO received status 0x%2x\n", TW_STATUS
);
141 printf("I2C: Unimplemented status 0x%02x\n", TW_STATUS
);