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);
	}
}

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

相关推荐
小曹要微笑1 小时前
STM32各系列时钟树详解
c语言·stm32·单片机·嵌入式硬件·算法
炸膛坦客2 小时前
Cortex-M3-STM32F1 开发:(三十)HAL 库开发 ➤ 通用定时器 2/3/4/5 的时钟源寄存器设置,以及中断实验
stm32·单片机·嵌入式硬件
2401_853448232 小时前
学习FreeRTOS(第四天)
单片机·嵌入式·freertos
inputA2 小时前
【LwIP源码学习8】netbuf源码分析
android·c语言·笔记·嵌入式硬件·学习
d111111111d3 小时前
STM32外设学习-I2C(细节)--学习笔记
笔记·stm32·单片机·嵌入式硬件·学习
chuwengeileyan13 小时前
stm32 光敏电阻 光控灯
stm32·单片机·嵌入式硬件
ElfBoard4 小时前
ElfBoard技术贴|如何在【RK3588】ELF 2开发板上进行UART引脚复用配置
人工智能·单片机·嵌入式硬件·物联网
就是蠢啊5 小时前
51单片机——数码管
单片机·嵌入式硬件·51单片机
别掩5 小时前
三极管恒流电路
单片机·嵌入式硬件