AVR
작성자 임베디드코리아
작성일17-09-28 15:58
조회2,789회
댓글0건
#include <avr/io.h>
#include <util/delay.h>
#include <stdio.h>
void init_TWI() {
TWSR = 0x00;
TWBR = 0x0C;
TWCR = (0x1<<TWEN);
}
void twi_master_write(char addr, char dat) {
TWCR = 0xA4;
while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x08));
TWDR = addr << 1;
TWCR = 0x84;
while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x18));
TWDR = dat;
TWCR = 0x84;
while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x28));
TWCR = 0x94;
}
char twi_master_read(char addr){
char dat;
TWCR = 0xA4;
while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x08));
TWDR = (addr << 1) | 1;
TWCR = 0x84;
while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x40));
TWCR = 0x84;
while(((TWCR & 0x80) == 0x00) || ((TWSR & 0xf8) != 0x58));
dat = TWDR;
TWCR = 0x94;
return dat;
}
int main(void) {
char ch;
DDRC=0x0F;
ch='a';
init_TWI();
while(1) {
twi_master_write(0x38, ch);
_delay_ms(100);
ch = twi_master_read(0x38);
if (ch == 'b') PORTC=0x02;
else PORTC=0x04;
_delay_ms(1000);
}
}