51 单片机[2-3]:LED流水灯

摘要:

本文使用STC80C51RC单片机实现了LED流水灯


创建项目,具体方法见[2-1]

一、固定延时

c 复制代码
#include <REGX52.H>
#include <INTRINS.H>

void Delay500ms()		//@12.000MHz
{
	unsigned char i, j, k;

	_nop_();
	_nop_();
	i = 23;
	j = 205;
	k = 120;
	do
	{
		do
		{
			while (--k);
		} while (--j);
	} while (--i);
}

void main()
{
	while(1)
	{
		P2 = 0xfe;//1111 1110
		Delay500ms();
		P2 = 0xfd;//1111 1101
		Delay500ms();
		P2 = 0xfb;//1111 1011
		Delay500ms();
		P2 = 0xf7;//1111 0111
		Delay500ms();
		P2 = 0xef;//1110 1111
		Delay500ms();
		P2 = 0xdf;//1101 1111
		Delay500ms();
		P2 = 0xbf;//1011 1111
		Delay500ms();
		P2 = 0x7f;//0111 1111
		Delay500ms();
	}
}

Delay500ms();函数是在STC-ISP软件中通过手动设置生成的,调整起来很不灵活。

如何定义一个函数,让我们在代码中灵活调整时间?

二、可变延时

先在STC-ISP中生成 1 毫秒延时的代码,复制一下

注意修改指令集为STC-Y1

c 复制代码
void Delay1ms()		//@12.000MHz
{
	unsigned char i, j;

	i = 2;
	j = 239;
	do
	{
		while (--j);
	} while (--i);
}

现在Delay1ms()函数是不接受任何参数的,我们需要让它接受一个形参xms

首先把void Delay1ms()改为void Delay1ms(unsigned int xms)

执行一次这段代码就耗时 1ms ,也就是说,这段代码执行几次就耗时几毫秒。

c 复制代码
	i = 12;
	j = 169;
	do
	{
		while (--j);
	} while (--i);

所以用一个while循环和xms自减来编写函数

c 复制代码
void Delay1ms(unsigned int xms)		//@12.000MHz
{
	unsigned char i, j;
	while(xms)
	{
		i = 2;
		j = 239;
		do
		{
			while (--j);
		} while (--i);
		xms--;
	}

}

主函数跟刚才的差不多

c 复制代码
void main()
{
	while(1)
	{
		P2 = 0xfe;//1111 1110
		Delay1ms(100);
		P2 = 0xfd;//1111 1101
		Delay1ms(100);
		P2 = 0xfb;//1111 1011
		Delay1ms(100);
		P2 = 0xf7;//1111 0111
		Delay1ms(100);
		P2 = 0xef;//1110 1111
		Delay1ms(100);
		P2 = 0xdf;//1101 1111
		Delay1ms(100);
		P2 = 0xbf;//1011 1111
		Delay1ms(100);
		P2 = 0x7f;//0111 1111
		Delay1ms(100);
	}
}

下载程序之后可以看到流水灯

相关推荐
iCxhust16 分钟前
如何在汇编中修改CS:IP
汇编·单片机·嵌入式硬件·51单片机·微机原理
Chat_zhanggong34522 分钟前
主推NT98336BG作用有哪些?
嵌入式硬件·算法
Deitymoon28 分钟前
STM32——433M无线遥控灯
stm32·单片机·嵌入式硬件
XD74297163637 分钟前
001. MSP430G2553 入门总述:从零开始学习这颗单片机
单片机·嵌入式硬件·学习·嵌入式·msp430g2553
模拟IC攻城狮43 分钟前
华为2026 年校园招聘——硬件技术工程师-电源方向-机试题(12套)(每套四十题)
嵌入式硬件·华为·硬件架构·芯片
阿哟阿哟1 小时前
立创3D模型快速下载
笔记·单片机·嵌入式硬件
三佛科技-134163842121 小时前
FT62F0GCA-LRB智能温控仪上的应用优势分析
单片机·嵌入式硬件·物联网·智能家居·pcb工艺
国产芯片设计1 小时前
小家电驱动开发实战:远乐YL1628在电饭煲显示面板的应用与调试
单片机·嵌入式硬件·mcu·51单片机·硬件工程
LCMICRO-133108477461 小时前
长芯微LD1871完全P2P替代AD1871,是一款立体声音频ADC
单片机·嵌入式硬件·fpga开发·音视频·硬件工程·dsp开发·音频adc
12.=0.1 小时前
【stm32_7】定时器的原理与应用、基本定时器、通用定时器、PWM、模拟脉冲信号的宽度、利用PWM控制外设、逻辑分析仪的使用
c语言·stm32·单片机·嵌入式硬件