首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >51单片机学习(1) LED点亮、闪烁以及流水灯实现

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

作者头像
叶庭云
修改2021-01-23 13:22:14
10K0
修改2021-01-23 13:22:14
举报

文章目录

一、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/ 本文仅用于交流学习,未经作者允许,禁止转载,更勿做其他用途,违者必究。 觉得文章对你有帮助、让你有所收获的话,期待你的点赞呀,不足之处,也可以在评论区多多指正。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-09-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 一、Keil创建项目
  • 二、Proteus搭建虚拟仿真电路
  • 三、LED点亮
  • 四、LED闪烁
  • 五、流水灯实现
    • 1. 流水灯(库函数法)
      • 2. 流水灯(左移法)
        • 3. 流水灯(右移法)
          • 4. 流水灯(数组索引法)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档