在线时间6060 小时
UID3426478
注册时间2017-9-25
NXP金币5683
TA的每日心情 | 奋斗 昨天 20:47 |
---|
签到天数: 1485 天 [LV.10]以坛为家III
超级版主
- 积分
- 93126
- 最后登录
- 2024-5-8
|
本帖最后由 stm1024 于 2018-11-21 09:52 编辑
废话少说,直接丢代码,重点是结合手册看时序。- void I2C0_WriteBuffer(uint8_t slaveAddr,uint8_t subAddr,uint8_t* buffer,uint8_t len)
- {
- uint8_t i;
- I2C0_Start();
- LPC_I2C0->DAT=slaveAddr<<1;//write address
- LPC_I2C0->CONSET = CONSET_AA;
- LPC_I2C0->CONCLR = CONCLR_SIC;//send data
- while (LPC_I2C0->STAT != 0x18);
- LPC_I2C0->DAT=subAddr;
- LPC_I2C0->CONSET = CONSET_AA;
- LPC_I2C0->CONCLR = CONCLR_SIC;
- while (LPC_I2C0->STAT != 0x28);
-
- for(i=0;i<len;i++)
- {
- LPC_I2C0->DAT=*(buffer+i);
- LPC_I2C0->CONSET = CONSET_AA;
- LPC_I2C0->CONCLR = CONCLR_SIC;
- while (LPC_I2C0->STAT != 0x28);
- }
- I2C0_Stop();
- }
- void I2C0_ReadBuffer(uint8_t slaveAddr,uint8_t subAddr,uint8_t* buffer,uint8_t len)
- {
- uint8_t i;
- I2C0_Start();
- //dummy write
- LPC_I2C0->DAT=slaveAddr<<1;//write address
- LPC_I2C0->CONSET = CONSET_AA;
- LPC_I2C0->CONCLR = CONCLR_SIC;//send data
- while (LPC_I2C0->STAT != 0x18);
- LPC_I2C0->DAT=subAddr;
- LPC_I2C0->CONSET = CONSET_AA;
- LPC_I2C0->CONCLR = CONCLR_SIC;
- while (LPC_I2C0->STAT != 0x28);
- I2C0_Start();//restart
- LPC_I2C0->DAT=(slaveAddr<<1)|1;//read address
- LPC_I2C0->CONSET = CONSET_AA;
- LPC_I2C0->CONCLR = CONCLR_SIC;
- while (LPC_I2C0->STAT != 0x40);
- LPC_I2C0->CONSET = CONSET_AA;
- LPC_I2C0->CONCLR = CONCLR_SIC;
- //now STAT=0x50
-
- for(i=0;i<len;i++)
- {
- while (LPC_I2C0->STAT != 0x50);
- *(buffer+i)=LPC_I2C0->DAT;
- if(i==len-1)
- {
- LPC_I2C0->CONCLR = CONCLR_SIC|CONCLR_AAC;
- }
- else
- {
- LPC_I2C0->CONSET = CONSET_AA;
- LPC_I2C0->CONCLR = CONCLR_SIC;
- }
- }
- while (LPC_I2C0->STAT != 0x58);
- I2C0_Stop();
- }
复制代码 推荐一个好的方法是阅读手册,然后单步调试,通过寄存器看STAT的值。
测试:
- uint8_t p[16]={0x31,0x50,0x09,0x01,0x12,0x03,0x18};
- int main()
- {
- uint8_t sec,min,hour,day,date,month,century,year;
- uint8_t isPM=0;
- Board_Init();
- I2C0_Init();
- I2C0_WriteBuffer(DS3231ADDR,0x00,p,7);//year
- while(1)
- {
- I2C0_ReadBuffer(DS3231ADDR,0x00,p,7);
- sec=(p[0]>>4)*10+(p[0]&0xf);
- min=(p[1]>>4)*10+(p[1]&0xf);
- if(p[2]>>6)//12-hour mode
- {
- hour=p[2]&0x1f;
- if(p[2]&0x20)//PM
- isPM=1;
- }
- else//24-hour mode
- {
- hour=p[2]&0x3f;
- hour=(hour>>4)*10+(hour&0x0f);
- }
- day=p[3]&0x07;
- date=(p[4]>>4)*10+(p[4]&0xf);
- month=p[5]&0x1f;
- month=(month>>4)*10+(month & 0x0f);
- year=(p[6]>>4)*10+(p[6]&0xf);
- printf("20%02d-%02d-%02d %02d:%02d:%02d",year,month,date,hour,min,sec);
- if(isPM)
- printf(" PM\r\n");
- else
- printf("\r\n");
-
- Delay_ms(999);
- }
- //return 0;
- }
复制代码 运行结果:
|
|