单元训练09:定时器实现秒闪功能

蓝桥杯 小蜜蜂  单元训练09:定时器实现秒闪功能

#include "stc15f2k60s2.h"

#define LED(x)                 \
    {                          \
        P0 = x;                \
        P2 = P2 & 0x1f | 0x80; \
        P2 &= 0x1f;            \
    }

#define L1 0xFE; // 定义L1
#define L8 0x7F; // 定义L8

typedef unsigned char uint8_t;

uint8_t timerCounterHalfSec = 0; // 0.5s,500ms计时
uint8_t EnableHalfSec = 0;       // 0.5s状态达到

uint8_t timerCounterFiveSec = 0; // 5s,5000ms计时
uint8_t EnableFiveSec = 0;       // 5s状态达到

uint8_t StatusHalfSec; // 用于L1切换状态
uint8_t StatusFiveSec; // 用于L8切换状态

void Timer0_Init(void) // 5毫秒@12MHz
{
    AUXR |= 0x80; // 定时器时钟1T模式
    TMOD &= 0xF0; // 设置定时器模式
    TL0 = 0xA0;   // 设置定时初始值
    TH0 = 0x15;   // 设置定时初始值
    TF0 = 0;      // 清除TF0标志
    TR0 = 1;      // 定时器0开始计时
    ET0 = 1;      // 使能定时器0中断
    EA = 1;
}

void blinkL1()
{
    switch (StatusHalfSec)
    {
    case 0:
        LED(P0 & L1);      // 点亮L1
        if (EnableHalfSec) // 0.5s延时
        {
            StatusHalfSec = 1;
            EnableHalfSec = 0;
        }
        break;
    case 1:
        LED(P0 | 0x01);    // 熄灭L1
        if (EnableHalfSec) // 0.5秒延时
        {
            StatusHalfSec = 0;
            EnableHalfSec = 0;
        }
        break;
    default:
        StatusHalfSec = 0;
        break;
    }
}
void blinkL8()
{
    switch (StatusFiveSec) // L8状态切换处理
    {
    case 0:
        LED(P0 & L8);      // 点亮L8
        if (EnableFiveSec) // 5秒延时
        {
            StatusFiveSec = 1;
            EnableFiveSec = 0;
        }
        break;
    case 1:
        LED(P0 | 0x80);    // 熄灭L8
        if (EnableFiveSec) // 5秒延时
        {
            StatusFiveSec = 0;
            EnableFiveSec = 0;
        }
        break;
    default:
        StatusFiveSec = 0;
        break;
    }
}
void main()
{
    LED(0xFF);     // 初始化,全灭
    Timer0_Init(); // 初始化定时器
    while (1)
    {
        blinkL1();
        blinkL8();
    }
}

void Timer0_Isr(void) interrupt 1
{
    if (++timerCounterHalfSec == 100) // 500ms,500ms/5ms = 100
    {
        EnableHalfSec = 1;
        timerCounterHalfSec = 0;
        if (++timerCounterFiveSec == 10) // 5s,5000ms,5000ms/500ms = 10
        {
            EnableFiveSec = 1;
            timerCounterFiveSec = 0;
        }
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zfdc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值