第四章 中断类 例 4-1 P104 假设外部中断0 和外部中断1 均为下降沿触发,当外部中断0 发生时,P0 端口的电平反向,当外部中断1 发生时,P1 端口的电平反向。 #include void IS0(void) interrupt 0 { P0=~P0;} //P0 端口反向 void IS1(void) interrupt 2 { P1=~P1;} //P1 端口反向 void main( ) 2 { P0=0x00; P1=0xFF; IT0=1; IT1=1; EX0=1; EX1=1; EA=1; while(1); } 【例4-9】外部中断示例 在本实例中,首先通过P1.7 口点亮发光二极管D1, 然后外部输入一脉冲串,则发光二极管D1 亮、暗交替。 #include sbit P1_7=P1^7; void interrupt0( ) interrupt 0 using 2 //外部中断0 { P1_7=!P1_7;} void main( ) 3 { EA=1; //开中断 IT0=1; //外部中断0 脉冲触发 EX0=1; //外部中断0 P1_7=0; do{ }while(1); } 如果有3 个脉冲,则灯亮、暗交替一次,可如下面编程: #include Sbit P17=P1^7; unsigned char i=3; void main( ) { EA=1; IT0=1; EX0=1; P17=0; do{ }while(1); } void interrupt0( ) interrupt 0 { i=i-1; if(i==0) { P17=!P17; i=3; } } 【例4-10】如图4-18 所示,8 只 LED 阴极接至单片机P0 口,两开关 4 S0、 S1 分别接至单片机引脚P3.2()和P3.3() 。编写程序控制LED状态。按下S0 后,点亮8 只 LED;按下S1 后,变为闪烁状态。 #include sbit P32=P3^2; void delay(unsigned int d) //定义延时子函数 { while(--d>0); } void main( ) { P0=0xFF; //熄灭LED IT0=1; IT1=1; //外中断0、 1 脉冲触发方式 EA=1; EX0=1; EX1=1; //开中断 for( ; ; ) //延时等待中断发生 {;} 5 } void INT0_ISR( ) interrupt 0//外中断0 中断服务函数 { P0=0x00; } void INT1_ISR( ) interrupt 2//外中断1 中断服务函数 { while(P32!=0) //如果有外部中断0,则退出 { delay(5000); P0=0x00; delay(5000); P0=0xFF; } } 定时类 【例4-16】设单片机的fosc=12MHz,要求在P1.0 上产生周期为2ms的方波。 要在P1.0 上产生周期为2ms 的方波,定时器应产生1ms 的周期性定时,定时到对P1.0 取反。 要产生1ms 的定时,应选择方式1,定时器方式。 TMOD 的确定:选择定时器/计数器T0,定时器方式。方式1, GATE不起作用,高...