i2c.h
#define OV9640_Device 0x3c
extern unsigned char I2cError;
void I2cBus_Init(void);
void I2cWrite(unsigned char Address,unsigned char dat);
unsigned char I2cRead(unsigned char Address);
i2c.c
#include <LM3Sxxxx.H>
#include "i2c.h"
unsigned char I2cError;
//------------------------------------------------------------------
void I2cBus_Init(void)
{
SysCtlPeripheralEnable(SYSCTL_PERIPH_I2C0);
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
GPIOPinTypeI2C(GPIO_PORTB_BASE,GPIO_PIN_2 | GPIO_PIN_3);
I2CMasterInit(I2C0_MASTER_BASE,false);
I2CMasterEnable(I2C0_MASTER_BASE);
}
//------------------------------------------------------------------
unsigned char I2cCheckBusyAndErr(void)
{
unsigned int i;
for(i=0;;i++){
if(I2CMasterBusy(I2C0_MASTER_BASE)==false)break;
if(i==1000)return 2;
d1ms();
}
if(I2CMasterErr(I2C0_MASTER_BASE)==true)return 3;
return 0;
}
//------------------------------------------------------------------
void I2cWrite(unsigned char Address,unsigned char dat)//写一个字节数据
{
I2cError=0;
I2CMasterSlaveAddrSet(I2C0_MASTER_BASE,OV9640_Device>>1,false);//写
I2CSlaveDataPut(I2C0_MASTER_BASE,Address);
I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_BURST_SEND_START);//S+DRVICE+A+ADDRESS+A
if(I2cCheckBusyAndErr())goto WriteErr;
I2CSlaveDataPut(I2C0_MASTER_BASE,dat);
I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_BURST_SEND_FINISH);//DATA+A+S
if(I2cCheckBusyAndErr())goto WriteErr;
return;
WriteErr:
I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_BURST_SEND_ERROR_STOP);//S
I2cError=1;
return;
}
//------------------------------------------------------------------
unsigned char I2cRead(unsigned char Address)//读一个字节数据
{
unsigned int temp;
I2cError=0;
I2CMasterSlaveAddrSet(I2C0_MASTER_BASE,OV9640_Device>>1,false);//写
I2CSlaveDataPut(I2C0_MASTER_BASE,Address);
I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_SINGLE_SEND);//S+DRVICE+A+ADDRESS+A+P
if(I2cCheckBusyAndErr())goto ReadErr;
I2CMasterSlaveAddrSet(I2C0_MASTER_BASE,OV9640_Device>>1,true);//读
I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_SINGLE_RECEIVE);//S+DEVICE+REV_DATA+N+P
if(I2cCheckBusyAndErr())goto ReadErr1;
temp="I2CMasterDataGet"(I2C0_MASTER_BASE);
return(temp);
ReadErr:
I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_BURST_SEND_ERROR_STOP);//S
I2cError=1;
return(0xfe);
ReadErr1:
I2CMasterControl(I2C0_MASTER_BASE, I2C_MASTER_CMD_BURST_RECEIVE_ERROR_STOP);//S+RUN
I2cError=1;
return(0xfe);
}
应用:
I2cBus_Init();//初始化
i=I2cRead(0x00);读地址0x00的数据
I2cWrite(0x01,0x80);//写数据0x80到地址0x01里
这个程序只是读写一个字节的,地址码也只是一个字节的,如果要读24C256这样双字节地址那程序还要改,要想一次读写几个字节也要改程序.
文章评论(0条评论)
登录后参与讨论