功能:按下K1时D1亮,松开时D1灭,P3_1对应K1 , P2_0对应D1
#include <REGX52.H>void main()
{while(1) {if(P3_1 == 0) //按下K1{P2_0 = 0;}else{P2_0 = 1;}}}
按下按钮和松开按钮时会有抖动,所以需要用延时函数来避免抖动造成的影响
功能:每按一次按钮,改变一次D1的状态
在这里如果一直按着按键就无法跳出while,就无法改变灯的状态
#include <REGX52.H>
#include <INTRINS.H>void Delay(unsigned int t) //@11.0592MHz
{unsigned char i, j;while(t --){_nop_();i = 2;j = 199;do{while (--j);} while (--i);}
}void main()
{while(1){if(P3_1 == 0) //按下K1{Delay(20); //按下消抖while(P3_1 == 0); //按完松开才能执行下一步操作Delay(20); //松开消抖P2_0 = ~P2_0; //亮变灭,灭变亮}}}
功能:用LED灯实现二进制,每按一次加1
#include <REGX52.H>
#include <INTRINS.H>void Delay(unsigned int t) //@11.0592MHz
{unsigned char i, j;while(t --){_nop_();i = 2;j = 199;do{while (--j);} while (--i);}
}void main()
{unsigned char LedNum = 0; //刚好八位,存P2的状态while(1){if(P3_1 == 0){Delay(20);while(P3_1 == 0);Delay(20);LedNum ++;P2 = ~LedNum;}}
}
功能:每按一次,LED灯移动一位
#include <REGX52.H>
#include <INTRINS.H>void Delay(unsigned int t);unsigned char LedNum; //表示移动位数void main()
{while(1){if(P3_1 == 0) //按下K1{Delay(20);while(P3_1 == 0);Delay(20);LedNum ++;if(LedNum == 8) LedNum = 0;P2 = ~(0x01 << LedNum);}if(P3_0 == 0) //按下K2{Delay(20);while(P3_0 == 0);Delay(20);if(LedNum == 0) LedNum = 7;else LedNum --;P2 = ~(0x01 << LedNum);}}
}void Delay(unsigned int t)
{unsigned char i, j;while(t --){_nop_();i = 2;j = 199;do{while (--j);} while (--i);}
}