占空比=周期内高电平持续的时间/整个周期
直流电机驱动芯片选择L293D
电机正转:
#include "reg51.h"
sbit IN0=P2^0;
sbit IN1=P2^1;
//使能
sbit E=P2^2;
void deal(){
IN0=1;
IN1=0;
E=1;
}
void main(){
while(1){
deal();
}
}
延迟函数实现PWM调速:
#include "reg51.h"
sbit IN0=P2^0;
sbit IN1=P2^1;
//使能
sbit E=P2^2;
void delay(unsigned int n){
unsigned int i=0,j=0;
for(i=0;i<n;i++){
for(j=0;j<120;j++){
}
}
}
void deal(){
IN0=0;
IN1=1;
delay(50);
IN1=0;
delay(50);
E=1;
}
void main(){
while(1){
deal();
}
}
高电平1/4 低电平3/4;pwm 196*1/4
定时器实现PWM调速:
最大速度96
#include "reg51.h"
sbit IN0=P2^0;
sbit IN1=P2^1;
//使能
sbit E=P2^2;
void inittimer(){
TMOD=0x01;
TH0=(65535-10000)/256;
TL0=(65535-10000)%256;
ET0=1;
EA=1;
TR0=1;
IN1=0;
}
void deal(){
IN0=0;
E=1;
}
void timer_isr() interrupt 1{
TH0=(65535-10000)/256;
TL0=(65535-10000)%256;
//每10秒取反
IN1=~IN1;
}
void main(){
inittimer();
while(1){
deal();
}
}
最大速度43
#include "reg51.h"
sbit IN0=P2^0;
sbit IN1=P2^1;
//使能
sbit E=P2^2;
unsigned int value[]={2000,8000};
unsigned int count=0;
void inittimer(){
TMOD=0x01;
TH0=(65535-8000)/256;
TL0=(65535-8000)%256;
ET0=1;
EA=1;
TR0=1;
//8000低电平
IN1=0;
}
void deal(){
IN0=0;
E=1;
}
void timer_isr() interrupt 1{
TH0=(65535-value[count])/256;
TL0=(65535-value[count])%256;
IN1=~IN1;
count++;
if(count==2){
count=0;
}
}
void main(){
inittimer();
while(1){
deal();
}
}