⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 __24c16.h

📁 本程式是使用C++寫單片機的軔體程式, 可以和PC做串列埠COM port通訊, 也結合I2C通訊標準, 將接收的資料燒錄傳輸至硬件IC 24C16
💻 H
字号:
#include <intrins.h>

typedef bit Bool;
typedef bit Bit;
typedef unsigned char Byte;
//-----------------------------------------------------------------------------------------
sbit SCL = P1^0;
sbit SDA = P1^1;
//-----------------------------------------------------------------------------------------
void I2cWait(void){  //Wait 2us
	_nop_();
	_nop_();
}
void I2cWaitXms(int count){
	int i,j;
	for (i=0;i<count;i++){
		for (j=0;j<250;j++){
			I2cWait();
			I2cWait();
		}
	}
}
void I2cInit(void){  // Initial condition
	SDA = 1;
	SCL = 1;
}
void I2cStart(void){	// Start condition
	SDA = 1;
	SCL = 1;
	I2cWait();
	SDA = 0;
	I2cWait();
	SCL = 0;
	I2cWait();
}
void I2cStop(void){		// Stop condition
	SDA = 0;
	I2cWait();
	SCL = 1;
	I2cWait();
	SDA = 1;
	I2cWait();
}
Bool I2cSentByte(Byte bytedata){
	Byte i;
	Bool ack;
	Byte BitMask = 0x80;
	for(i=0;i<8;i++){
		if((bytedata & BitMask)==0x00){
			SDA = 0;
		}else{
			SDA = 1;
		}
		
		I2cWait();
		SCL = 1;
		I2cWait();
		SCL = 0;
		I2cWait();
		
		BitMask >>=1;
	}
	SDA = 1;
	I2cWait();
	SCL = 1;
	I2cWait();
	ack = SDA;
	SCL = 0;
	I2cWait();
	SDA = 1; // because SDA may be pull down by ack, so reset SDA = 1
	return ack;
}
Byte I2cReceiveByte(void){
	Byte i;
	Byte BitMask = 0x80;
	Byte bytedata = 0x00;
	// Receive byte(MSB first)
	for(i=0;i<8;i++){
		SCL = 1;
		I2cWait();

		if(SDA) bytedata |= BitMask;
		
		BitMask >>=1;

		SCL = 0;
		I2cWait();
   	}
	return bytedata;
}
void I2cSendAck(Bool ack){
	SDA = ack;
	I2cWait();//
	SCL = 1;
	I2cWait();
	SCL = 0;
	I2cWait();
	SDA = 1;  // because SDA may be pull down by ack, so reset SDA = 1
}
void I2cByteRead(Byte Device, Byte Addr, int Num, unsigned char* pData){
    int i;

    I2cInit();
    I2cStart();             //Dummy Wirte
    I2cWait();
    I2cSentByte(Device);    //Device Address (include 3 bit for word address)
    I2cSentByte(Addr);       //Last 8 bit address
    I2cWait();
	I2cStop();
   
    I2cStart();             //Start to Read Data
    I2cWait();
    I2cSentByte(Device|0x01);    //Read Data
    for(i=0;i<Num-1;i++)
    {
        *(pData+i)=I2cReceiveByte();	//*pData is also return value;
		I2cSendAck(0);
    }
    *(pData+Num-1)=I2cReceiveByte();
	I2cSendAck(1);
    I2cWait();
    I2cStop();
}
void I2cByteWrite(Byte Device, Byte Addr, int Num, unsigned char* pData){
	int i;
		
    I2cInit();
    I2cStart();
    I2cWait();

    I2cSentByte(Device);    //Device Address (include 3 bit for word address)
    I2cSentByte(Addr);       //Last 8 bit address
    I2cWait();
	
	for (i=0;i<Num;i++)
		I2cSentByte(*(pData+i));
	I2cWaitXms(10);
	I2cStop();
}






⌨️ 快捷键说明

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