#include "reg52.h"
#include "i2c.h"
typedef unsigned char u8;
typedef unsigned int u16;
sbit lsa=P2^2;
sbit lsb=P2^3;
sbit lsc=P2^4;
sbit k1=P3^1;
sbit k2=P3^0;
sbit k3=P3^2;
sbit k4=P3^3;
u8 code smgduan[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};
void delay(i)
{
while(i--);
}
unsigned char num=100;
void Keypros()
{
if(k1==0)
{
delay(1000);
if(k1==0)
{
At24c02Write(1,num);
}
while(!k1);
}
if(k2==0)
{
delay(1000);
if(k2==0)
{
At24c02Read(1);
}
while(!k2);
}
if(k3==0)
{
delay(1000);
if(k3==0)
{
num++;
if(num>255)
{
num=0;
}
}
while(!k3);
}
if(k4==0)
{
delay(1000);
if(k4==0)
{
num=0;
}
while(!k4);
}
}
u8 disp[4];
void datapros()
{
disp[0]=smgduan[num/1000];
disp[1]=smgduan[num%1000/100];
disp[2]=smgduan[num%1000%100/10];
disp[3]=smgduan[num%1000%100%10];
}
void DigDisplay()
{
u8 i;
for(i=0;i<4;i++)
{
switch(i)
{
case(0):lsa=0;lsb=0;lsc=0;break;
case(1):lsa=1;lsb=0;lsc=0;break;
case(2):lsa=0;lsb=1;lsc=0;break;
case(3):lsa=1;lsb=1;lsc=0;break;
}
P0=disp[3-i];
delay(100);
P0=0x00;
}
}
void main()
{
while(1)
{
Keypros();
datapros();
DigDisplay();
}
}
//這是主函數頁,下面是i2c.c頁//
#include "i2c.h"
#include "reg52.h"
void delay10us() //誤差 0us
{
unsigned char a,b;
for(b=1;b>0;b--)
for(a=2;a>0;a--);
}
void I2cStart()
{
SDA=1;
delay10us();
SCL=1;
delay10us();
SDA=0;
delay10us();
SCL=0;
delay10us();
}
void I2cStop()
{
SDA=0;
delay10us();
SCL=1;
delay10us();
SDA=1;
delay10us();
}
unsigned char I2cSendByte(unsigned char dat)
{
unsigned char i,j;
for(i=0;i<8;i++)
{
SDA=dat>>7;
dat=dat<<1;
delay10us();
SCL=1;
delay10us();
SCL=0;
delay10us();
}
SDA=1;
delay10us();
SCL=1;
while(SDA)
{
j++;
if(j>200)
{
SCL=0;
delay10us();
return 0;
}
}
SCL=0;
delay10us();
return 1;
}
unsigned char I2cReadByte()
{
unsigned char i,dat=0;
SDA=1; //起始和發送一個字節之后SCL都是0
delay10us();
for(i=0;i<8;i++)
{
SCL=1;
delay10us();
dat=dat<<1;
dat|=SDA;
delay10us();
SCL=0;
delay10us();
}
return dat;
}
void At24c02Write(unsigned char addr,unsigned char dat)
{
I2cStart();
I2cSendByte(0xa0);
I2cSendByte(addr);
I2cSendByte(dat);
I2cStop();
}
unsigned char At24c02Read(unsigned char addr)
{
unsigned char num;
I2cStart();
I2cSendByte(0xa0);
I2cSendByte(addr);
I2cStart();
I2cSendByte(0xa1);
num=I2cReadByte();
I2cStop();
return num;
}
//下面的頭文件頁//
#ifndef _I2C_H
#define _I2C_H
#include <reg52.h>
sbit SCL=P2^1;
sbit SDA=P2^0;
void I2cStart();
void I2cStop();
unsigned char I2cSendByte(unsigned char dat);
unsigned char I2cReadByte();
void At24c02Write(unsigned char addr,unsigned char dat);
unsigned char At24c02Read(unsigned char addr);
#endif
|