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.5ms
	TH0 = 0xFE;									
	ET0 = 1;				//打开定时器0中断			
	EA = 1;					//打开总中断EA
	TR0 = 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次,经过20ms
			cnt = 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.5ms
		Delay1000ms();
		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.5ms
	TH0 = 0xFE;									
	ET0 = 1;				//打开定时器0中断			
	EA = 1;					//打开总中断EA
	TR0 = 1;		    //开始计时
	TF0 = 0;
}

//定时器1
void Time1Init()
{
	TMOD &= 0x0F;		//配置定时器1工作模式位16位时
	TMOD |= 0x1 << 4;
	TL1 = 0x33;		  //给初值,定一个0.5ms
	TH1 = 0xFE;									
	ET1 = 1;				//打开定时器1中断			
	EA = 1;					//打开总中断EA
	TR1 = 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次,经过20ms
			cntLeft = 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次,经过20ms
			cntRight = 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.5ms
		speedRight = 40;
		Delay1000ms();
		Delay1000ms();

		speedLeft = 40;
		speedRight = 10;
		Delay1000ms();
		Delay1000ms();
	}
}

你可能感兴趣的:(STC51,单片机,嵌入式硬件,stm32,c语言,51单片机)