#include “main.h”
#define SLAVE_ADDRESS0x05
#define SCL 0
#define SDA 1
#define TWI_PORT PORTC
#define TWI_DIR DDRC
//SLAVE RECEIVE MODE
#define SR_SLA_ACK 0X60//从机接纳地址呼应
#define SR_SLA_FAIL 0X68//作为主机裁定失利,自己的ALT+W被接纳
#define SR_GCA_ACK 0X70//从机接纳播送呼应
#define SR_GCA_FAIL 0X78//作为主机裁定失利,接纳到播送地址
#define SR_DATA_ACK 0X80//从机接纳数据呼应
#define SR_DATA_NACK 0X88//从机接纳数据非应对
#define SR_GCA_DATA_ACK 0X90//从机接纳播送数据应对
#define SR_GCA_DATA_NACK 0X98//从机接纳播送数据非应对
#define SR_STOP_RESTART 0xA0//从机作业时收到STOP或RESTART
//SLAVE SEND MODE
#define ST_SLA_ACK 0XA8//从机发送地址应对
#define ST_SLA_FAIL 0XB0//作为主机裁定失利,自己的ALT+R被接纳
#define ST_DATA_ACK 0XB8//从机发送数据应对
#define ST_DATA_NACK 0XC0//从机发送数据非应对
#define ST_BYTE_ACK 0XC8//数据已发送,接纳到ACK
#define ILLEGAL 0x00
#define TWI_ACK() (TWCR = (1< //全局变量 static struct SR sr_temp; void IIC_Init(void) #pragma interrupt_handler TWI_ISR:18 unsigned char *p_st = (unsigned char *)&st; SREG &= ~0x80; if (sleep_mode == POWER_DOWN) switch(TWSR&0xf8) case ST_SLA_ACK: // 0XA8:从机发送地址应对
//volatile unsigned char transmit_ready = 0;
volatile unsigned char receive_ready = 0;
//局部变量
static unsigned char transmit_leng = 0;
static unsigned char receive_leng = 0;
{
PORTC |= (1<
TWCR = (1<
}
void TWI_ISR(void)
{
static unsigned char transmit_cnt = 0;
static unsigned char receive_cnt = 0;
unsigned char *p_sr = (unsigned char *)&sr_temp;
static unsigned char check = 0; //校验和
{
sys_reset_flag = 1;
}
{
case SR_SLA_ACK:
case 68:
receive_cnt = 0;
TWI_ACK();
break;
case SR_DATA_ACK:
if (receive_cnt < (receive_leng-1))
{
*(p_sr+receive_cnt) = TWDR;
}
else if (receive_cnt == (receive_leng-1))
{
*(p_sr+receive_cnt) = TWDR;
receive_ready = 1;
}
receive_cnt++;
TWI_ACK();
break;
case SR_STOP_RESTART: // 0xA0:从机作业时收到STOP或RESTART
TWI_ACK();
break;
transmit_cnt = 0;
TWDR = *(p_st+transmit_cnt);
check = *(p_st+transmit_cnt);
transmit_cnt++;
TWI_ACK();
break;
case ST_DATA_ACK: // 0XB8:从机发送数据应对
if (transmit_cnt < (transmit_leng-1))
{
TWDR = *(p_st+transmit_cnt);
check += *(p_st+transmit_cnt);
}
else if (transmit_cnt == (transmit_leng-1))
{
TWDR = check; //发送校验和
}
transmit_cnt++;
TWI_ACK();
break;
case ST_DATA_NACK:
//transmit_ready = 1;
TWI_ACK();
break;
case ILLEGAL:
case 0xF8:
TWI_RESUME();
break;
}
SREG |= 0x80;
}