IIC.h
#ifndef _iic_h_
#define _iic_h_
#include <reg52.h>
#include <intrins.h>
sbit SDA=P2^0;
sbit SCL=P2^1;
void IICstart();
void IICstop();
unsigned char IICWriteByte(unsigned char dat);
unsigned char IICReadbyte();
void At24c02Write(unsigned char addr,unsigned char dat);
unsigned char At24c02Read(unsigned char addr);
#endif
IIC.c
#include "IIC.h"
void Delay10us()
{
unsigned char i;
_nop_();
_nop_();
i = 27;
while (--i);
}
void IICstart(){
SDA=1;
Delay10us();
SCL=1;
Delay10us();
SDA=0;
Delay10us();
SCL=0;
Delay10us();
}
void IICstop(){
SDA=0;
Delay10us();
SCL=1;
Delay10us();
SDA=1;
Delay10us();
}
unsigned char IICSendByte(unsigned char dat){
unsigned char a=0;
unsigned char i;
for ( i = 0; i < 8; i++)
{
SDA=dat>>7;
dat<<=1;
Delay10us();
SCL=1;
Delay10us();
SCL=0;
Delay10us();
}
SDA=1;
Delay10us();
SCL=1;
while(SDA){
a++;
if(a>200){
SCL=0;
Delay10us();
return 0;
}
}
SCL=0;
Delay10us();
return 1;
}
unsigned char IICReadByte(){
unsigned char i;
unsigned char num=0;
SDA=1;
Delay10us();
for ( i = 0; i < 8; i++)
{
SCL=1;
Delay10us();
num=num<<1;
num=num|SDA;
Delay10us();
SCL=0;
Delay10us();
}
return num;
}
void At24c02Writer(unsigned char addr,unsigned char dat){
IICstart();
IICSendByte(0xa0);
IICSendByte(addr);
IICSendByte(dat);
IICstop();
}
unsigned char At24c02Read(unsigned char addr){
unsigned char dat;
IICstart();
IICSendByte(0xa0);
IICSendByte(addr);
IICstart();
IICSendByte(0xa1);
dat=IICReadByte();
IICstop();
return dat;
}
main.c
#include "IIC.h"
#include "reg52.h"
typedef unsigned char u8;
typedef unsigned int u16;
sbit LSA=P2^2;
sbit LSB=P2^3;
sbit LSC=P2^4;
sbit k1=P3^0;
sbit k2=P3^1;
sbit k3=P3^2;
sbit k4=P3^3;
char num=0;
u8 code smgduan[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
u8 dis[4];
void delay(u16 i){
while (i--);
}
void keyprocess(){
if(k1==0){
delay(1000);
if (k1==0)
{
At24c02Writer(1,num);
}
while(!k1);
}
if(k2==0){
delay(1000);
if (k2==0)
{
num=At24c02Read(1);
}
while(!k2);
}
if(k3==0){
delay(1000);
if (k3==0)
{
num++;
if(num>225){
num=0;
}
}
while(!k3);
}
if(k4==0){
delay(1000);
if (k4==0)
{
num=0;
}
while(!k4);
}
}
void dataprocess(){
dis[0]=smgduan[num/1000];
dis[1]=smgduan[num%1000/100];
dis[2]=smgduan[num%1000%100/10];
dis[3]=smgduan[num%1000%100%10];
}
void display(){
u8 i;
for ( i = 0; i<4; i++)
{
switch (i)
{
case (0):
LSA=1;LSB=1;LSC=0;
break;
case (1):
LSA=0;LSB=1;LSC=0;
break;
case (2):
LSA=1;LSB=0;LSC=0;
break;
case (3):
LSA=0;LSB=0;LSC=0;
break;
}
P0=dis[i];
delay(100);
P0=0x00;
}
}
void main(){
while(1){
keyprocess();
dataprocess();
display();
}
}
总结
这是自己对照时序图写的代码,单片机开发板中有一块EEROM芯片(AT24C02),通过IIC协议完成通信。
包含的知识点:
IIC协议、AT23C02芯片通讯原理、动态数码管(74HC138译码器)、独立按键等。
|