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

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

相关推荐
宵时待雨20 小时前
STM32笔记归纳8:时钟
笔记·stm32·单片机·嵌入式硬件
JJRainbow21 小时前
SN75176 芯片设计RS-232 转 RS-485 通信模块设计原理图
stm32·单片机·嵌入式硬件·fpga开发·硬件工程
花月mmc1 天前
CanMV K230 波形识别——整体部署(4)
人工智能·python·嵌入式硬件·深度学习·信号处理
宁静致远20211 天前
STM32模拟IIC读取PCF8563
stm32·单片机·嵌入式硬件
三佛科技-134163842121 天前
宠物洗澡打泡机方案,宠物泡泡机MCU方案开发设计分享
单片机·嵌入式硬件·物联网·智能家居·pcb工艺·宠物
芯岭技术1 天前
低成本315/433M接收芯片 XL420 SOP8封装,支持 1527 等常见 OOK编码
单片机·嵌入式硬件
Wangshanjie_981 天前
【通讯协议】-01、Modbus协议
单片机·信息与通信
听风吹雨yu1 天前
STM32F407-MD5码计算/Digest认证计算
stm32·单片机·嵌入式硬件
yugi9878381 天前
RN8302B电表芯片驱动开发指南(基于SPI通信)
驱动开发·单片机·嵌入式硬件
youcans_1 天前
【STM32-MBD】(15)Simulink 模型开发之三相互补 PWM
stm32·单片机·嵌入式硬件·matlab·foc