// 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; unsigned char tdata; const char CDATA[]={0x01,0x80,0x02,0x40,0x04,0x20,0x08,0x10}; void port_init(void) { PORTB = 0x00; DDRB = 0x00; PORTC = 0b1001111; //m103 output only DDRC = 0x00; PORTD = 0xFF; DDRD = 0xFF; } //TWI initialize // bit rate:1 void twi_init(void) { TWCR= 0X00; //disable twi TWBR= 0x01; //set bit rate TWSR= 0x00; //set prescale TWAR= 0x01; //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) { TWCR = (1 << TWINT) | (1 << TWEN); TWAMR = 0x00; TWAR = ((s_addr <<1) | 0); TWCR = (1 << TWEA) | (1 << TWEN); while (!(TWCR & (1 << TWINT))) ; if ((TWSR & 0xF8) != 0x60) ERROR(3); TWCR = (1 << TWINT) | (1 << TWEA) | (1 << TWEN); while (!(TWCR & (1 << TWINT))) ; if ((TWSR & 0xF8) != 0x080) ERROR(4); rdata = TWDR; TWCR = (1 << TWINT) | (1 << TWEN); while (!(TWCR & (1 << TWINT))) ; if ((TWSR & 0xF8) != 0x0A0) ERROR(5); TWCR = (1 << TWINT) | (1 << TWEN); return rdata; } void SlaveTransmit(void) { TWCR = (1 << TWINT) | (1 << TWEN); // TWAMR = 0xFE; TWAR = ((s_addr <<1) | 0); TWCR = (1 << TWEA) | (1 << TWEN); while (!(TWCR & (1 << TWINT))) ; if ((TWSR & 0xF8) != 0xA8) ERROR(0x30); TWDR = tdata; TWCR = (1 << TWINT) | (1 << TWEA) | (1 << TWEN); while (!(TWCR & (1 << TWINT))) ; if ((TWSR & 0xF8) != 0x0C0) ERROR(0x40); } // void main(void) { init_devices(); s_addr = 0x50; PORTD =0xAA; while(1) { rdata = SlaveReceive(); tdata = CDATA[rdata]; SlaveTransmit(); PORTD = ~rdata; } }