/*
89c52 软件模拟I2C 接口
33.1776MHZ
*/
#include "STC89C51RC.h"
#include"IIC.h"
#define uchar unsigned char
#define uint unsigned int
uchar total;
uchar testdat[5]={0x01,0x02,0x03,0x11,0x5a};
uchar tempp[5];
//串口初始化
void Communications_Init(void)
{
PCON &= 0x7F; //波特率不倍速
SCON = 0x50; //8位数据,可变波特率
AUXR &= 0xBF; //定时器1时钟为Fosc/12,即12T
AUXR &= 0xFE; //串口1选择定时器1为波特率发生器
TMOD &= 0x0F; //清除定时器1模式位
TMOD |= 0x20; //设定定时器1为8位自动重装方式
TL1 = 0xF7; //设定定时初值
TH1 = 0xF7; //设定定时器重装值
ET1 = 0; //禁止定时器1中断
TR1 = 1; //启动定时器1
}
//串口发送数据1字节
void Send_Uart(unsigned char a_s)
{
ES=0;
TI=0;
SBUF=a_s;
while(!TI);
TI=0;
ES=1;
}
void Delay1ms() //@33.1776MHz
{
unsigned char i, j;
i = 6;
j = 93;
do
{
while (--j);
} while (--i);
}
//write one data
void W24c02(uchar address,uchar dat)
{
IIC_start();
IIC_write(0xa0); //写从器件地址
IIC_write(address); //字节地址
IIC_write(dat); //写数据
IIC_stop();
}
//read one data
uchar R24c02(uchar address)
{
uchar temp;
IIC_start();
IIC_write(0xa0); //写从器件地址
IIC_write(address); //字节地址
IIC_start();
IIC_write(0xa1); //写从器件地址
temp=IIC_read();
IIC_stop();
return temp;
}
//写多字节
void Wm24c02(uchar address,uchar *dat,uchar un)
{
uchar i;
IIC_start();
IIC_write(0xa0); //写从器件地址
IIC_write(address); //字节地址
for(i=0;i<un;i++)
{
IIC_write(dat[i]); //写数据
}
IIC_stop();
}
//读多字节
void Rm24c02(uchar address,uchar *dat,uchar un)
{
uchar i=0;
IIC_start();
IIC_write(0xa0); //写从器件地址
IIC_write(address); //字节地址
IIC_start();
IIC_write(0xa1); //写从器件地址
dat[0]=IIC_read();
for(i=1;i<un;i++)
{
IIC_ack();
dat[i]=IIC_read();
}
IIC_stop();
}
void main()
{
uchar i;
EA = 1; //开总中断
ES = 1; //允许串口中断
P2M1=0X00;
P2M0=0X00;
Communications_Init();
// Send_Uart(0x99);
// W24c02(0x00,0x02);
Wm24c02(0x00,testdat,5);
while(1)
{
if(total!=0x00)
{
Rm24c02(0x00,tempp,5);
for(i=0;i<5;i++)
Send_Uart(tempp[i]);
// W24c02(0xff,0xfd);
// i=R24c02(0x00);
// Send_Uart(i);
total=0x00;
}
}
}
//串口接收中断函数
void serial(void) interrupt 4 using 0
{
while(!RI);
RI=0;
total=SBUF;
}