LED介绍
- 中文名:发光二极管
- 外文名:Light Emitting Diode
- 简称:LED
- 用途:照明、广告灯、指引灯、屏幕
创建一个工程项目
- 打开Keil
Project>>New Project- 选择单片机型号
AT89C52 - 不添加启动文件 点
否 - 右键
Source Group 1添加 一个新的文件Add New Item - 选择C语言
- 注:要生成
hex文件 需要在设置(Options)中打开Creat HEX File选项
LED 在开发板中的连接方式
点亮一个LED
因为LED 非连接单片机一端连的是VCC, 所以连接单片机引脚的一端 要输出低电压 才可以使得LED点亮
基本原理:
CPU 执行程序给 P2寄存器(8个为一组 分别为 P2_0 — P2_7 )输入数字信号 0为低电平 1为高电平(【TTL电平】高电平:5V 低电平: 0V) 每个寄存器连一个驱动器连接引脚 由驱动器控制高低电平 从而控制LED
因为引脚默认输出的是高电平,所以我们只需要对想要点亮的LED对应引脚输出低电平就可以了
也可以对整组寄存器进行控制
因为一组寄存器是8位 24=16 所以可以用两个十六进制控制一组寄存器
十六进制表示方式 : 0x
| 进制 | 英文 | 范围 | 前缀 | 后缀 |
|---|---|---|---|---|
| 二进制 | Binary | 0-1 | 0B | B |
| 八进制 | Octal | 0-7 | 0O | O |
| 十进制 | Decimal | 0-9 | 无 | D |
| 十六进制 | Hexadecimal | 0-9,A-F | 0x | H |
LED闪烁
我们可以是用STC-ISP 的软件延时计算器工具 生成延时函数
注意:调整系统频率,就是晶振的频率 我的是11.0592MHz
8051指令集为Y1
#include <REGX52.H>
#include <INTRINS.H> //_nop_();语句的头文件
void Delay500ms() //@11.0592MHz 500ms延时函数
{
unsigned char i, j, k;
_nop_();
i = 4;
j = 129;
k = 119;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void main()
{
while(1)
{
P2_0=0;//P2=0xFE;
Delay500ms();
P2_0=1;//p2=0xFF;
Delay500ms();
}
}
流水灯的几种写法
方法一
与LED闪烁一样我们只需要用延时函数,然后依次控制每个灯就可以了
#include <REGX52.H>
#include <INTRINS.H> //延时函数中的_nop_()语句再这个库中定义
void Delay(unsigned int xms) //@11.0592MHz 延时函数
{
unsigned char i, j;
while(xms){
_nop_();
i = 2;
j = 199;
do
{
while (--j);
} while (--i);
xms--;
}
}
void main()
{
while(1)
{
P2=0xFE;//1111 1110
Delay(500);
P2=0xFD;//1111 1101
Delay(500);
P2=0xFB;//1111 1011
Delay(500);
P2=0xF7;//1111 0111
Delay(500);
P2=0xEF;//1110 1111
Delay(500);
P2=0xDF;//1101 1111
Delay(500);
P2=0xBF;//1011 1111
Delay(500);
P2=0x7F;//0111 1111
Delay(500);
}
}
到这里我已成为一名合格的电灯大师!!!
方法二
//方法二 利用数组
#include <REGX52.H>
#include <INTRINS.H>
void Delay(unsigned int xms) //@11.0592MHz 延时函数
{
unsigned char i, j;
while(xms){
_nop_();
i = 2;
j = 199;
do
{
while (--j);
} while (--i);
xms--;
}
}
unsigned char LED[8]={0xFE,0xFD,0xFB,0xF7,0xEF,0xDF,0xBF,0x7F};//定义数组
unsigned int i = 0;
void main()
{
while(1){
for(i=0;i<8;i++)
{
P1 = LED[i];
Delay(500);
}
}
}
方法三
//方法三 利用 << 位移
#include <REGX52.H>
#include <INTRINS.H>
void Delay(unsigned int xms) //@11.0592MHz 延时函数
{
unsigned char i, j;
while(xms){
_nop_();
i = 2;
j = 199;
do
{
while (--j);
} while (--i);
xms--;
}
}
unsigned char i = 0;
void main()
{
while(1)
{
for(i=0;i<8;i++)
{
P1 = ~(0x01 << i ); //目标是1111 1110 写0000 0001 然后取反
Delay(500);
}
}
}
//当然还可以先a = 0xFE;然后定义P1 = a;a = (a << 1)+1;
//还可以每次都P1 << 1; P1 |= 0X01;
方法四
//方法四 利用<INTRINS.H>库中的_corl_()函数
#include <REGX52.H>
#include <INTRINS.H>
void Delay(unsigned int xms) //@11.0592MHz 延时函数
{
unsigned char i, j;
while(xms){
_nop_();
i = 2;
j = 199;
do
{
while (--j);
} while (--i);
xms--;
}
}
unsigned char a=0xFE;
void main()
{
while(1)
{
P1 = a;
Delay(500);
a=_crol_(a,1) ; //将a左移1位,一位后最高位变最低位
}
}