[51单片机] 第七节 定时器和中断总结<代码部分>
ps: 单片机的可位寻址/不可位寻址
- 可位寻址:可以对单个位赋值
- 不可位寻址:只能整体赋值
代码示例:
1 2 3 4 5
| void Timer0_Init() { TMOD=0x01; TF=0; }
|
定时器的快捷配置
晶振电路简介(这里所使用晶振为11.0592MHZ)
一、中断测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include <REGX52.H> #include "Tmier0.h"
void main() { Timer0_Init(); while(1) { } }
void Timer0_Routine() interrupt 1 { static unsigned int T0Count; TL0 = 0x66; TH0 = 0xFC; T0Count++; if(T0Count>=1000) { T0Count=0; P2_0 =~P2_0; } }
|
ps: 中断执行模块不宜存在过于复杂的任务
二、基于中断系统的流水灯按键控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| #include <REGX52.H> #include "Timer0.h" #include "Key.h" #include <INTRINS.H>
unsigned char keynum,LEDMode; void main() { P2=0xFE; Timer0_Init(); while(1) { keynum = Key(); if(keynum) { if(keynum == 1) { LEDMode++; if(LEDMode>=2)LEDMode=0; } } } }
void Timer0_Routine() interrupt 1 { static unsigned int T0Count; TL0 = 0x66; TH0 = 0xFC; T0Count++; if(T0Count>=500) { T0Count=0; if(LEDMode == 0) P2=_crol_(P2,1); if(LEDMode == 1) P2=_cror_(P2,1); } }
|
crol和cror函数区别于<<,>>移位操作符,具有“循环移位”的特性,不需要考虑移位“溢出”;
三、基于定时器的LCD数字时钟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <REGX52.H> #include "LCD1602.h" #include "Timer0.h"
unsigned int sec=55,min=59,hour=23; void main() { LCD_Init(); LCD_ShowString(1,1,"CLOCK:"); LCD_ShowString(2,3,": : "); Timer0_Init(); while(1) { LCD_ShowNum(2,1,hour,2); LCD_ShowNum(2,4,min,2); LCD_ShowNum(2,7,sec,2); } }
void Timer0_Routine() interrupt 1 { static unsigned int T0Count; TL0 = 0x66; TH0 = 0xFC; T0Count++; if(T0Count>=1000) { T0Count=0; P2_0=~P2_0; sec++; if(sec >=60) { sec=0; min++; } if(min >=60) { min=0; hour++; } if(hour >=24) { hour=0; } } }
|
思考:Verilog/VHDL和单片机(c语言) 程序执行区别?
- c语言程序为顺序执行,而非并行执行,单片机中需要动态执行的任务要放在while循环体中