51单片机 01 LED
一、点亮一个LED
在STC-ISP中单片机型号选择 STC89C52RC/LE52RC;如果没有找到hex文件(在objects文件夹下),在keil中options for target-output- 勾选 create hex file。
如果要修改编程 :重新编译-下载/编程-单片机重新启动
#include <REGX52.H>
void main()
{
P2=0xFE; //1111 1110 注意是大写P
// P2=0x55; 间隔亮LED小灯
while(1)
{
}
}
二、LED闪烁
这里我的keil中我STC database出现了于是我就选了STC89C52RC。
RC后缀单片机的系统频率是 11.0592mhz。
#include <STC89C5xRC.H>
#include <INTRINS.H>
void Delay500ms() //@11.0592MHz
{
unsigned char i, j, k;
_nop_(); // need .h file
i = 4;
j = 129;
k = 119;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void main(){
while(1){
P2=0xFE;
Delay500ms();
P2=0xFF;
Delay500ms();
}
}
三、LED 流水灯
LED和蜂鸣器共用P2引脚,所以会响(正常现象)
#include <STC89C5xRC.H>
void Delay500ms() //@11.0592MHz
{
unsigned char i, j, k;
// _nop_(); // can delete this sentense
i = 4;
j = 129;
k = 119;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void main()
{
while(1)
{
P2=0xFE;
Delay500ms();
P2=0xFD;
Delay500ms();
P2=0xFB;
Delay500ms();
P2=0xF7;
Delay500ms();
P2=0xEF;
Delay500ms();
P2=0xDF;
Delay500ms();
P2=0xBF;
Delay500ms();
P2=0x7F;
Delay500ms();
}
}
四、流水灯代码优化版
unsigned char: 适用于 8 位数据(如 P2 寄存器),内存占用小,与硬件匹配度高。
注意在 delay 函数中选择的值是500,所以要用unsigned int。
左移运算符 << 会将二进制数向左移动一位,右边空出的位用 0 填充。
按位或运算符 | 会将两个二进制数的每一位进行或运算。|0x01:将最低位置1。
#include <STC89C5xRC.H>
void Delayms(unsigned int x) //@11.0592MHz
{
unsigned char i, j;
while(x)
{
i = 2;
j = 199;
do
{
while (--j);
} while (--i);
x--;
}
}
void main()
{
unsigned char pattern =0xFE;
while(1)
{
P2=pattern;
Delayms(500);
pattern=(pattern<<1)|0x01; //() is more distinct
if(pattern==0xFF) pattern=0xFE;
}
}