/*此为自已写的, 功能:实现按一次按键灯亮,再按一次灯灭 欢迎仿问我的空间http://378621667.qzone.qq.com里头有好多单片机C语言代码 2011年10月24于厦门软件园二期 */ #include <pic.h> //此为pic的代码 #define uint unsigned int #define uchar unsigned char void delay(uint x) //延时函数 { uint a,b; for(a=x;a>0;a--) for(b=110;b>0;b--); } void main() //主函数 { static bit temp; //定义一个静态的位变量,注意得放在第一行,否则会提示一堆的错误 TRISB=0;PORTB=0xff; TRISD=0;PORTD=0x00; temp=RD0; //把RD0 LED灯的当前状态赋给变量temp while(1) { if(RB0==0) //判断按键是否有被按下,有则为0 { delay(10); //去抖 if(RB0==0) //去抖完得再判断一次 { temp=!temp; //每按一次,位变量temp取反一次 while(!RB0) //松手检测,按下时为0取反为1,一直循环直至松手为1取反后为0退出循环 RD0=temp; //把取反后的temp值赋给RD0即LED灯 } } } } //-----------------------下面为51的代码---------------------------------------------------- /* #include <reg52.h> //此为51单片机的代码 #define uint unsigned int #define uchar unsigned char void delay(uint x) //延时函数 { uint a,b; for(a=x;a>0;a--) for(b=110;b>0;b--); } void main() //主函数 { static bit temp; //定义一个静态的位变量,注意得放在第一行,否则会提示一堆的错误 sbit RD0=P1^1; //定义LED灯为RD0 sbit RB0=p3^2; //定义INT0为RB0(按键) temp=RD0; //把RD0 LED灯的当前状态赋给变量temp while(1) { if(RB0==0) //判断按键是否有被按下,有则为0 { delay(10); //去抖 if(RB0==0) //去抖完得再判断一次 { temp=!temp; //每按一次,位变量temp取反一次 while(!RB0) //松手检测,按下时为0取反为1,一直循环直至松手为1取反后为0退出循环 RD0=temp; //把取反后的temp值赋给RD0即LED灯 } } } } */