C51点灯学习
#点灯环节
点亮第一个灯
原理:从VCC正极电极过来,若碰到的组件是 1,那么就会不亮(因为两个都是高电平),若碰到的组件是 0,则会通过高低电平来促使灯发亮
#include <REGX52.H>
void main()
{
P2 = 0xFE;//由高往低数(从P27 ~ P20)1111 1110
}
让灯交互闪烁
#include <REGX52.H>
#include <INTRINS.H>
void Delay500ms() //@12.000MHz
{
unsigned char i, j, k;
_nop_();
i = 4;
j = 205;
k = 187;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void main()
{
while(1)
{
P2 = 0xFE;
Delay500ms();
P2 = 0xFF;
Delay500ms();
}
}
/*
P2 = 0x49;
Delay500ms();
P2 = 0xB6;
Delay500ms();
*/
流水灯实现
#include <REGX52.H>
void Delay1ms(unsigned int xms) //@12.000MHz
{
unsigned char i, j;
while(xms)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
xms--;
}
}
void main()
{
while(1)
{
P2 = 0xFE;
Delay1ms(100);
P2 = 0xFD;
Delay1ms(100);
P2 = 0xFB;
Delay1ms(100);
P2 = 0xF7;
Delay1ms(100);
P2 = 0xEF;
Delay1ms(100);
P2 = 0xDF;
Delay1ms(100);
P2 = 0xBF;
Delay1ms(100);
P2 = 0x7F;
Delay1ms(100);
}
}
独立按键控制灯
#include <REGX52.H>
void main()
{
//P3_1 == 0表示按下
if(P3_1 == 0)//注意这里的独立按键串口,第一个独立按键是P3_1的串口,第二个独立按键是P3_0的串口
{
P2_0 = 1;//表示寄存器中8位中的一位
}else P2_0 = 0;
}
独立按键控制灯状态
注意:单片机上电后所有串口默认是高电平(1)
#include <REGX52.H>
void Delay1ms(unsigned int xms) //@12.000MHz
{
unsigned char i, j;
while(xms)
{
i = 12;
j = 169;
do
{
while (--j);
} while (--i);
xms--;
}
}
void main()
{
while(1)
{
//P2_0 = 0;
if(!P3_1)
{
Delay1ms(20);
while(!P3_1);
Delay1ms(20);
P2_0 = ~P2_0;
}
}
}
实现二进制点灯方式
用需要定义一个字符去表示对应的二进制数,不断累加
#include <REGX52.H>
void Delay1ms(unsigned int xms) //@12.000MHz
{
unsigned char i, j;
while(xms)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
xms--;
}
}
void main()
{
unsigned char erjinzhi = 0;
while(1)
{
if(P3_1 == 0)
{
Delay1ms(20);
while(P3_1 == 0);
Delay1ms(20);
erjinzhi++;
P2 = ~erjinzhi;
}
}
}
实现按键操控灯移向
单键操控
#include <REGX52.H>
void Delay1ms(unsigned int xms) //@12.000MHz
{
unsigned char i, j;
while(xms)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
xms--;
}
}
void main()
{
unsigned char Num = 0;
P2 = ~(0x01);//需要初始化P2的第一位,因为不初始化会直接跳过第一位
while(1)
{
if(P3_1 == 0)
{
Delay1ms(20);
while(P3_1 == 0);
Delay1ms(20);
Num++;
if(Num == 8)Num = 0;
P2 = ~(0x01<<Num);
}
}
}
双键操控
#include <REGX52.H>
void Delay1ms(unsigned int xms) //@12.000MHz
{
unsigned char i, j;
while(xms)
{
i = 2;
j = 239;
do
{
while (--j);
} while (--i);
xms--;
}
}
void main()
{
unsigned char Num = 0;
P2 = ~(0x01);//ÐèÒª³õʼ»¯P2´®¿ÚµÄÖµ£¬ÒòΪÈç¹û²»³õʼ»¯»áÌø¹ýµÚһλ
while(1)
{
if(P3_1 == 0)
{
Delay1ms(20);
while(P3_1 == 0);
Delay1ms(20);
Num++;
if(Num == 8)Num = 0;
P2 = ~(0x01<<Num);
}
if(P3_0 == 0)
{
Delay1ms(20);
while(P3_0 == 0);
Delay1ms(20);
if(Num == 0)Num = 7;
else Num --;
P2 = ~(0x01 << Num);
//这里为什么继续用左移
//因为你的Num在执行K1按键的时候,Num自增了1,然后你在决定按K2的时候,Num又自减了1,相当于在K1的基础上右移了一位
}
}
}