#include "SmartM_M0.h"
//0 1 2 3 4 5 6 7 8 9
const uint8_t TM1637_CODE[16]={0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F,
//A B C D E F
0x77, 0X7F, 0x39, 0x3F, 0x79, 0x71};
#define I2C_CLOCK 13
VOID I2CInit(VOID)
{
P3_PMD &= ~(Px4_PMD | Px5_PMD | Px2_PMD);
P3_PMD |= (Px4_OD | Px5_OD | Px2_OUT); //使能I2C0引脚
P3_MFP &= ~(P34_T0_I2CSDA | P35_T1_I2CSCL);
P3_MFP |= (I2CSDA | I2CSCL); //选择P3.4,P3.5作为I2C0功能引脚
APBCLK |= I2C0_CLKEN; //使能I2C0时钟
I2CLK = I2C_CLOCK;
I2CON |= ENSI; //使能I2C
}
void TM1637_Write(UINT8 led)
{
UINT8 i, ge, shi, bai, qian;
I2CON |= STA; //启动
/* 40H地址自动加1模式,44H固定地址模式,本程序采用自加1模式 */
I2DAT = 0x40;
I2CON &= (~AA); //发送ACK
I2CON |= STO; //停止
/*写起始地址命令(0C0H),地址从00H单元开始。*/
I2CON |= STA; //启动
I2DAT = 0xc0;
I2CON &= (~AA); //发送ACK
/*写数据,显示4位数码管,地址自动加1*/
for(i=0; i<4; i++)
{
if(i==0) //第一位数码管
{
ge = led%10;
I2DAT = TM1637_CODE[ge];
I2CON &= (~AA); //发送ACK
// I2CON |= SI;
// while ((I2CON & SI) != SI);
}
if(i==1) //第二位数码管
{
shi = led%100/10;
I2DAT = TM1637_CODE[shi];
I2CON &= (~AA); //发送ACK
// I2CON |= SI;
// while ((I2CON & SI) != SI);
}
if(i==2) //第三位数码管
{
bai = led%1000/100;
I2DAT = TM1637_CODE[bai];
I2CON &= (~AA); //发送ACK
// I2CON |= SI;
// while ((I2CON & SI) != SI);
}
if(i==3) //第四位数码管
{
qian = led/1000;
I2DAT = TM1637_CODE[qian];
I2CON &= (~AA); //发送ACK
}
}
I2CON |= STO; //停止
}
void TM1637_Read(u8 Rkey)
{
UINT8 i;
I2CON |= STA; //启动
I2CON |= SI;
while ((I2CON & SI) != SI);
I2CON &= ((~STA)&(~SI));
//写入读地址
I2DAT = 0x42;
I2CON |= SI;
while ((I2CON & SI) != SI);
//读取数据
I2CON |= AA;
for(i=0; i<8; i++)
{
I2CON |= SI;
while ((I2CON & SI) != SI);
I2DAT = Rkey>>1;
}
//发送NACK到TM1637,执行断开连接操作
I2CON &= (~AA);
I2CON |= SI;
while ((I2CON & SI) != SI);
I2CON |= STO; //停止
// I2CON |= SI;
// while (I2CON & STO);
// return TRUE;
}
INT32 main(VOID)
{
UINT8 i, dadt = 128, key;
Un_Lock_Reg(); //ISP下载时保护FLASH存储器
PWRCON |= OSC22M_EN; //默认时钟源为外部晶振
while((CLKSTATUS & OSC22M_STB) == 0); //等待12MHz时钟稳定
CLKSEL0 = (CLKSEL0 & (~HCLK)) | HCLK_22M; //设置外部晶振为系统时钟
I2CInit();
while(1)
{
TM1637_Write(dadt); //执行写操作
Delayms(500);
TM1637_Read(key); //执行读操作
for(i=0; i<4; i++)
{
if(key != 0xff)
{
switch(key)
{
case 0xf7:
P2_DOUT &= 0X01;
break;
case 0xf6:
if(dadt<255)
{
dadt++;
}
break;
case 0xf5:
if(dadt>0)
{
dadt--;
}
break;
case 0xf4:
P2_DOUT |= 0x01;
break;
default:
break;
}
}
}
Delayms(500);
}
}
|