TWI ATMEGA16L 丛机模式
#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
//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 = 0x00;
TWAR = (SLAVE_ADDRESS<1)|(0x00);
TWDR = 0x00;
TWCR = (1
st.start = 0x5A;
transmit_leng = sizeof(st);
receive_leng = sizeof(sr);
}
void TWI_ISR(void)
{
static unsigned char transmit_cnt = 0;
static unsigned char receive_cnt = 0;
unsigned char *p_st = (unsigned char *)&st;
unsigned char *p_sr = (unsigned char *)&sr_temp;
static unsigned char check = 0; //校验和
SREG &= ~0x80;
if (sleep_mode == POWER_DOWN)
{
sys_reset_flag = 1;
}
switch(TWSR&0xf8)
{
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;
case ST_SLA_ACK: // 0XA8:从机发送地址应答
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;
}
TWIATMEGA16L丛机模 相关文章:
- Windows CE 进程、线程和内存管理(11-09)
- RedHatLinux新手入门教程(5)(11-12)
- uClinux介绍(11-09)
- openwebmailV1.60安装教学(11-12)
- Linux嵌入式系统开发平台选型探讨(11-09)
- Windows CE 进程、线程和内存管理(二)(11-09)