24c256.c

来自「这是单片机实验板比较齐全的程序」· C语言 代码 · 共 143 行

C
143
字号
/*---------------------------------------------
读写24C256/512标准程序段 适用于地址为两个字节的IIC存储器
-------------------------------------------*/
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit SDA=P1^0;
sbit SCL=P1^1;
/*-----------------------------------------------
调用方式:void start_bit(void)
函数说明:开始位
-----------------------------------------------*/
void start_bit(void)
{
	SCL=1;
	_nop_();
	SDA=1;
	_nop_(); 
	SDA=0;
	_nop_(); 
	SCL=0;
	_nop_(); 
}
/*-----------------------------------------------
调用方式:void stop_bit(void)
函数说明:停止位
-----------------------------------------------*/
void stop_bit(void)
{
	SDA=0;
	_nop_(); 
	SCL=1;
	_nop_(); 
	SDA=1;
	_nop_(); 
}
 
/*-----------------------------------------------
调用方式:void ack(void)
函数说明:应答函数
-----------------------------------------------*/
void ack(void)
{
	SDA=1;
	SCL=0;
	_nop_();  
	SCL=1;
	_nop_();
	//while(SDA){;}   //This may make the CPU crash. 04-3-18 17:16
	SCL=0;
	_nop_(); 
}
/*-----------------------------------------------
调用方式:void no_ack(void)
函数说明:无需应答位,在读程序中用到
-----------------------------------------------*/
void no_ack(void)
{
	SDA=1;
	_nop_(); 
	SCL=1;
	_nop_(); 
	//while(SDA){;}  //This may make the CPU crash. 04-3-18 17:16
	SCL=0;
	_nop_(); 
}
/*-----------------------------------------------
调用方式:void write_8bit(uchar ch)
函数说明:写一个字节(8位)数据
-----------------------------------------------*/
void write_8bit(uchar ch)
{
	uchar i=8;
	
	SCL=0;
	_nop_();
	while(i--)
	{
		SDA=(bit)(ch&0x80);
		_nop_(); 
		ch<<=1;
		SCL=1;
		_nop_();
		SCL=0;
		_nop_();  
	}
}

/*----------------------------------------------
调用方式:uchar read24c16(uint address)
函数说明:读24c16指定地址数据(字节读)
-----------------------------------------------*/
uchar ReadFm24c256(uint address)
{
	uchar data rdata;
	uchar i=8;
	//EA=0;//避免与串口通讯等中断冲突
	start_bit();
	write_8bit(0xA0);
	ack();
	write_8bit(address/256);
	ack();//伪写
	write_8bit(address%256);
	ack();
	start_bit();
	write_8bit(0xA1);
	ack();
	while(i--)
	{
		rdata<<=1;
		SCL=0;
		_nop_(); 
		SCL=1;
		if(SDA) rdata|=0x01;
	}
	no_ack();
	stop_bit();
	//EA=1;
	return rdata;
}

/*-----------------------------------------------
调用方式:void write24c16(uint address,uchar ddata)
函数说明:写数据到24c16的指定地址(字节写)
-----------------------------------------------*/
void WriteFm24c256(uint address,uchar ddata)
{
	//EA=0;  //避免与串口通讯等中断冲突
	start_bit();
	write_8bit(0xA0);
	ack();
	write_8bit(address/256);
	ack();
	write_8bit(address%256);
	ack();
	write_8bit(ddata);
	ack();   
	stop_bit();
	//EA=1;
} 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?