实验目的:
??测试评估板上的按键和LED
实验内容:
??1、按下s1一次红灯亮1s后熄灭
??2、快速按下s1两次绿灯亮1s后熄灭
|
#ifndef _BSP_LED_H
#define _BSP_LED_H
#include "msp430.h"#define Set_Bit(val,bitn) (val |= (/*1 << */(bitn)))
#define Clr_Bit(val,bitn) (val &= ~(/*1 << */(bitn)))
#define Get_Bit(val,bitn) (val & (1 <<bitn))//LED1
#define LED1_RED_DIR P1DIR
#define LED1_RED_OUT P1OUT
#define LED1_RED_SEL P1SEL
#define LED1_RED_Pin_Num (BIT0) //P1^0#define LED1_RED_IO_Init() (Set_Bit(LED1_RED_DIR,LED1_RED_Pin_Num)) //初始化IO为输出模式
#define LED1_RED_Set() (Set_Bit(LED1_RED_OUT,LED1_RED_Pin_Num))
#define LED1_RED_Clr() (Clr_Bit(LED1_RED_OUT,LED1_RED_Pin_Num))//LED2
#define LED2_GREEN_DIR P4DIR
#define LED2_GREEN_OUT P4OUT
#define LED2_GREEN_SEL P4SEL
#define LED2_GREEN_Pin_Num (BIT7) //P4^7#define LED2_GREEN_IO_Init() (Set_Bit(LED2_GREEN_DIR,LED2_GREEN_Pin_Num))
#define LED2_GREEN_Set() (Set_Bit(LED2_GREEN_OUT,LED2_GREEN_Pin_Num))
#define LED2_GREEN_Clr() (Clr_Bit(LED2_GREEN_OUT,LED2_GREEN_Pin_Num))#endif /*_BSP_LED_H*/
|
#ifndef _BSP_KEY_H
#define _BSP_KEY_H
#include<msp430.h>#define Set_Bit(val,bitn) (val |= (/*1 << */(bitn)))
#define Clr_Bit(val,bitn) (val &= ~(/*1 << */(bitn)))
#define Get_Bit(val,bitn) (val & (1 <<bitn))//s1
#define KEY1_DIR P2DIR
#define KEY1_SEL P2SEL
#define KEY1_OUT P2OUT
#define KEY1_IN P2IN //按键需读入IO口状态值
#define KEY1_Pin_Num (BIT1)#define KEY1_IO_Init() (Clr_Bit(KEY1_DIR,KEY1_Pin_Num)) //初始化IO状态为读取输入电平状态
#define KEY1_Set() (Set_Bit(KEY1_OUT,KEY1_Pin_Num))
#define KEY1_Clr() (Clr_Bit(KEY1_OUT,KEY1_Pin_Num))#endif /*BSP_LED_H*/
|
#include <msp430.h>
#include "bsp_led.h"
#include "bsp_key.h"#define delay_s(x) __delay_cycles(x*1000000)
unsigned int n = 0;void main()
{
WDTCTL = WDTPW + WDTHOLD;LED1_RED_IO_Init(); //初始化设置IO口方向为输出LED2_GREEN_IO_Init();LED1_RED_Clr(); //关闭LED_REDLED2_GREEN_Clr(); //关闭LED_GreenKEY1_IO_Init(); //读取电平输入KEY1_Set();P2REN |= KEY1_Pin_Num; //使能s1按键端口的寄存器P2IE |= KEY1_Pin_Num; //使能s1按键端口中断P2IES |= KEY1_Pin_Num; //s1中断沿触发控制寄存器P2IFG &= ~KEY1_Pin_Num; //s1中断标志寄存器_EINT(); //使能全局中断 __enable_interrupt()while(1){
if(n==0) //当按键一次都没有按下时,红色和绿色LED都不亮{
LED1_RED_Clr();LED2_GREEN_Clr();}else if(n==1) //当按键s1按下一次时,红色LED亮1s后灭{
LED1_RED_Set();LED2_GREEN_Clr();delay_s(1);n=0;}else if(n==2) //当按键s1快速按下两次时,绿色LED亮1s后灭{
LED1_RED_Clr();LED2_GREEN_Set();delay_s(1);n=0;}}
}#pragma vector = PORT2_VECTOR
__interrupt void Port2()
{
unsigned int i=0;if(!(P2IN & KEY1_Pin_Num)) //如果s1被按下 --> 按键共地{
__delay_cycles(5000); //消抖if(!(P2IN & KEY1_Pin_Num)){
while(!(P2IN & KEY1_Pin_Num)){
} //松手检测n = 1;P2IFG &= ~KEY1_Pin_Num;while((P2IN & KEY1_Pin_Num)) //500ms-1000ms内如果不按下,视为只按一次{
i++;__delay_cycles(1000);if(i>1000)return;}if(!(P2IN & KEY1_Pin_Num)){
__delay_cycles(5000); //消抖if(!(P2IN & KEY1_Pin_Num)){
while(!(P2IN & KEY1_Pin_Num)){
} //第二次松手n = 2;P2IFG &= ~KEY1_Pin_Num;}}}}}
代码适用的开发板类型
上述代码可直接烧录到如下图所示的开发板中,作为上手程序: