⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 key01.c

📁 MSP430单片机C语言应用程序设计实例精讲(秦龙编著)
💻 C
字号:
#include <msp430x14x.h>

void Delay(void);
int KeyScan(void);
int KeyProcess(void);
void Init_Port(void)
{
    //将P1口所有的管脚在初始化的时候设置为输入方式
    P1DIR = 0;
 
    //将P1口所有的管脚设置为一般I/O口
    P1SEL = 0;
    
    // 将P1.4 P1.5 P1.6 P1.7设置为输出方向
    P1DIR |= BIT4;
    P1DIR |= BIT5;
	P1DIR |= BIT6;
    P1DIR |= BIT7;

	//先输出低电平
	P1OUT = 0x00;
    return;
}
int KeyScan(void)
{
	int nP10,nP11,nP12,nP13;
	int nRes = 0;
	for(;;)
	{
		//读取各个管脚的状态
		nP10 = P1IN & BIT0;
		nP11 = (P1IN & BIT1) >> 1;
		nP12 = (P1IN & BIT2) >> 2;
		nP13 = (P1IN & BIT3) >> 3;

		//是否有键被按下
		if(nP10 == 0 || nP11 == 0 || nP12 == 0 || nP13 == 0)
		{
			//有键被按下
			break;
		}
		
	}
    Delay(); //延时一点时间,消除抖动
	//读取各个管脚的状态
	nP10 = P1IN & BIT0;
	nP11 = (P1IN & BIT1) >> 1;
	nP12 = (P1IN & BIT2) >> 2;
	nP13 = (P1IN & BIT3) >> 3;

	//是否有键被按下
	if(nP10 == 0 || nP11 == 0 || nP12 == 0 || nP13 == 0)
	{
		//有键被按下,进行键盘输入分析
		nRes = KeyProcess();
	}
	else return -1;//没有输入,为干扰

	return nRes;
}
void Delay(void)
{
	int i;
	for(i = 100;i--;i > 0) ;//延时一点时间
}
int KeyProcess(void)
{
	int nRes = 0;
	int nP10;
	int nP11;
	int nP12;
	int nP13;
	//P1.4输出低电平
	P1OUT &= ~(BIT4);
	nP10 = P1IN & BIT0;
	if (nP10 == 0) nRes = 13;
	nP11 = (P1IN & BIT1) >> 1;
	if (nP11 == 0) nRes = 14;
	nP12 = (P1IN & BIT2) >> 2;
	if (nP12 == 0) nRes = 15;
	nP13 = (P1IN & BIT3) >> 3;
	if (nP13 == 0) nRes = 16;
	//P1.5输出低电平
	P1OUT &= ~(BIT4);
	nP10 = P1IN & BIT0;
	if (nP10 == 0) nRes = 9;
	nP11 = (P1IN & BIT1) >> 1;
	if (nP11 == 0) nRes = 10;
	nP12 = (P1IN & BIT2) >> 2;
	if (nP12 == 0) nRes = 11;
	nP13 = (P1IN & BIT3) >> 3;
	if (nP13 == 0) nRes = 12;
	//P1.6输出低电平
	P1OUT &= ~(BIT4);
	nP10 = P1IN & BIT0;
	if (nP10 == 0) nRes = 5;
	nP11 = (P1IN & BIT1) >> 1;
	if (nP11 == 0) nRes = 6;
	nP12 = (P1IN & BIT2) >> 2;
	if (nP12 == 0) nRes = 7;
	nP13 = (P1IN & BIT3) >> 3;
	if (nP13 == 0) nRes = 8;
	//P1.7输出低电平
	P1OUT &= ~(BIT4);
	nP10 = P1IN & BIT0;
	if (nP10 == 0) nRes = 1;
	nP11 = (P1IN & BIT1) >> 1;
	if (nP11 == 0) nRes = 2;
	nP12 = (P1IN & BIT2) >> 2;
	if (nP12 == 0) nRes = 3;
	nP13 = (P1IN & BIT3) >> 3;
	if (nP13 == 0) nRes = 4;

	P1OUT = 0x00;//恢复以前值。

	//读取各个管脚的状态
	nP10 = P1IN & BIT0;
	nP11 = (P1IN & BIT1) >> 1;
	nP12 = (P1IN & BIT2) >> 2;
	nP13 = (P1IN & BIT3) >> 3;
	for(;;)
	{
		if(nP10 == 1 && nP11 == 1 && nP12 == 1 && nP13 == 1)
		{
			//等待松开按键
			break;
		}
	}
	return nRes;
}
void Init_CLK(void)
{
    unsigned int i;
    BCSCTL1 = 0X00;			//将寄存器的内容清零
					//XT2震荡器开启
					//LFTX1工作在低频模式
					//ACLK的分频因子为1
					
    do 
    {
	IFG1 &= ~OFIFG;                       // 清除OSCFault标志
	for (i = 0x20; i > 0; i--);                
    }
    while ((IFG1 & OFIFG) == OFIFG);      // 如果OSCFault =1   
					
    BCSCTL2 = 0X00;			//将寄存器的内容清零
    BCSCTL2 += SELM1;		//MCLK的时钟源为TX2CLK,分频因子为1
    BCSCTL2 += SELS;		//SMCLK的时钟源为TX2CLK,分频因子为1
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -