delay.h
#include <main.h>
#ifndef _DELAY_H
#define _DELAY_H
void delay_ms(uint timer);
#endif
delay.c
#include "main.h"
void delay_ms(uint timer)
{
uchar j = 124;
while(timer--)
{
while(j--);
}
}
iic.h
#ifndef _IIC_H
#define _IIC_H
#include <reg51.h>
#include "main.h"
sbit SDA = P2^7;
sbit SCL = P2^6;
#define IIC_DEVICE 0x40
void init_IIC();
void IIC_start();
void IIc_stop();
void ack();
void noack();
void IIC_write_byte(uchar dat);
uchar IIC_read_byte();
void write_IIC(uchar addr, uchar dat);
uchar read_IIC(uchar addr);
void delay();
#endif
iic.c
#include <intrins.h>
#include <reg51.h>
#include "main.h"
#include "iic.h"
void delay()
{
uchar i;
for(i = 0; i < 8; i++)
{
_nop_();
}
}
void init_IIC()
{
SDA = 1;
delay();
SCL = 1;
delay();
}
void IIC_start()
{
SDA = 1;
delay();
SCL = 1;
delay();
SDA = 0;
delay();
}
void IIc_stop()
{
SDA = 0;
delay();
SCL = 1;
delay();
SDA = 1;
delay();
}
void ack()
{
uchar i = 0;
SCL = 1;
delay();
while((SDA = 1)&&(i < 255))
{
i++;
}
SCL = 0;
delay();
}
void noack()
{
SDA = 1;
delay();
SCL = 1;
delay();
SCL = 0;
delay();
}
void IIC_write_byte(uchar dat)
{
uchar i, tmp;
tmp = dat;
for (i = 0; i < 8; ++i)
{
tmp = tmp<<1;
SCL = 0;
delay();
SDA = CY;
delay();
SCL = 1;
delay();
}
SCL = 0;
delay();
SDA = 1;
delay();
}
uchar IIC_read_byte()
{
uchar i, k;
SCL = 0;
delay();
SDA = 1;
for (i = 0; i < 8; ++i)
{
SCL = 1;
delay();
k = (k<<1)|SDA;
SCL = 0;
delay();
}
delay();
return k;
}
void write_IIC(uchar addr, uchar dat)
{
IIC_start();
IIC_write_byte(IIC_DEVICE);
ack();
IIC_write_byte(addr);
ack();
IIC_write_byte(dat);
ack();
IIc_stop();
}
uchar read_IIC(uchar addr)
{
uchar tmp;
IIC_start();
IIC_write_byte(IIC_DEVICE);
ack();
IIC_write_byte(addr);
ack();
IIC_start();
IIC_write_byte(IIC_DEVICE|0x01);
ack();
IIC_read_byte();
noack();
IIc_stop();
return tmp;
}
main.h
#ifndef _MAIN_H
#define _MAIN_H
#define uint unsigned int
#define uchar unsigned char
#endif
main.c
#include <reg51.h>
#include "main.h"
#include "delay.h"
#include "iic.h"
#define DAT_ADDR 0X03
sbit LED1 = P2^0;
sbit LED2 = P2^1;
uchar g_ucDat;
void display(uchar dat)
{
LED1 = 0;
LED2 = 1;
P0 = (dat%10);
delay_ms(5);
LED2 = 0;
LED1 = 1;
P0 = (dat/10);
delay_ms(5);
}
void int0_init()
{
EX0 = 1;
IT0 = 1;
EA = 1;
}
void int0_inter() interrupt 0
{
g_ucDat++;
}
void main()
{
uchar tmp = 0;
g_ucDat = 0;
int0_init();
init_IIC();
tmp = read_IIC(DAT_ADDR);
if (tmp == 0xff)
{
tmp = 0;
write_IIC(DAT_ADDR, tmp);
delay_ms(10);
}
g_ucDat = tmp;
while(1)
{
if(tmp != g_ucDat)
{
if(g_ucDat > 99)
{
g_ucDat = 1;
}
tmp = g_ucDat;
write_IIC(DAT_ADDR, tmp);
}
display(tmp);
}
}