jgphu发表于 2010-10-18 14:57 | 只看该作者 回复 引用 编辑 评分 返回版面 TOP 得分:0
6楼: 还有下面的
#include "iic.h"
void IIC_Init(void)
{
UCHAR temp;
CLK_PCKENR1 |= 0x01;
I2C_FREQR |= 0x10; //输入外设时钟频率为1MHz
I2C_CR1 = 0x00; //禁止I2C外设
I2C_CCRH &= ~0xcf;
I2C_CCRL &= ~0xff;
I2C_TRISER = 0x11;
I2C_CCRL = 0x10;
I2C_CCRH = 0x00;
I2C_CR1 |= 0x01; //开启I2C外设
I2C_CR2 |= 0x04; //当前接收字节返回应答
I2C_CR2 &= 0x08;
I2C_OARL = 0x86; //自身地址
I2C_OARH = 0x40;
}
void Read_8816(UCHAR *pBuffer, UCHAR index, UCHAR NumByteToRead)
{
UCHAR temp;
while(I2C_SR3 & 0x02); //等待总线空闲
I2C_CR2 |= 0x01; //产生起始位
while(!(I2C_SR1 & 0x01)); //等待START发送完
I2C_DR = 0x8a; //发送8816器件地址
while(!(I2C_SR1 & 0x02)); //等特7位器件地址发送完
temp = I2C_SR1;
temp = I2C_SR3;
I2C_DR = (UCHAR)(index);
while(!(I2C_SR1 & 0x84));
I2C_CR2 |= 0x01; //产生重复起始位
while(!(I2C_SR1 & 0x01)); //等待START发送完
I2C_DR = 0x8b; //读
while(!(I2C_SR1 & 0x02)); //等特7位器件地址发送完
temp = I2C_SR1;
temp = I2C_SR3;
while(NumByteToRead) //要读几个字节
{
if(NumByteToRead == 1)
{
I2C_CR2 &= ~0x04; //不返回应答
I2C_CR2 |= 0x02; //产生停止位
}
if(I2C_SR1 & 0x40)
{
temp = I2C_SR1;
*pBuffer = I2C_DR;
pBuffer++;
NumByteToRead--;
}
}
I2C_CR2 |= 0x04;
I2C_CR2 &= ~0x08; //为下一次接收使能应答
} |