//--------------------------------------------------------------------------------
#include <stdio.h> /* prototype declarations for I/O functions */
#include <LPC2103.H> /* LPC21xx definitions */
#include "Main.h"
//--------------------------------------------------------------------------------
/**************************************************************************/
/***********************************************************************************/
#define STA (1<<5) //起始位 0010 0000
#define I2CEN (1<<6) //允许位 0100 0000
#define STO (1<<4) //停止位 0001 0000
#define SI (1<<3) // 中断标志 0000 1000
#define AA (1<<2) // 响应(应答)标志 0000 0100 I2C0CONCLR=AA;
void i2cInit(void);//I2C初始化程序
void i2cStart(void);//I2C发送起始位
void i2cStop(void);//I2C发送停止位
void i2cwrite(UINT8 value);
void delayMs(int dly);//延时
void UART1_Init (void)
{
UINT16 Fdiv;
PINSEL0 = 0x00050000;
U1LCR = 0x83; // DLAB = 1,可设置波特率
Fdiv = (Fpclk / 16)/ UART_BPS; // 设置波特率
U1DLM = Fdiv / 256;
U1DLL = Fdiv % 256;
U1LCR = 0x03;
}
/*****************************PLL初始化**************************************/
void PLL_Init(void)
{
/* 设置系统各部分时钟 */
#if (Fcco / Fcclk) == 2
PLLCFG = ((Fcclk / Fosc) - 1) | (0 << 5);
#endif
#if (Fcco / Fcclk) == 4
PLLCFG = ((Fcclk / Fosc) - 1) | (1 << 5);
#endif
#if (Fcco / Fcclk) == 8
PLLCFG = ((Fcclk / Fosc) - 1) | (2 << 5);
#endif
#if (Fcco / Fcclk) == 16
PLLCFG = ((Fcclk / Fosc) - 1) | (3 << 5);
#endif
PLLFEED = 0xaa;
PLLFEED = 0x55;
while((PLLSTAT & (1 << 10)) == 0);
PLLCON = 3;
PLLFEED = 0xaa;
PLLFEED = 0x55;
}
void i2cInit(void)
{
PINSEL0 &= ~((3 << 4) | (3 << 6));
PINSEL0 |= ((1 << 4) | (1 << 6));
I2C0SCLH = 15; //Set bit rate 12Mhz/VPBDIV+SCLH+SCLL = 12/4/(15+15) = 100Khz
I2C0SCLL = 15;
I2C0CONCLR = 0XFF;
I2C0CONSET = I2CEN;
}
//I2C发送起始位
void i2cStart(void)
{
I2C0CONSET=STA;
do{}
while(I2C0STAT!=0x08);//等待起始条件发送完成
I2C0CONCLR=STA;
}
//I2C发送停止位
void i2cStop(void)
{
I2C0CONSET=STO;//启动发送stop位,STO位是自动清除的,不必判断是否结束
I2C0CONCLR=SI; //只能清除SI,如果同时清除STO会导致返回到初始化状态
}
void i2cwrite(UINT8 value)
{
i2cStart();
I2C0DAT=value;
I2C0CONCLR=SI;
i2cStop();
}
void delayMs(int dly)
{
int i;
for(;dly>0;dly--)
for(i=0;i<1000;i++);
}
int main (void)
{
int TEMP;
PLL_Init();
UART1_Init();
printf("\n\n\n串口连接成功!");
i2cInit();//I2C初始化
i2cStart();
I2C0DAT=0x9e; // 1001 1110 (bit0位 0是写,1是读)
// I2C0CONCLR=AA;
I2C0CONCLR=SI;
while(I2C0STAT!=0x20); //等待MCP9801应答
printf("\nMCP9801已经应答");
// delayMs(2);
// i2cStart();
I2C0DAT=0x00;//写入00,配置为温度寄存器
I2C0CONCLR=SI;
while(I2C0STAT!=0xC0); // 为什么到这步出不去呢???应该是什么值??求高手指导!
printf("\n配置温度寄存器成功!");
i2cStart();
I2C0DAT=0x9f; //读值
while(I2C0STAT!=0x28);
TEMP=I2C0DAT;
printf("\n\n TEMP");
} |