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

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

cpp 复制代码
#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;
        }
    }
}
相关推荐
我爱我家diyer29 分钟前
使用STM32的HAL库开发GD32F303CGT6
stm32·单片机·嵌入式硬件
新能源BMS佬大2 小时前
【仿真到实战】STM32落地EKF算法实现锂电池SOC高精度估算(含硬件驱动与源码)
stm32·嵌入式硬件·算法·电池soc估计·bms电池管理系统·扩展卡尔曼滤波估计soc·野火开发板
点灯小铭2 小时前
基于单片机的井盖安全监测与报警上位机监测系统设计
单片机·嵌入式硬件·毕业设计·课程设计
Hello_Embed2 小时前
USB 虚拟串口源码改造与 FreeRTOS 适配
笔记·单片机·嵌入式·freertos·usb
无垠的广袤3 小时前
【CPKCOR-RA8D1】RUHMI 转换 AI 模型
人工智能·python·嵌入式硬件·开发板
望眼欲穿的程序猿4 小时前
SDCC+Ai8051U 中断点灯
stm32·单片机·嵌入式硬件
youcans_4 小时前
【动手学STM32G4】(15)三路互补带死区 PWM 输出
stm32·单片机·嵌入式硬件·pwm·死区
小慧10244 小时前
外部中断与回调函数
stm32·单片机·嵌入式硬件
XH华4 小时前
备战蓝桥杯,第三章:条件判断与循环
职场和发展·蓝桥杯
加斯顿工程师5 小时前
STM32F103C8T6驱动DS18B20温度传感器程序
stm32·单片机·嵌入式硬件