求单片机通过定时器产生PWM的C语言,PWM可以变化的,谢谢~

如题所述

#include<reg51.h>   // 
sbit P1_0 = P1^0;   // 8路PWM输出
sbit P1_1 = P1^1;
sbit P1_2 = P1^2;
sbit P1_3 = P1^3;
sbit P1_4 = P1^4;
sbit P1_5 = P1^5;
sbit P1_6 = P1^6;
sbit P1_7 = P1^7;
unsigned char PWM0 = 1; // 占空比调整
unsigned char PWM1 = 3;     
unsigned char PWM2 = 5;
unsigned char PWM3 = 7;
unsigned char PWM4 = 9;     
unsigned char PWM5 = 11;
unsigned char PWM6 = 13;     
unsigned char PWM7 = 15;
unsigned char counter = 0;  // 计数的
unsigned char tt1;      // 标志位
void main()
{
 TMOD=0x02;
 TH0=256-250;      // 定时时间  可以修改
 TL0=256-250; 
 EA=1;
 ET0=1;
 TR0=1;
 while(1)
 {                          // 开关调整 PWM  占空比
 if(tt1==250)
   {
   tt1=0;
   PWM0++;PWM1++;PWM2++;PWM3++;
   PWM4++;PWM5++;PWM6++;PWM7++;
   if(PWM0==17) PWM0=0;
   if(PWM1==17) PWM1=0;
   if(PWM2==17) PWM2=0;
   if(PWM3==17) PWM3=0;
   if(PWM4==17) PWM4=0;
   if(PWM5==17) PWM5=0;
   if(PWM6==17) PWM6=0;
   if(PWM7==17) PWM7=0;
    }
  }
}
void Timer0(void) interrupt 1 // 定时器0   PWM 控制
{                           
 // TH0=(65536-2000)/256;       // 定时时间  可以修改
 // TL0=(65536-2000)%256;
  counter++;
  tt1++;
  if(counter >= 16) counter = 0;   // PWM  16级  可以修改
  if(counter >= PWM0) P1_0 = 0; else P1_0 = 1;
  if(counter >= PWM1) P1_1 = 0; else P1_1 = 1;
  if(counter >= PWM2) P1_2 = 0; else P1_2 = 1;
  if(counter >= PWM3) P1_3 = 0; else P1_3 = 1;
  if(counter >= PWM4) P1_4 = 0; else P1_4 = 1;
  if(counter >= PWM5) P1_5 = 0; else P1_5 = 1;
  if(counter >= PWM6) P1_6 = 0; else P1_6 = 1;
  if(counter >= PWM7) P1_7 = 0; else P1_7 = 1;
  }

追问

你好,我的单片机是STC90C516RD+ 然后我要通过单片机输出不同频率的低电平,单片机和uln2003连接的,然后uln2003输出高电平来控制和它相连接的电磁继电器,让继电器得电,请问这个程序使用吗。能不能再改的简单点,谢谢~

追答

这是 8 路 PWM 输出,如果只要一路,删除 7 路 简单多了。
自己试试。

温馨提示:答案为网友推荐,仅供参考