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

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

相关推荐
Szime4 小时前
高速 ADC 国产替代选型:通信、雷达、仪器仪表项目要看哪些参数?
单片机·嵌入式硬件·fpga开发
菜鸟的学习日记、6 小时前
GPIO的几种模式——以STM32为例
stm32·单片机·嵌入式硬件·gpio
辰哥单片机设计6 小时前
STM32智能睡眠检测系统
stm32·单片机·嵌入式硬件
隔窗听雨眠8 小时前
在STM32上跑通TinyML:从模型训练到推理优化的完整实战指南
stm32·单片机·嵌入式硬件
ryanuo710 小时前
Mac(M芯片)上进行嵌入式开发遇到的问题
嵌入式硬件·macos·开发板
机器视觉知识推荐、就业指导11 小时前
为什么同一个引脚不能同时做按键和串口
stm32·单片机·嵌入式硬件
崇山峻岭之间11 小时前
单片机基本定时器实验
单片机·嵌入式硬件
DS小龙哥11 小时前
基于ESP32设计的智能养蜂监测系统
stm32·单片机·嵌入式硬件·物联网·华为云
夜月yeyue12 小时前
STM32 DMA 双缓冲采样
linux·stm32·单片机·嵌入式硬件·系统架构
西城微科方案开发12 小时前
SIC8P370D2L-PLP16 8位OTP单片机 低功耗多功能MCU详解
单片机·嵌入式硬件