本帖最后由 哆啦dd 于 2022-11-11 09:19 编辑
使用定时器0工作方式1,定时100us,每10ms改变一个占空比,呼吸有效果,但是呼吸几次后会保持长亮或者熄灭,找不到原因,有没有大神解惑。
以下为源码:
#include <reg52.h>
#define uint unsigned int
#define uchar unsigned char
typedef bit bool;
#define true 1
#define false 0
sbit LED1 = P1^0;
uint code BreathLEDArray[] = {
0,1,2,3,4,5,6,7,7,7,
7,8,10,12,13,13,13,15,15,16,
17,22,22,25,25,25,30,33,38,40,
40,45,51,55,67,70,72,73,75,77,
80,83,90,95,96,97,98,99,99,100};
bool BreathLEDFlag;
bool BreathLEDPhase; //true:½¥ÁÁ£»false:½¥Ãð
uchar BreathLEDIndex;
uchar BreathSystickCount;
uchar Flag_10ms;
void Init();
void BreathLEDHandle();
void main()
{
Init();
while(1)
{
BreathLEDHandle();
}
}
void Init()
{
TMOD = 0x01;
TH0 = (65536-92) / 256;
TL0 = (65536-92) % 256;
EA = 1;
ET0 = 1;
TR0 = 1;
BreathLEDFlag = true;
BreathLEDPhase = false;
BreathLEDIndex = 0;
BreathSystickCount = 0;
Flag_10ms = 0;
}
void BreathLEDHandle()
{
if(!BreathLEDFlag)
{
return;
}
if(Flag_10ms % 10 == 0)
{
if((BreathLEDIndex > 0) && BreathLEDPhase) //½¥Ãð
{
BreathLEDIndex--;
if(BreathLEDIndex <= 0)
{
BreathLEDIndex = 0;
BreathLEDPhase = false;
}
} else if ((BreathLEDIndex < 49) && !BreathLEDPhase) { //½¥ÁÁ
BreathLEDIndex++;
if(BreathLEDIndex >= 49)
{
BreathLEDIndex = 49;
BreathLEDPhase = true;
}
}
}
}
void T0_Interrupt() interrupt 1
{
TH0 = (65536-92) / 256;
TL0 = (65536-92) % 256;
if(BreathLEDFlag)
{
BreathSystickCount++;
if(BreathSystickCount >= BreathLEDArray[BreathLEDIndex])
{
LED1 = 0;
} else {
LED1 = 1;
}
if(BreathSystickCount >= 100)
{
BreathSystickCount = 0;
Flag_10ms += 10;
if(Flag_10ms >= 65535)
{
Flag_10ms = 0;
}
}
}
}
|