AVR

TWI slave

작성자 임베디드코리아 작성일17-09-28 16:00 조회2,602회 댓글0건
#include <avr/io.h> 
#include <util/delay.h>
#include <stdio.h>

void init_TWI() {
  TWSR = 0x00;
  TWBR = 0x0C;
  TWCR = (0x1<<TWEN);  //TWCR=0x4,TWI가 Enbale되어 SCL(PD0)과 SDA(PD1) 핀을 제어 
}
char twi_slave_read(char addr){
  byte dat;
  TWAR = addr << 1;
  TWCR = 0x44;                    // SLAVE
  while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x60));
  TWCR = 0xc4;
  while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x80));
  dat = TWDR;                    // READ
  TWCR = 0xc4;
  while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0xa0));
  TWCR = 0xc4;
  return dat;
}
void twi_slave_write(char addr, char dat){
    TWAR = addr << 1;
    TWCR = 0x44;    // SLAVE
    while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0xa8));
    TWDR = dat;
    TWCR = 0xc4;
    while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0xc0));
    TWCR = 0xc4;
}

int main(void) {
    char ch;
    init_TWI();
 
  while(1)  {
    ch = twi_slave_read(0x38);
        if (ch == ‘a’) PORTC=0x01;
                else PORTC=0x08;;
      _delay_ms(10);
      ch=‘b’;
      twi_slave_write(0x38, ch);
    }
}