本文主要是介绍C51--小车——PWM调速,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
如何进行小车PWM调速:
原理:
全速前进:LeftCon1A = 0;LeftCon1B = 1;
完全停止:LeftCon1A = 0;LeftCon1B = 0;
单位时间内,例如20ms,有15ms是全速,5ms是停止,速度就会比15ms是停止,5ms是全速的功率多,速度快。
要用到PWM的舵机控制代码。
设置定时器:
#include "motor.h"
#include "reg52.h"char speed;
char cnt = 0;void Time0Init()
{TMOD = 0x01; //配置定时器0工作模式位16位时TL0 = 0x33; //给初值,定一个0.5msTH0 = 0xFE; ET0 = 1; //打开定时器0中断 EA = 1; //打开总中断EATR0 = 1; //开始计时TF0 = 0;
}void Time0Handler() interrupt 1
{cnt++; //统计爆表的次数TL0 = 0x33; //重新给初值TH0 = 0xFE;if(cnt < speed){ //PWM波形控制go_Forward(); //前进}else{go_Storp(); //停止}if(cnt == 40){ //爆表40次,经过20mscnt = 0; //重新计算cnt}
}
主函数:
#include "motor.h"
#include "Delay.h"
#include "uart.h"
#include "time.h"extern char speed;void main()
{Time0Init(); //定时器0初始化UartInit(); //串口初始化while(1){speed = 10; //10份(5ms)全速,30份停止。20ms是40份的0.5msDelay1000ms();Delay1000ms();speed = 20;Delay1000ms();Delay1000ms();speed = 40;Delay1000ms();Delay1000ms();}
}
PWM调速实现小车转向:
原理:
左轮定时器0,右轮定时器1;
左转:右轮速度大于左轮
右转:左轮速度大于右轮
重新封装函数:
//左前进
void go_ForwardLeft()
{LeftCon1A = 0;LeftCon1B = 1;
}//左停止
void go_StopLeft()
{LeftCon1A = 0;LeftCon1B = 0;
}//右前进
void go_ForwardRight()
{RightCon1A = 0;RightCon1B = 1;
}//右停止
void go_StopRight()
{RightCon1A = 0;RightCon1B = 0;
}
定时器0和1 :
#include "motor.h"
#include "reg52.h"char speedLeft;
char cntLeft = 0;char speedRight;
char cntRight = 0;//定时器0
void Time0Init()
{TMOD = 0x01; //配置定时器0工作模式位16位时TL0 = 0x33; //给初值,定一个0.5msTH0 = 0xFE; ET0 = 1; //打开定时器0中断 EA = 1; //打开总中断EATR0 = 1; //开始计时TF0 = 0;
}//定时器1
void Time1Init()
{TMOD &= 0x0F; //配置定时器1工作模式位16位时TMOD |= 0x1 << 4;TL1 = 0x33; //给初值,定一个0.5msTH1 = 0xFE; ET1 = 1; //打开定时器1中断 EA = 1; //打开总中断EATR1 = 1; //开始计时TF1 = 0;
}//定时器0的中断
void Time0Handler() interrupt 1
{cntLeft++; //统计爆表的次数TL0 = 0x33; //重新给初值TH0 = 0xFE;if(cntLeft < speedLeft){ //PWM波形控制go_ForwardLeft(); //左前进}else{go_StopLeft(); //左停止}if(cntLeft == 40){ //爆表40次,经过20mscntLeft = 0; //重新计算cnt}
}//定时器1的中断
void Time1Handler() interrupt 3
{cntRight++; //统计爆表的次数TL1 = 0x33; //重新给初值TH1 = 0xFE;if(cntRight < speedRight){ //PWM波形控制go_ForwardRight(); //右前进}else{go_StopRight(); //右停止}if(cntRight == 40){ //爆表40次,经过20mscntRight = 0; //重新计算cnt}
}
主函数:
#include "motor.h"
#include "Delay.h"
#include "uart.h"
#include "time.h"extern char speedLeft;
extern char speedRight;void main()
{Time0Init(); //定时器0初始化Time1Init(); //定时器1初始化UartInit(); //串口初始化while(1){speedLeft = 10; //10份(5ms)全速,30份停止。20ms是40份的0.5msspeedRight = 40;Delay1000ms();Delay1000ms();speedLeft = 40;speedRight = 10;Delay1000ms();Delay1000ms();}
}
这篇关于C51--小车——PWM调速的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!