51单片机学习(1) LED点亮、闪烁以及流水灯实现

时间:2022-07-25
本文章向大家介绍51单片机学习(1) LED点亮、闪烁以及流水灯实现,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

文章目录

一、Keil创建项目

1. 打开keil软件,在工具栏点击Project选项选择new uVision Project创建新的工程并保存,步骤如下图所示:

2. 创建新的文件,按快捷键“Ctrl+S”命名为led.c并保存,步骤如下:

3. 在.c文件中编写C语言程序

#include "reg51.h"    

sbit led=P2^0; 

void main()
{
	while(1)	
		{
			led=0; 
		}       
}

4. 依次点击工具栏中的"Option for target"选择框中的"output ",勾选“Create Hex file ”,确保自己编写的源程序转换为.hex文件,为后续操作使用

5. 依次点击工具栏按钮,生成目标文件

程序运行成功,将在相对路径Object文件夹中生成learning_002.hex文件

二、Proteus搭建虚拟仿真电路

三、LED点亮

搭建好电路后,点击AT89C51主控,导入上文用keil中C语言程序生成的learning_002.hex文件

点击软件右下角的运行按钮,红色的发光二级管被点亮

四、LED闪烁

C语言代码改为如下:

#include "reg51.h"    

unsigned int x;
sbit led=P2^0; 

void main()
{
	x=50000;
	while(1)	
		{
			led=0; //亮
			while(x--);  //延时
			led=1; //灭
			while(x--);	 //延时
		}       
}

五、流水灯实现

1. 流水灯(库函数法)

#include <reg51.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char

uchar temp;
int x;

void main()
{
	x=50000;
	temp = 0x01;
	P1 = temp;
	while(x--);   //延时
	while(1)
	{
		temp = _crol_(temp,1);  //调用库函数
		P1=temp;
		while(x--);
	}
}

2. 流水灯(左移法)

#include <reg51.h>

unsigned int x;
//shift to the left water lamp
void main()
{
	x=50000;
	P1=0x01;
	while(1)
	{
		while(x--);    //delay time
		P1=P1<<1;      //左移
		if(P1==0x00)
			P1=0x01;   //回到起始位置
	}
}

3. 流水灯(右移法)

#include <reg51.h>

unsigned int x;
//shift to the right water lamp
void main()
{
	x=50000;
	P1=0x80;
	while(1)
	{
		while(x--);
		P1=P1>>1;
		if(P1==0x00)
			P1=0x80;
	}

}

4. 流水灯(数组索引法)

#include <reg51.h>
#define uint unsigned int 
#define uchar unsigned char
	
uchar table[]={0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80};
uchar p;
int x;

void main()
{
	x=50000;
	while(1)
		{
		  for(p=0;p<8;p++)
		  {
		  	P1=table[p];
		   	while(x--);
		  }
		  for(p=6;p>=1;p--)
		  {
			P1=table[p];
			while(x--);
		  }
		}
}

作者:叶庭云 微信公众号:修炼Python CSDN:https://yetingyun.blog.csdn.net/ 本文仅用于交流学习,未经作者允许,禁止转载,更勿做其他用途,违者必究。 觉得文章对你有帮助、让你有所收获的话,期待你的点赞呀,不足之处,也可以在评论区多多指正。