您的位置 首页 系统

TWI ATMEGA16L 丛机形式

#includemain.h#defineSLAVE_ADDRESS0x05#defineSCL0#defineSDA1#defineTWI_PORTPORTC#defineTWI_DIRDDRC//

#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<#define TWI_NOACK() (TWCR = (1<#define TWI_RESUME() (TWCR = (1<

//全局变量
//volatile unsigned char transmit_ready = 0;
volatile unsigned char receive_ready = 0;
//局部变量
static unsigned char transmit_leng = 0;
static unsigned char receive_leng = 0;

static struct SR sr_temp;

void IIC_Init(void)
{
PORTC |= (1<DDRC &= ~((1<TWDR = 0x00;
TWCR = (1<receive_leng = sizeof(sr);
}

#pragma interrupt_handler TWI_ISR:18
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;
}

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/qianrushi/xitong/273241.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部