2016年3月24日 星期四

微處理器實作: AT89S52 程式練習(多重中斷)

        這個練習在於練習同時使用多個中斷服務: 兩個內部計數器(timer0, timer1)和兩個外部中斷(按鍵P3.2和P3.3)。timer0 控制變數mynum,每秒加1,timer1 控制變數mynum_2,每0.5秒加1,按鍵P3.2 按下時,將mynum_2歸0,按鍵P3.3 按下時,將mynum歸0。


執行結果:



完整程式碼如下:

#include <regx52.h>

#define LED_NUM_0 0xC0
#define LED_NUM_1 0xF9
#define LED_NUM_2 0xA4
#define LED_NUM_3 0xB0
#define LED_NUM_4 0x99
#define LED_NUM_5 0x92
#define LED_NUM_6 0x82
#define LED_NUM_7 0xF8
#define LED_NUM_8 0x80
#define LED_NUM_9 0x98

#define LED_OUT P1

int count   = 1024;
int count_2 = 1024;
int mynum = 0;
int mynum_2 = 0;

unsigned char led_num[10] =
{
LED_NUM_0, LED_NUM_1, LED_NUM_2, LED_NUM_3, LED_NUM_4, 
LED_NUM_5, LED_NUM_6, LED_NUM_7, LED_NUM_8, LED_NUM_9
};

void my_delay(unsigned int n)
{
unsigned int i, j;

for(j=0; j<n; j++)
for(i=0; i<120; i++) ; 

}

void T0_int(void) interrupt 1
{
TL0 = (65535-1024*12) % 256;
TH0 = (65535-1024*12) / 256;

if(count ==0 )
{
count=1024; // 1024*1204*12 => 1 second
mynum++;
if (mynum == 10) mynum = 0;

}
else 
           count--;
}

void T1_int(void) interrupt 3
{
TL1 = (65536-1024*6) % 256;
TH1 = (65536-1024*6) / 256;

if(count_2 ==0 )
{
count_2=1024; // 1024*1204*12 => 1 second
mynum_2++;
if (mynum_2 == 10) mynum_2 = 0;

}
else 
count_2--;
}

void EX0_int(void) interrupt 0
{
mynum_2 = 0;
}

void EX1_int(void) interrupt 2
{
mynum = 0;
}

main()
{

TMOD = 0x00;                  // set timer control register
TL0 = (65536-1024*12) % 256;  // set count number:12K for 1/1024 sec
TH0 = (65536-1024*12) / 256;  // set count number:12K(TH  1/1024 sec
TL1 = (65536-1024*6)  % 256;  // set count number: 6K(TL  1/2048 sec
TH1 = (65536-1024*6)  / 256;  // set count number: 6K(TL  1/2048 sec

ET0 =1; ET1 = 1; EX0 = 1; EX1 = 1; EA =1; //set IE register
TR0 =1; TR1 = 1; IT0 = 1; IT1 = 1;        //set TCON register      
P3_4 = 0; //pull low p3.4 for enable EX0 and EX1

while(1)
{
   P3_0 = 0; P3_1 =1;
   LED_OUT = led_num[mynum];
   my_delay(3);
   LED_OUT = 0xFF;  
  
          P3_0 = 1; P3_1 =0;
 LED_OUT = led_num[mynum_2];
  my_delay(3);
  LED_OUT = 0xFF;
}
}

沒有留言:

張貼留言