C51单片机 通过定时器模拟输出多路PWM

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wuyuzun/article/details/86557719

前言

  1. 本博文基于STC89C52RC和keil5 C51开发;
  2. 如有不做之处还请多多指教;

需要用到的东西

  1. 利用定时器0完成(定时器1也一样);
  2. 利用P1.0~P1.3完成4路PWM的输出(不同的占空比);

代码如下:

#include <STC89C5xRC.H>

#define ENABLE 1
#define DISENABLE 0

typedef unsigned int uint16;
typedef unsigned char uchar8;

sbit  P1_0 = P1^0;
sbit  P1_1 = P1^1;
sbit  P1_2 = P1^2;
sbit  P1_3 = P1^3;

/*
占空比的时间计算:
占空比 = High_Level_Time_P1_x/Cycle;
*/
uchar8 Cycle = 10;					//设置PWM周期:10*定时器溢出周期(100us)= 1000us;
uchar8 High_Level_Time_P1_0 = 0;    //这里四个全局变量控制每个周期内高电平时间;
uchar8 High_Level_Time_P1_1 = 0;
uchar8 High_Level_Time_P1_2 = 0;
uchar8 High_Level_Time_P1_3 = 0;   

void Time0_Init(void);

void main()
{
  Time0_Init();
  while(1);
}

/*
定时器的配置:
1.假设单片机晶振频率为12MHz;则定时器累加周期为1us;
2.定时器初值为:9C(十进制的156,即定时器的溢出周期为100us);
3.定时器0设置成8位自动重装载工作方式;
*/

void Time0_Init(void)
{
  	TMOD = 0x02;
	TH0 = 0x9C;
	TL0 = 0x9C;
	
	TR0 = ENABLE;	
	ET0 = ENABLE;
	
	EA = ENABLE;
}

void Timer0_IT() interrupt 1
{ 
	static uchar8 count_P1_0,count_P1_1,\
				  count_P1_2,count_P1_3; 
	
	if(count_P1_0==High_Level_Time_P1_0)
	{
		P1_0 = 0;
	}
	count_P1_0++;
	if(count_P1_0==Cycle)
	{
		P1_0= 1;
		count_P1_0 = 0;
	}
	
	if(count_P1_1==High_Level_Time_P1_1)
	{
		P1_1 = 1;
	}
	count_P1_1++;
	if(count_P1_1==Cycle)
	{
		P1_1= 0;
		count_P1_1 = 1;
	}
	
	if(count_P1_2==High_Level_Time_P1_2)
	{
		count_P1_2=0;
	}
	count_P1_2++;
	if(count_P1_2==Cycle)
	{
		P1_2 = 0;
		count_P1_2=1;
	}
	
	if(count_P1_3==High_Level_Time_P1_3)
	{
		count_P1_3 = 0;
	}
	count_P1_3++;
	if(count_P1_3==Cycle)
	{
		P1_3 = 1;
		count_P1_3= 1;
	}
}



猜你喜欢

转载自blog.csdn.net/wuyuzun/article/details/86557719