说明
本程序是C8051F020,查询方式读写24C16的程序;阅读本文这前,最好熟悉一下C8051F020端口配置、SMBUS、IIC、及24C16的相关资料和文档。
电路
//代码
使用 Keil C V8.02
#include "C8051F020.h"
#define IICDEVSEL 0xA0
#define IICWRITE 0
#define IICREAD 1
sbit IIC_WP = P3^0;
/*
* C8051F020的SMBUS初始化配置、端口配置
*/
void IIC_Init()
{
//
SMB0CR
= 0x40;
return
;
}
/*
* C8051F020的SMBUS总线使能控制
*/
void IIC_BusEnable(unsigned char enable)
{
if(enable)
{
//SMBUS 总线使能
SMB0CN
|= 0x40;
}
else
{
//SMBUS 总线不使能
SMB0CN
&= 0xBF;
}
}
/*
* 向24C16写地址
*/
char IIC_WriteAddress(unsigned int addr)
{
unsigned
char xdata temp;
//产生START状态
STA
= 1;
while(1)
{
switch
(SMB0STA)
{
case:
0xF8:
break;
case
0x08:
//取出地址的8~10位,合并到器件选择命令字节中
temp
= (unsigned char)(addr>>8);
temp
&= 0x07;
temp
<<= 1;
SMB0DAT
= IICDEVSEL | IICWRITE | temp;
STA
= 0;
SI
= 0;
break;
case
0x18:
//发送低8位地址
SMB0DAT
= (unsigned char)(addr);
STA
= 0;
SI
= 0;
break;
case
0x28:
//地址发送正确的完成
return
0;
break;
default:
//地址发送错误
STO
= 1;
SI
= 0;
for(i=0; i<3; i++); //delay for stop state transmitted
return
-1;
break;
}
}
}
/*
* 向24C16写数据
*/
char IIC_Write(unsigned char len, unsigned
char* buffer)
{
unsigned
char xdata i;//
i
= 0;
while(1)
{
switch
(SMB0STA)
{
case:
0xF8:
break;
case
0x28:
if(i)>
{
SMB0DAT
= *buffer;
buffer++;
i++;
SI
= 0;
}
else
{
STO
= 1;
SI
= 0;
for(i=0; i<3;
i++); //delay for stop state transmitted
return 0;
}
break;
default:
STO
= 1;
SI
= 0;
for(i=0;
i<3; i++); //delay for stop state transmitted
return
-1;
break;
}
}
return
0;
}
/*
* 从24C16中读数据
*/
unsigned char IIC_Read(unsigned char len,
unsigned char* buffer)
{
unsigned
char xdata i;
i
= 0;
//iic
repeat start
STA
= 1;
SI
= 0;
while(1)
{
switch
(SMB0STA)
{
case:
0xF8:
break;
case
0x10:
SMB0DAT
= IICDEVSEL | IICREAD;
STA
= 0;
SI
= 0;
break;
case
0x40:
i++;
if(i
== len)
{
//如果是最后一个字节,则发送NOACK
AA
= 0;
}
else
{
//发送ACK
AA
= 1;
}
SI
= 0;
break;
case
0x50:
*buffer
= SMB0DAT;
buffer++;
i++;
if(i
== len)
{
//如果是最后一个字节,发送NOACK
AA
= 0;
}
else
{
//发关ACK
AA
= 1;
}
SI
= 0;
break;
case
0x58:
*buffer
= SMB0DAT;
STO
= 1;
SI
= 0;
for(i=0; i<3; i++); //delay for stop state transmitted
return
0;
break;
default:
STO
= 1;
SI
= 0;
for(i=0; i<3; i++); //delay for stop state transmitted
return
-1;
break;
}
}
return
0;
}
/*
* 测试程序
*/
unsigned char sendbuf[]={1,2,3,4,5,6,7,8};
unsigned char revbuf[8];
void main(void)
{
IIC_Init();
IIC_BusEnable(1);
IIC_WriteAddress(0x100);
IIC_Write(8,sendbuf);
IIC_WriteAddress(0x100);
IIC_Read(8,revbuf);
while(1);
}
文章评论(0条评论)
登录后参与讨论