#include <reg51.h> //program is written based on KEIL-C51, introducing 8051 header files Sbit p10=p1^0; Sbit p11=p1^1;unsigned intScale//Duty ratio control variablevoidMainvoid) {unsigned intN//delay cycle variableTmod=0x02;//Timer 0, operating mode 2 (0000 0010), 8-bit timingth0=0x06;//Timing 250US (12M oscillator)tl0=0x06;//Preset valuetr0=1;//Start timer 0et0=1;//Start Timer 0 InterruptEa=1;//Open Total Interrupt while(1) { for(n=0;n<50000; n++);//delay for some timescale++;//Duty ratio control variable plus one if(scale==Ten) scale=0;//To Achieve loop effect}} TIMER0 () interrupt1 //Timer 0 Interrupt Program{Static unsigned inttt;//tt is used to save the current time in a clock cycle positiontt++;//Interrupt every time, that is, the value of each 250US,TT is added from 1 if(tt==Ten)//Interrupt 10 timing 2.5ms,{tt=0;//Make tt=0, start a new cycle, achieve the effect of the cyclep10=0;//Illuminated LED}if(SCALE>=TT)//If the duty ratio is the same as the number of interrupts, the output high levelp10=1;//Off LED lights / * The previous procedure is to set the duty cycle to 10 levels, the time to maintain high on the scale=1 is 1/10 PWM cycles (here is 2.5ms), because the SCALE<=TT time period is low-level lit LED lights, scale>=tt time is Turn off the LED lamp, by changing the duration of the high and low levels in a cycle can be controlled by the brightness of the LED lamp or the speed of the motor, this is how the PWM work * *}
PWM principle:
Reference article: Principle and control procedure of PWM in monolithic microcomputer
A slight modification of the program changes the speed control of the motor, and the proteus8.4 simulation is as follows:
51 Monolithic Microcomputer PWM program detailed