在写代码的时候经常用到电机,有时候电机需要控制速度,就会显得手足无措,这里我编写了一个,通过控制占空比的程序来控制电机
pwm.c
#include <stc15.h>
// 什么单片机型号就把头文件换成什么
sbit Motor_Enable = P1^6; // pwm
sbit Motor_Dir_A = P1^4; // A
sbit Motor_Dir_B = P0^6; // B
unsigned int pwm_duty_cycle = 0; // (0-1000)
unsigned int pwm_period = 1000; // PWM
void Timer_Init(void)
{
//这是定时器,为了防止定时器干扰,用了一
//换成自己的定时器
//C51的 在前面加上 sfr AUXR=0x8e;
AUXR |= 0x40;
TMOD &= 0x0F;
TL1 = 0x48;
TH1 = 0xF4;
TF1 = 0;
TR1 = 1;
ET1 = 1;
}
void Timer_ISR(void) interrupt 3
{
static unsigned int pwm_count = 0;
TL1 = 0x1C;
TH1 = 0xF3;
pwm_count++;
if (pwm_count < pwm_duty_cycle)
{
Motor_Enable = 1;
}
else
{
Motor_Enable = 0;
}
if (pwm_count >= pwm_period)
{
pwm_count = 0;
}
}
void Set_Motor_Speed(unsigned int speed)
{
if (speed > 1000) speed = 1000;
pwm_duty_cycle = speed;
}
void Set_Motor_Dir(bit direction)
{
if (direction)
{
Motor_Dir_A = 1;
Motor_Dir_B = 0;
}
else
{
Motor_Dir_A = 0;
Motor_Dir_B = 1;
}
}
void Motor_Stop()
{
Motor_Dir_A = 0;
Motor_Dir_B = 0;
Set_Motor_Speed(0);
}
void PWM_INIT()
{
Timer_Init();
Motor_Stop();
}
pwm.h
#ifndef _PWM_H__
#define __PWM_H__
#include <stc15.h>
void PWM_INIT(void);//电机初始化
void Set_Motor_Speed(unsigned int speed);//电机控制速度 0-1000
void Set_Motor_Dir(bit direction);//电机控制方向1是正传,0是反转
void Motor_Stop();//电机停止
#endif
接下来延时怎么使用
main.c
#include<STC15.h>
void main()
{
/*STC15端口需要声明此处省略*/
PWM_INIT();//电机初始化
while(1){
Set_Motor_Dir(1);//设置电机方向
Set_Motor_Speed(500)//设置电机速度
}
}