STC12C5A60S2单片机怎么才能输出占空比可调的PWM?
STC12C5A60S2输出PWM后怎么在程序中调节占空比?例如中断中怎么赋值能改变输出PWM的占空比?
以前用过STC其它型号的做过PWM,也可以调节占空比,你仔细看手册,里面很详细的。
规格书上有对应的寄存器,一个是设置Pwm的频率,一个是设置占空比,你要调频的话改变设置占空比的寄存器就可以了
手册中只有输出固定占空比的例程,我改调节占空比的参数结果占空比还是没有变化
#include "reg51.h"
#include "intrins.h"
#define FOSC 18432000L
typedef unsigned char BYTE;
typedef unsigned int WORD;
/*Declare SFR associated with the PCA */
sfr CCON = 0xD8; //PCA control register
sbit CCF0 = CCON^0; //PCA module-0 interrupt flag
sbit CCF1 = CCON^1; //PCA module-1 interrupt flag
sbit CR = CCON^6; //PCA timer run control bit
sbit CF = CCON^7; //PCA timer overflow flag
sfr CMOD = 0xD9; //PCA mode register
sfr CL = 0xE9; //PCA base timer LOW
sfr CH = 0xF9; //PCA base timer HIGH
sfr CCAPM0 = 0xDA; //PCA module-0 mode register
sfr CCAP0L = 0xEA; //PCA module-0 capture register LOW
sfr CCAP0H = 0xFA; //PCA module-0 capture register HIGH
sfr CCAPM1 = 0xDB; //PCA module-1 mode register
sfr CCAP1L = 0xEB; //PCA module-1 capture register LOW
sfr CCAP1H = 0xFB; //PCA module-1 capture register HIGH
sfr PCAPWM0 = 0xf2;
sfr PCAPWM1 = 0xf3;
sbit k=P1^0;
BYTE a=0;
void main()
{
CCON = 0; //Initial PCA control register
//PCA timer stop running
//Clear CF flag
//Clear all module interrupt flag
CL = 0; //Reset PCA base timer
CH = 0;
CMOD = 0x02; //Set PCA timer clock source as Fosc/2
//Disable PCA timer overflow interrupt
CCAP0H = CCAP0L =a; //PWM0 port output 50% duty cycle square wave
CCAPM0 = 0x42; //PCA module-0 work in 8-bit PWM mode
PCAPWM0 = 0x03; //and no PCA interrupt
CCAP1H = CCAP1L = 255; //PWM1 port output 0% duty cycle square wave
PCAPWM1 = 0x03;
CCAPM1 = 0x42; //PCA module-1 work in 8-bit PWM mode and no PCA interrupt
CR = 1; //PCA timer start run
EA=1;
EX0=1;
while(1);
}
void inter0() interrupt 0
{
a=200;
}
这是把手册上例程修改过的程序,通过中断修改a的值从而使100%的占空比变为(256-200)/256的占空比,但是达不到预期的要求,求大神指点。
计时器控制高低电平随便来啊
通过调整CCAP0L CCCAP0H的值就可以调整 P1^3口的脉冲占空比#include<stc12c5a60s2.h>
sbit k8=P1^7;
sbit k7=P1^6;
unsigned char a,b;
unsigned char z=255,y=0;
void delay1ms(void) //误差 0us
{
unsigned char a,b,c;
for(c=1;c>0;c--)
for(b=222;b>0;b--)
for(a=12;a>0;a--);
}
void delay(unsigned int n)
{
unsigned int i;
for(i=0;i<n;i++)
delay1ms();
}
void pwm_init()
{
CCON=0; // 关闭中断,停止计数器
CL=0; // 清0
CH=0; // 清0
CMOD=0X02; //系统时钟的/2;
CCAP0H=CCAP0L=0X00; //赋值128
CCAPM0=0X42; //工作模式设定
CCAP1H=CCAP1L=0X00;
CCAPM1=0X42;
CR=1;
}
void pwm_set(unsigned char x,unsigned char y)
{
CCAP0H=x;
CCAP0L=x;
CCAP1H=y;
CCAP1L=y;
}
void main()
{
pwm_init();
while(1)
{
if(k8==0)
{
delay(10);
if(k8==0)
{
while(!k8);
a=1;
z--;
if(z==0) z=256;
}
}
if(k7==0)
{
delay(10);
if(k7==0)
{
while(!k7);
b=1;
y++;
if(y==256) y=0;
}
}
if(a==1)
{
a=0;
pwm_set(z,0);
}
if(b==1)
{
b=0;
pwm_set(0,y);
}
}
}
我这个是通过按键K8 K7改变 1.3 1.4的占空比,实测OK
谢谢。我试试程序
CCAP0H=CCAP0L这两个是什么关系?
去掉PCAPWM0 = 0x30;