本小實驗基於MSP430f5529,不同的型號可能管腳和中斷配置有所不同。
實現的功能為:
第一次按下按鍵后,系統以每 2 秒鍾,指示燈暗 1 秒,亮 1 秒的方式閃爍。程序采用默認時鍾配置;
第二次按下按鍵后,系統以每 4 秒鍾,指示燈亮 2 秒,暗 2 秒鍾方式閃爍。
第三次按下按鍵后,系統以每 4 秒鍾,指示燈亮 1 秒,暗 3 秒方式閃爍。程序基於定時器配置。
/*
* main.c
* 第一次按下按鍵后,系統以每 2 秒鍾,指示燈暗 1 秒,亮 1 秒的方式閃
爍,程序采用默認時鍾配置;
第二次按下按鍵后,系統以每 4 秒鍾,指示燈亮 2 秒,暗 2 秒鍾方式閃
爍。
第三次按下按鍵后,系統以每 4 秒鍾,指示燈亮 1 秒,暗 3 秒方式閃
爍,程序基於定時器配置。
*/
#include <msp430f5529.h>
int count = 0; //計數
int t1_50ms = 20; //一個單位對應50ms(亮)
int t2_50ms = 20; //一個單位對應50ms(滅)
int flag = 0; //閃爍頻率標志
int flag_t = 1; //亮滅標志
int main(void) {
WDTCTL = WDTPW+WDTHOLD;
//時鍾中斷配置
P1DIR |= BIT0;
TA0CCTL0 = CCIE;//使能定時器中斷
TA0CCR0 = 50000;
TA0CTL = TASSEL_2 + MC_1 + TACLR;//配置為SMCLK,升計數模式,初始化時鍾
//S1配置
P1IE |= BIT7; //允許P1.7中斷
P1IES |= BIT7; //設置為下降沿中斷
P1IFG &= ~BIT7; //設置為輸入
P1REN |= BIT7; //啟用上下拉電阻
P1OUT |= BIT7; //將電阻設置為上拉
__bis_SR_register(LPM0_bits+GIE); //打開中斷
return 0;
}
#pragma vector=TIMER0_A0_VECTOR
__interrupt void TIMER0_A0_ISR(void)
{
if(count==t1_50ms&&flag_t==1) //燈亮
{
P1OUT |= BIT0;
count=0;
flag_t=0;
}
else if(count==t2_50ms&&flag_t==0) //燈滅
{
P1OUT &=~BIT0;
count = 0;
flag_t=1;
}
else count++;
}
#pragma vector=PORT1_VECTOR;
__interrupt void botton (void)
{
__delay_cycles(75);//延時消抖
switch(flag)//flag決定閃爍頻率
{
case 0:
t1_50ms = 20;t2_50ms = 20;break;//1秒亮 1秒暗
case 1:
t1_50ms = 40;t2_50ms = 40;break;//2秒亮 2秒暗
case 2:
t1_50ms = 60;t2_50ms = 20;break;//3秒亮 3秒暗
}
flag++;//狀態變化
if(flag>2) flag = 0;//flag歸位
P1IFG &=~ BIT7; //清除中斷標志位
__bis_SR_register(LPM0_bits+GIE);//打開中斷
}