| 958 | void (*twi_cbreadFromDone)(int); |
| 959 | |
| 960 | void twi_init() { |
| 961 | // initialize state |
| 962 | twi_state = TWI_READY; |
| 963 | |
| 964 | // activate internal pull-ups for twi |
| 965 | // as per note from atmega8 manual pg167 |
| 966 | sbi(PORTC, 4); |
| 967 | sbi(PORTC, 5); |
| 968 | |
| 969 | // initialize twi prescaler and bit rate |
| 970 | cbi(TWSR, TWPS0); // TWI Status Register - Prescaler bits |
| 971 | cbi(TWSR, TWPS1); |
| 972 | |
| 973 | /* twi bit rate formula from atmega128 manual pg 204 |
| 974 | SCL Frequency = CPU Clock Frequency / (16 + (2 * TWBR)) |
| 975 | note: TWBR should be 10 or higher for master mode |
| 976 | It is 72 for a 16mhz Wiring board with 100kHz TWI */ |
| 977 | |
| 978 | TWBR = ((CPU_FREQ / TWI_FREQ) - 16) / 2; // bitrate register |
| 979 | // enable twi module, acks, and twi interrupt |
| 980 | |
| 981 | TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA); |
| 982 | |
| 983 | /* TWEN - TWI Enable Bit |
| 984 | TWIE - TWI Interrupt Enable |
| 985 | TWEA - TWI Enable Acknowledge Bit |
| 986 | TWINT - TWI Interrupt Flag |
| 987 | TWSTA - TWI Start Condition |
| 988 | */ |
| 989 | } |
| 990 | |
| 991 | typedef struct { |
| 992 | uint8_t address; |