#include "iom16v.h"
/*I2C总线主机模式错误处理*/
void error(unsigned char type) {
switch (type & 0xF8) {
case 0x20: /*址址写失败*/
/*stop 停止*/
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
break;
case 0x30: /*数据写失败*/
/*stop 停止*/
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
break;
case 0x38: /*仲裁失败*/
break;
case 0x48: /*址址读失败*/
/*stop 停止*/
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
break;
}
}
/*I2C总线单字节写入*/
unsigned char twi_write(unsigned char addr, unsigned char dd) {
TWBR = 2;
/*start 启动*/
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x08) {
error(TWSR);
return 0;
}
/*SLA_W 芯片地址*/
TWDR = 0xA0;
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x18) {
error(TWSR);
return 0;
}
/*addr 操作地址*/
TWDR = addr;
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x28) {
error(TWSR);
return 0;
}
/*dd 写入数据*/
TWDR = dd;
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x28) {
error(TWSR);
return 0;
}
/*stop 停止*/
TWCR = (1 << TWINT) | (1 << TWEN) | (1 << TWSTO);
return 1;
}
/*I2C总线单字节读取*/
unsigned char twi_read(unsigned char addr, unsigned char *dd) {
TWBR = 2;
/*start 启动*/
TWCR=(1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
while(!(TWCR&(1<<TWINT)));
if ((TWSR & 0xF8) != 0x08) {
error(TWSR);
return 0;
}
/*SLA_W 芯片地址*/
TWDR = 0xA0;
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x18) {
error(TWSR);
return 0;
}
/*addr 操作地址*/
TWDR = addr;
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x28) {
error(TWSR);
return 0;
}
/*start 启动*/
TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x10) {
error(TWSR);
return 0;
}
/*SLA_R 芯片地址*/
TWDR = 0xA1;
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x40) {
error(TWSR);
return 0;
}
/*读取数据*/
TWCR = (1 << TWINT) | (1 << TWEN);
while (!(TWCR & (1 << TWINT)));
if ((TWSR & 0xF8) != 0x58) {
error(TWSR);
return 0;
}
*dd = TWDR;
/*stop 停止*/
TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
return 1;
}
|