简易PWN 呼吸灯程序
#include <reg51.h>
/*****************************************
连续呼吸灯程序:
主要用到定时器的周期改变占空比
这里用到定时器0和定时器1,脉冲
数组在定时器1中定义。定时器0输
出pwn波,定时器1根据脉冲数组输
出不同脉冲改变定时器0的初值从
而达到呼吸灯效果。
*****************************************/
#define uint unsigned int
#define uchar unsigned char
sbit Pwnout=P0^1;
uchar HIGHRH = 0;//用于定时器0使用
uchar HIGHRL= 0;
uchar LOWRH = 0;
uchar LOWRL = 0;
uchar T1RL = 0; //定时器一
uchar T1RH = 0;
unsigned long periodkb = 0;
void Openpwn(uchar fr,uchar kb) //开pwn开口
{
uchar high ,low;
periodkb = 11059200/12/fr;//为pwn一个周期需要的计数 11059200/12 为一个机器周期的计数
high = (periodkb*kb)/100;//当pwn为1 占空比为kb时的计数
low = periodkb-high; //当pwn为0,占空比为kb时的计数
high = 65536-high+12;//+12为了补充损耗
low = 65536-low+12;//
HIGHRH = (unsigned char)(high >> 8);// 当pwn为1时的高8位 和 低8位分离
HIGHRL = (unsigned char)high ;
LOWRH = (unsigned char)(low >> 8);// 当pwn为0时的高8位 和 低8为分离
LOWRL = (unsigned char)low;
TMOD &=0XF0;
TMOD |=0X01;//TMOD开定时器一
TH0 = HIGHRH; //
TL0 = HIGHRL;
ET0 = 1;
TR0 = 1;
Pwnout = 1;
}
void Pwntime (uint ms)
{
uchar tmp = 0;
tmp = 11059200/12; //定时器计数频率
tmp = (tmp*ms)/100;// 计算所需要的计数值
tmp = 65536-tmp+12;//前面是计算定时器重载值 +12为了补充中断延时的损耗
T1RH = (unsigned char)(tmp >> 8);// 当pwn为1时的高8位 和 低8位分离
T1RL = (unsigned char)tmp ;
TMOD &=0XF0;
TMOD |=0X01;//TMOD开定时器一
TH1 = T1RH; //
TL1 = T1RL;
ET1 = 1; //使能T1中断
TR1 = 1; //启动T1
}
void Adjustpwn(uint ms)
{
uchar high = 0,low = 0;
high = (periodkb*ms)/100;
low = periodkb - high;
high = 65536 - high + 12;
low = 65536 - low + 12;
HIGHRH = (unsigned char)(high >> 8);// 当pwn为1时的高8位 和 低8位分离
HIGHRL = (unsigned char)high ;
LOWRH = (unsigned char)(low >> 8);// 当pwn为0时的高8位 和 低8为分离
LOWRL = (unsigned char)low;
}
main() //用于设置定时器和中断方式
{
EA = 1;//开总中断
Openpwn(100,10);//打开pwn
Pwntime(50);//隔50ms 进入一次中断 改变占空比
while (1);
}
void Tnterrupttime0() interrupt 1
{
if (Pwnout = 1) //当前为高电平时,装载低电平并输出低电平
{
TH0 = LOWRH;
TL0 = LOWRL;
Pwnout = 0;
}
else //当前为高电平时,装载高电平并输出高电平
{
TH0 = HIGHRH;
TL0 = HIGHRL;
Pwnout = 0;
}
}
void Interrupttime1() interrupt 3
{
static bit dir = 0; //呼吸灯亮灭,0为逐渐亮,1为逐渐灭
static uchar inde = 0; // 占空比数组计数
uchar code table[13] = {5,8,15,25,35,45,55,65,75,85,95,98,99}; //占空比数的变化
TH1 = T1RH;//初始化赋值
TL1 = T1RL;
Adjustpwn(table[inde]);
if(dir == 0)
{
inde++;
if(inde >= 12)
dir = 1;
}
else
{
inde --;
if(inde == 0)
dir =0;
}
}
编译出现如图问题 试过编译流水灯程序就没问题 有hex文件 网上说是没有** 但是我**过两次还是不行 求助
|