PIC IIC & 24c02
#include //調(diào)用頭文件,可以去PICC18軟件下去查找PIC18FXX2.H
__CONFIG(1,XT) ; //晶振為外部4M
__CONFIG(2,WDTDIS) ; //看門(mén)狗關(guān)閉
__CONFIG(4,LVPDIS) ; //禁止低電壓編程
#define uint unsigned int
#define uchar unsigned char
#define nop NOP()
#define scl RC3 //時(shí)鐘線(xiàn)
#define sda RC4 //數(shù)據(jù)線(xiàn)
char shuma[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
uint count=0;
uchar sec;
void usdelay()
{
nop; //其實(shí)在用IIC對(duì)EEPROM操作時(shí),它反應(yīng)很快,延時(shí)可以很短,但必須延時(shí),只要一個(gè)NOP()就可以了
}
void init_24c() //初始化24C,就是把兩根線(xiàn)拉高
{
TRISC4=0;
scl=1;
sda=1;
usdelay();
}

void start() //開(kāi)始信號(hào),根據(jù)時(shí)序圖(sx)
{
TRISC4=0;
scl=1;
usdelay();
sda=1;
usdelay();
sda=0;
}
void stop() //結(jié)束信號(hào) sx
{
TRISC4=0;
scl=1;
usdelay();
sda=0;
usdelay();
sda=1;
}
void ack() //不知道為什么,在PIC中不能用ack,好像一用就會(huì)出錯(cuò)= =?
{
uchar i;
TRISC4=0;
sda=1;
nop;
TRISC4=1;
scl=1;
nop;
while(sda==1&&i<10)i++;
scl=0;
}

void write_byte(uchar dat) //寫(xiě)字節(jié) sx 由于不僅要寫(xiě)數(shù)據(jù),還要寫(xiě)地址,所以只能先寫(xiě)字節(jié)的最高位R7,最后寫(xiě)最低位R0
{
uchar i;
TRISC4=0;
sda=0;
scl=0;
nop;
for(i=0;i<=8;i++)
{
sda=(dat&0x80)>>7;
nop;
scl=1;
nop;
scl=0;
dat<<=1;
nop;
}
}
uchar read_byte() //讀字節(jié) sx 先讀高位R7,最后讀地位R0
{
uchar i,dat=0;
TRISC4=1;
sda=0;
usdelay();
scl=1;
usdelay();
for(i=0;i<8;i++)
{
dat<<=1;
usdelay();
scl=1;
nop;
dat=dat|sda;
nop;
scl=0;
usdelay();
}
return dat;
}


void write_add(uchar add,uchar dat) //寫(xiě)數(shù)據(jù)到地址 sx 注意不要用ack
{
start();
write_byte(0xa0);
write_byte(add);
write_byte(dat);
stop();
}


uchar read_add(uchar add) //從地址讀數(shù)據(jù) sx 注意不要用ack
{
uchar dat;
start();
write_byte(0xa0);
write_byte(add);
start();
write_byte(0xa1);
dat=read_byte();
stop();
return dat;
}
void interrupt kaito() //定時(shí)器中斷0
{
if(TMR0IF==1)
{
TMR0IF=0;
TMR0=0xff13;
count++;
if(count==4000)
{
count=0;
sec++;
if(sec>9)
sec=0;
write_add(0x10,sec); //每次要顯示的數(shù)據(jù)發(fā)生變化,就寫(xiě)入到24c02中存起來(lái),方便斷電后保留
}
}
}
void main(void)
{
sec=0;
ADCON1=0X06;
TRISD=0x00;
TRISC3=0;
TRISC4=0;
init_24c();
GIE=1;
IPEN=0;
TMR0IE=1;
TMR0IF=0;
T0CON=0x88;
TMR0=0xff13;
GIE=1;
sec=read_add(0x10);
while(1)
{
PORTD=shuma[sec];
}
}
就是感覺(jué)很奇怪,為什么不能用attack,時(shí)序圖上明明有,可是一寫(xiě)上就是錯(cuò)的= =?
達(dá)到效果,定時(shí)器計(jì)數(shù),數(shù)碼管顯示,如果關(guān)機(jī)或者復(fù)位,數(shù)碼管從關(guān)機(jī)前的數(shù)開(kāi)始繼續(xù)計(jì)數(shù)。
如果對(duì)一個(gè)地址以前沒(méi)有用過(guò),它里面存的是出廠時(shí)設(shè)置在里面的數(shù)據(jù),很多是ff,如果不對(duì)它做正確的寫(xiě)入,讀出的數(shù)據(jù)就會(huì)是ff,如果用1602來(lái)顯示,要取十位和個(gè)位,都是f,在加上顯示時(shí)的0x30,就變成0x59,和0x35,顯示出來(lái)的就是I5
還有在定時(shí)器中斷中要寫(xiě)入多個(gè)數(shù)據(jù),必須按照條件分開(kāi)寫(xiě)入,同時(shí)寫(xiě)入的話(huà)會(huì)有幾條語(yǔ)句可能寫(xiě)入失敗。
評(píng)論