第4章 流水灯的实现
单片机电路图:
缓冲器、译码器电路图:
流水灯左移代码:
#include<reg52.h>
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
void main()
{
unsigned char cnt = 0;
unsigned int i=0;
ENLED = 0;
ADDR3 = 1;
ADDR2 = 1;
ADDR1 = 1;
ADDR0 = 0;
while(1)
{
P0 = ~(0x01 <<cnt);
for(i=0; i<30000; i++);
cnt++;
if(cnt>=8)
{
cnt = 0;
}
}
}
流水灯右移代码:
#include<reg52.h>
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
void main()
{
unsigned char cnt = 0;
unsigned int i=0;
ENLED = 0;
ADDR3 = 1;
ADDR2 = 1;
ADDR1 = 1;
ADDR0 = 0;
while(1)
{
P0 = ~(0x80 >>cnt);
for(i=0; i<30000; i++);
cnt++;
if(cnt>=8)
{
cnt = 0;
}
}
}
流水灯左移到头,然后右移,然后再左移,依次循环,代码如下:
#include <reg52.h>
sbit ADDR0 = P1^0;
sbit ADDR1 = P1^1;
sbit ADDR2 = P1^2;
sbit ADDR3 = P1^3;
sbit ENLED = P1^4;
void main()
{
unsigned int i = 0;
unsigned char dir = 0; //0为左移,1为右移
unsigned char shift = 0x01;
ENLED = 0;
ADDR3 = 1;
ADDR2 = 1;
ADDR1 = 1;
ADDR0 = 0;
while (1)
{
P0 = ~shift;
for (i=0; i<20000; i++);
if (dir == 0)
{
shift = shift << 1;
if (shift == 0x80)
{
dir = 1;
}
}
else
{
shift = shift >> 1;
if (shift == 0x01)
{
dir = 0;
}
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET10 - 预览版1新功能体验(一)