AVR單片機IIC實驗

//芯片ATMEGA16 晶振8mhz
#include
#include
#define uchar unsigned char
#define uint unsigned int
//-----------------------------
uchar str1[]={"IIC TEST"};
//---------------------------
void delay(uint k) //延時函數
{
uint i,j;
for(i=0;i
for(j=0;j<1140;j++);
}
#include "1602.h" //1602庫函數
//-------按鍵輸入點設置-------
#define s1 (PIND&0x10) //變量值增加鍵
#define s2 (PIND&0x20) //變量值減少鍵
#define s3 (PIND&0x40) //存儲鍵
#define s4 (PIND&0x80) //讀取鍵
//-------------------
#define TWINT 7 //中斷標志
#define TWEN 2 //中斷時能
#define TWSTA 5 //啟動狀態位
#define TWSTO 4 //停止狀態位
//-----TWI狀態定義,MT主方式傳送,MR主方式接受
#define START 0x08 //啟動
#define RE_START 0x10 // 重新啟動
#define MT_SLA_ACK 0x18 //主機應答
#define MT_SLA_NOACK 0x20 //主機非應答
#define MT_DATA_ACK 0x28 //主機數據傳送后應答
#define MT_DATA_NOACK 0x30 //主機數據傳送后非應答
#define MR_SLA_ACK 0x40 //從機應答
#define MR_SLA_NOACK 0x48 //從機非應答
#define MR_DATA_ACK 0x50 //從機數據應答
#define MR_DATA_NOACK 0x58 //從機數據非應答
//-------------------------
#define start() (TWCR=(1<
#define stop() (TWCR=(1<
#define wait() {while(!(TWCR&(1<
#define testack() (TWSR&0xf8) //TWI狀態檢測,屏蔽預分頻位
#define setack() (TWCR|(1<
#define setnoack() (TWCR&=~(1<
#define twi() (TWCR=(1<
#define writebit(x) {TWDR=(x);TWCR=(1<
主站蜘蛛池模板:
灵川县|
石门县|
白玉县|
乌拉特中旗|
陆川县|
太仆寺旗|
芦山县|
霸州市|
阜宁县|
栾城县|
黎川县|
康乐县|
伽师县|
安乡县|
武夷山市|
南平市|
潍坊市|
陈巴尔虎旗|
错那县|
中宁县|
巴南区|
保靖县|
鄢陵县|
东山县|
平定县|
文昌市|
抚松县|
信宜市|
萝北县|
独山县|
济宁市|
桃园市|
桦南县|
洛浦县|
萍乡市|
天全县|
定结县|
鲜城|
河津市|
马鞍山市|
南澳县|
//------I/0口設置------------
void portinit()
{
PORTA=0xff;
DDRA=0xff;
PORTB=0xff;
DDRB=0xff;
PORTC=0xff;
DDRC=0xff;
PORTD=0xff;
DDRD=0x00;
}
//-----------讀數據函數----------
uchar iicread(uchar address)
{
uchar temp;
start();
wait();
if(testack()!=START) return 0;
writebit(0xa0);
wait();
if(testack()!=MT_SLA_ACK) return 0;
writebit(address);
wait();
if(testack()!=MT_DATA_ACK) return 0;
start();
wait();
if(testack()!=RE_START) return 0;
writebit(0xa1);
wait();
if(testack()!=MR_SLA_ACK) return 0;
twi();
wait();
if(testack()!=MR_DATA_NOACK) return 0;
temp=TWDR;
stop();
return temp;
}
//---------------寫數據函數----------------
uchar iicwrite(uchar address,uchar data)
{
start();
wait();
if(testack()!=START) return 1;
writebit(0xa0);
wait();
if(testack()!=MT_SLA_ACK) return 1;
writebit(address);
wait();
if(testack()!=MT_DATA_ACK) return 1;
writebit(data);
wait();
if(testack()!=MT_DATA_ACK) return 1;
stop();
delay(10);
return 0;
}
void main()
{
uchar val=0; //數據值變量
portinit();
delay(200);
init();
delay(200);
display(2,0,str1);
delay(200);
while(1)
{
displayz(5,1,val/10+0x30);
displayz(6,1,val%10+0x30);
delay(10);
if(s1==0) //值增加鍵
{
delay(100); //軟件延時100ms防止按鍵抖動
if(s1==0)
{
val++;
if(val>30)val=0;
}
}
if(s2==0) //值減少鍵
{
delay(100);
if(s2==0)
{
val--;
if(val<1)val=40;
}
}
if(s3==0) //值存儲鍵
{
delay(100);
if(s3==0)
{
iicwrite(70,val);
}
}
if(s4==0) //值讀取鍵
{
delay(100);
if(s4==0)
{
val=iicread(70);
}
}
}
}
關鍵詞:
AVR單片機IIC實
評論