新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計(jì)應(yīng)用 > TWI ATMEGA16L 叢機(jī)模式

TWI ATMEGA16L 叢機(jī)模式

作者: 時(shí)間:2016-11-13 來源:網(wǎng)絡(luò) 收藏
#include "main.h"

#define SLAVE_ADDRESS0x05

本文引用地址:http://m.butianyuan.cn/article/201611/316563.htm

#define SCL 0
#define SDA 1
#define TWI_PORT PORTC
#define TWI_DIR DDRC

//SLAVE RECEIVE MODE
#define SR_SLA_ACK 0X60//從機(jī)接收地址響應(yīng)
#define SR_SLA_FAIL 0X68//作為主機(jī)仲裁失敗,自己的ALT+W被接收
#define SR_GCA_ACK 0X70//從機(jī)接收廣播響應(yīng)
#define SR_GCA_FAIL 0X78//作為主機(jī)仲裁失敗,接收到廣播地址
#define SR_DATA_ACK 0X80//從機(jī)接收數(shù)據(jù)響應(yīng)
#define SR_DATA_NACK 0X88//從機(jī)接收數(shù)據(jù)非應(yīng)答
#define SR_GCA_DATA_ACK 0X90//從機(jī)接收廣播數(shù)據(jù)應(yīng)答
#define SR_GCA_DATA_NACK 0X98//從機(jī)接收廣播數(shù)據(jù)非應(yīng)答
#define SR_STOP_RESTART 0xA0//從機(jī)工作時(shí)收到STOP或RESTART
//SLAVE SEND MODE
#define ST_SLA_ACK 0XA8//從機(jī)發(fā)送地址應(yīng)答
#define ST_SLA_FAIL 0XB0//作為主機(jī)仲裁失敗,自己的ALT+R被接收
#define ST_DATA_ACK 0XB8//從機(jī)發(fā)送數(shù)據(jù)應(yīng)答
#define ST_DATA_NACK 0XC0//從機(jī)發(fā)送數(shù)據(jù)非應(yīng)答
#define ST_BYTE_ACK 0XC8//數(shù)據(jù)已發(fā)送,接收到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<
TWCR = 0x00;

TWAR = (SLAVE_ADDRESS<<1)|(0x00);
TWDR = 0x00;
TWCR = (1<
st.start = 0x5A;

transmit_leng = sizeof(st);
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; //校驗(yàn)和

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:從機(jī)工作時(shí)收到STOP或RESTART
TWI_ACK();
break;

case ST_SLA_ACK: // 0XA8:從機(jī)發(fā)送地址應(yīng)答
transmit_cnt = 0;
TWDR = *(p_st+transmit_cnt);
check = *(p_st+transmit_cnt);
transmit_cnt++;
TWI_ACK();
break;
case ST_DATA_ACK: // 0XB8:從機(jī)發(fā)送數(shù)據(jù)應(yīng)答
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; //發(fā)送校驗(yàn)和
}
transmit_cnt++;
TWI_ACK();
break;
case ST_DATA_NACK:
//transmit_ready = 1;
TWI_ACK();
break;
case ILLEGAL:
case 0xF8:
TWI_RESUME();
break;
}
SREG |= 0x80;
}



關(guān)鍵詞: TWIATMEGA16L叢機(jī)模

評論


技術(shù)專區(qū)

關(guān)閉