// Copyright 2006 Yamane Akira //ICC-AVR application builder : 2005/07/24 9:21:20 // Target : M48 // Crystal: 8.0000Mhz // TWI Slave Mode Test Program // Programmed by A.Yamane #include #include unsigned char s_addr, rdata; void port_init(void) { PORTB = 0xFF; DDRB = 0x00; PORTC = 0b1001111; //SDA,SCL Low DDRC = 0x00; PORTD = 0xFF; DDRD = 0xFF; } //TWI initialize // bit rate:1 void twi_init(void) { TWCR= 0X00; //disable twi TWBR= 0x00; //set bit rate as 0 TWSR= 0x00; //set prescale as 0 TWAR= 0x00; //set slave address TWCR= 0x04; //enable twi } //call this routine to initialize all peripherals void init_devices(void) { //stop errant interrupts until set up CLI(); //disable all interrupts port_init(); twi_init(); MCUCR = 0x00; EICRA = 0x00; //extended ext ints EIMSK = 0x00; TIMSK0 = 0x00; //timer 0 interrupt sources TIMSK1 = 0x00; //timer 1 interrupt sources TIMSK2 = 0x00; //timer 2 interrupt sources PCMSK0 = 0x00; //pin change mask 0 PCMSK1 = 0x00; //pin change mask 1 PCMSK2 = 0x00; //pin change mask 2 PCICR = 0x00; //pin change enable PRR = 0x00; //power controller SEI(); //re-enable interrupts //all peripherals are now initialized } void ERROR(unsigned char edata) { PORTD= ~edata; //while(1); } unsigned char SlaveReceive(void) { TWAMR = 0x00; // No address Mask TWAR = ((s_addr <<1) | 0); // Slave Address TWCR = (1 << TWEA) | (1 << TWEN); // Ack Enable while (!(TWCR & (1 << TWINT))) // Wait TWINT Flag ; if ((TWSR & 0xF8) != 0x60) // Own Address Packet has received ERROR(3); TWCR = (1 << TWINT) | (1 << TWEA) | (1 << TWEN); // Data will be received // & Ack will be returned while (!(TWCR & (1 << TWINT))) // Wait TWINT Flag ; if ((TWSR & 0xF8) != 0x080) // Previous addressed Data has been received ERROR(4); rdata = TWDR; // Read received DATA TWCR = (1 << TWINT) | (1 << TWEN); // Ack return while (!(TWCR & (1 << TWINT))) // Wait TWINT ; if ((TWSR & 0xF8) != 0x0A0) // STOP condition has been received ERROR(5); TWCR = (1 << TWINT) | (1 << TWEN) // Switched to the not addressed | (1 << TWEA); // Slave Mode; own SLA will be recognized return rdata; } // void main(void) { init_devices(); s_addr = 0x10; PORTD =0xAA; while(1) { PORTD = ~SlaveReceive(); } }