我用89C51访问24C02无反应.
24C02时钟接P1.7,数据接P1.6,A0 A1 A2接地
执行函数:I2C_Write(0xA0,0x01,0);I2C_Read(0xA1,0x01,&c);都直接返回0
我是用Proteus仿真的.89C51时钟为24MHz
执行写入命令:
Write(0xA0,0x00,'T');
Write(0xA0,0x01,'E');
Write(0xA0,0x02,'S');
Write(0xA0,0x03,'T');
Write(0xA0,0x10,'O');
Write(0xA0,0x11,'K');
用Proteus的I2C窗口查看:
S A0 N 00 N 54 N P
S A0 N 01 N 45 N P
S A0 N 02 N 53 N P
S A0 N 03 N 54 N P
S A0 N 10 N 4F N P
S A0 N 11 N 4B N P
查看I2C的内容均为FF.
这里的N说的是没有应答?????24C02没应答????
24C02.H
#ifndef __24C02_H__
#define __24C02_H__
#ifndef uchar
#define uchar unsigned char
#endif
#ifndef uint
#define uint unsigned int
#endif
#ifndef ulong
#define ulong unsigned long
#endif
#define I2C_TIMEOUT 255
#define CTRL_BASE_ADDR_I2C 0x90
#define I2C_CLK_PIN 7
#define I2C_DATA_PIN 6
//Extern Function
bit I2C_Read(uint I2C_Addr,uint Byte_Addr,uchar *c);
bit I2C_Write(uint I2C_Addr,uint Byte_Addr,uchar dat);
//Internal Function
void I2CSend(uchar dat);
uchar I2CRecv();
void I2C_Start();
void I2C_Stop();
void I2C_ACK();
void I2C_NOACK();
bit I2C_CHK_ACK();
#endif
24C02.C
#include "24C02.H"
#include "Process.h"
#include <intrins.h>
#define Nop4(); {_nop_();_nop_();_nop_();_nop_();}
sbit SCLK_I2C = CTRL_BASE_ADDR_I2C^I2C_CLK_PIN;
sbit SDATA_I2C = CTRL_BASE_ADDR_I2C^I2C_DATA_PIN;
bit I2CACK;
void I2C_Start()
{
SCLK_I2C = 0;
SDATA_I2C = 1;
_nop_();
SCLK_I2C = 1;
Nop4();
SDATA_I2C = 0;
Nop4();
SCLK_I2C = 0;
_nop_();
}
void I2C_Stop()
{
SCLK_I2C = 0;
SDATA_I2C = 0;
_nop_();
SCLK_I2C = 1;
Nop4();
SDATA_I2C = 1;
Nop4();
}
void I2C_ACK()
{
SDATA_I2C = 0;
Nop4();
SCLK_I2C = 1;
Nop4();
SCLK_I2C = 0;
_nop_();
_nop_();
}
void I2C_NOACK()
{
SDATA_I2C = 1;
Nop4();
SCLK_I2C = 1;
Nop4();
SCLK_I2C = 0;
_nop_();
_nop_();
}
bit I2C_Read(uint I2C_Addr,uint Byte_Addr,uchar *c)
{
I2C_Start();
I2CSend(I2C_Addr & 0xFE);
if(!I2CACK) return 0;
I2CSend(Byte_Addr);
if(!I2CACK) return 0;
I2C_Start();
I2CSend(I2C_Addr | 0x01);
*c = I2CRecv();
I2C_NOACK();
I2C_Stop();
}
bit I2C_Write(uint I2C_Addr,uint Byte_Addr,uchar dat)
{
I2C_Start();
I2CSend(I2C_Addr & 0xFE);
if(!I2CACK) return 0;
I2CSend(Byte_Addr);
if(!I2CACK) return 0;
I2CSend(dat);
if(!I2CACK) return 0;
I2C_Stop();
return 1;
}
bit I2C_CHK_ACK()
{
bit bStatus = 1;
ulong iTimeout = I2C_TIMEOUT;
SCLK_I2C = 0;
SDATA_I2C = 1;
Nop4();
SCLK_I2C = 1;
Nop4();
while(SDATA_I2C)
{
iTimeout--;
if(!iTimeout)
{
I2C_Stop();
bStatus = 0;
return bStatus;
}
}
SCLK_I2C = 0;
_nop_();
return bStatus;
}
void I2CSend(uchar dat)
{
uchar i=8;
while(i--)
{
SDATA_I2C = (bit)(dat & (0x01<<(i-1)));
_nop_();
_nop_();
SCLK_I2C = 1;
Nop4();
SCLK_I2C = 0;
}
_nop_();
_nop_();
I2CACK = I2C_CHK_ACK();
_nop_();
}
uchar I2CRecv()
{
uchar temp = 0x00;
uchar i = 8;
SCLK_I2C = 0;
SDATA_I2C = 1;
while(i--)
{
SCLK_I2C = 0;
Nop4();
SCLK_I2C = 1;
_nop_();
_nop_();
temp |= ((uchar)(SDATA_I2C )<< (i-1));
_nop_();
_nop_();
}
return temp;
}
|