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

📄 i2ceeprom.c

📁 《dsPIC通用数字信号控制器原理及应用》源码
💻 C
字号:
/********************************************************
** 文件名  :I2CEEPROM.c                               **
** 功能描述: I2C应用,24LC256页读写程序,页长度为16字节**
********************************************************/
#include "p30f6014.h"

int failmemory[40];
unsigned int WriteTable[16]={0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,
                             0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff};
unsigned int ReadTable[16];
unsigned int ControlByteW=0xa0; //控制字:写准备(器件地址000)
unsigned int ControlByteR=0xa1; //控制字:读准备(器件地址000)
unsigned int AddressH=0x00; //数据地址高7位
unsigned int AddressL=0x00; //数据地址低8位
unsigned long int i = 0;

//I2CEEPROM配置子程序
void ConfigI2CEEPROM()
{
    SRbits.IPL = 7;	//关闭所有中断
	TRISG = TRISG&0xfeff; //RG8引脚为输出
    I2CCONbits.I2CEN = 1; //启动I2C模块
    I2CBRG = 0x064; //I2C波特率
}   

//向24LC256中写入16个字节的数据
void PageWrite()
{ 
    I2CCONbits.SEN = 1; //发送启动位
    while(I2CCONbits.SEN == 1); //等待启动操作完成
    I2CTRN = ControlByteW; //发送控制字:写准备
    while(I2CSTATbits.TRSTAT == 1); //等待发送完成
    I2CTRN = AddressH;  
    while(I2CSTATbits.TRSTAT == 1); //等待发送完成
	I2CTRN = AddressL;   
    while(I2CSTATbits.TRSTAT == 1); //等待发送完成
    for(i=0; i<16; i++)
	{
		I2CTRN = WriteTable[i];
        while(I2CSTATbits.TRSTAT == 1); //等待发送完成
    }
    I2CCONbits.PEN = 1; //发送停止位
    while(I2CCONbits.PEN == 1); //等待停止操作完成    
}

//从24LC256中读出16个字节的数据
void PageRead()
{  
    I2CCONbits.SEN = 1; //发送启动位                  
    while(I2CCONbits.SEN == 1); //等待启动操作完成  
    I2CTRN = ControlByteW; //发送控制字:写准备
    while(I2CSTATbits.TRSTAT == 1); //等待发送完成
    I2CTRN = AddressH;  
    while(I2CSTATbits.TRSTAT == 1); //等待发送完成
	I2CTRN = AddressL;   
    while(I2CSTATbits.TRSTAT == 1); //等待发送完成
    I2CCONbits.RSEN = 1; //发送重启动位
    while(I2CCONbits.RSEN == 1); //等待重启动操作完成
    I2CTRN = ControlByteR; //发送控制字:读准备
    while(I2CSTATbits.TRSTAT == 1); //等待发送完成
    for(i=0; i<16; i++)
	{ 
        I2CCONbits.RCEN = 1; //接收数据使能   
        while(I2CSTATbits.RBF == 0);
        ReadTable[i] = I2CRCV;
        I2CCONbits.ACKDT = 0;
        if (i==15)
        	I2CCONbits.ACKDT = 1; //最后一字节则不发ACK 
        I2CCONbits.ACKEN = 1;   
        while(I2CCONbits.ACKEN == 1);
    }   
    I2CCONbits.PEN = 1; //发送停止位
    while(I2CCONbits.PEN == 1); //等待停止操作完成  
}

int main()
{
	ConfigI2CEEPROM();		
    PORTGbits.RG8 = 0;
    PageWrite();
    for(i=0; i<650000; i++); //页写操作后的等待
    PageRead();
    while(1);
}

⌨️ 快捷键说明

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