unsigned char ErrorBit = 0; //¶Áд´íÎó±êÖ¾£¬1-´íÎó£¬0-ÕýÈ·
void delay()
{
unsigned char j;
for(j =0;j <254; j++)
;
}
void Start(void)
{
I2C_INIT2;
SDA_1;
SCL_1;
delay();
SDA_0;
delay();
SCL_0;
}
void Stop()
{
SCL_0;
SDA_0;
delay();
SCL_1;
delay();
SDA_1;
delay();
}
unsigned char Write_I2c(unsigned char dat)
{
unsigned char i;
for(i =0;i <8;i++)
{
SCL_0;
delay();
if(dat&0x80) SDA_1;
else SDA_0;
dat <<= 1;
SCL_1;
delay();
}
SCL_0;
SDA_1;
delay();
SCL_1;
delay();
SCL_0;
if(ReadSDA)
return FALSE;
else
return TRUE;
}
unsigned char Read_I2c(void)
{
unsigned char i;
unsigned char byte = 0;
SCL_0;
SDA_1;
for(i =0;i <8;i++)
{
byte = byte <<1;
SCL_0;
delay();
SCL_1;
delay();
if(ReadSDA) byte = (byte|0x01);
}
SCL_0;
return (byte);
}
void Ack(void)
{
SCL_0;
SDA_0;
delay();
SCL_1;
delay();
SCL_0;
}
void NoAck(void)
{
SCL_0;
SDA_1;
delay();
SCL_1;
delay();
SCL_0;
}
void Write_Dat(unsigned char StartAddress,unsigned char *dat,unsigned char bytes)
{
unsigned char i;
Start();
Write_I2c(Write24C256);
Write_I2c(StartAddress>>8);
Write_I2c(StartAddress);
for(i =0;i <bytes;i++)
{
Write_I2c(*dat++);
}
Stop();
}
void Read_Dat(unsigned char StartAddress,unsigned char *dat,unsigned char bytes)
{
unsigned char i;
Start();
Write_I2c(Write24C256);
Write_I2c(StartAddress>>8);
Write_I2c(StartAddress);
Start();
Write_I2c(Read24C256);
if(bytes > 1)
{
for(i =0;i <bytes-1;i++)
{
*dat++ = Read_I2c();
Ack();
}
*dat = Read_I2c();
NoAck();
}
else
*dat = Read_I2c();
NoAck();
}
头文件
#define CSI24C256_Addr 0xa0 //Æ÷¼þµØÖ·
#define Write24C256 0xa0 //дÊý¾ÝµØÖ·
#define Read24C256 0xa1 //¶ÁÊý¾ÝµØÖ·
#define SDA_H IOSET0|=0x00000020
#define SDA_L IOCLR0|=0x00000020
#define SCL_H IOSET0|=0x00000004
#define SCL_L IOCLR0|=0x00000004
#define SDA_0 IODIR0|=0x00000020 //SDAÉèΪÊä³öģʽ
#define SDA_1 IODIR0&=(~0x00000020) //SDAÉèΪÊäÈëģʽ
#define SCL_0 IODIR0|=0x00000004 //SCLÉèΪÊä³öģʽ
#define SCL_1 IODIR0&=(~0x00000004) //SCLÉèΪÊäÈëģʽ
#define I2C_INIT2 IOSET0 &= ~(0x00000024)
#define ReadSDA IOPIN0&0x00000020
#define SDA_Val IOPIN0&0x00000020 //ȡSDAλֵ
#define TRUE 1
#define FALSE 0
//void delay(unsigned char i);
//extern void Ini
tiIC();
void Start(); //Æô¶¯IIC×ÜÏß
void Stop(); //Í£Ö¹IIC×ÜÏß
void Ack(void); //Íê³ÉIICµÄÖ÷»úÓ¦´ð²Ù×÷
void NoAck(void); //Íê³ÉIICµÄÖ÷»úÎÞÓ¦´ð²Ù×÷
unsigned char Write_I2c(unsigned char data);
unsigned char Read_I2c(void);
extern void Write_Dat(unsigned char StartAddress,unsigned char *dat,unsigned char bytes);
extern void Read_Dat(unsigned char StartAddress,unsigned char *dat,unsigned char bytes);
大家好,请问这个I2C程序有什么问题吗?为什么写进去的数据读出来全是0xff
一周热门 更多>