current position:Home>PWM control car speed

PWM control car speed

2022-09-23 03:08:34what's the matter

//The initial car to 20%Duty ratio speed running,K1 Key can accelerate,K2 Key can slow down.最大可以 100%Duty ratio speed.

#include "reg52.h"

typedef unsigned char u8;
typedef unsigned int u16;


//定义电机控制管脚
sbit MOTOA=P1^0;
sbit MOTOB=P1^1; //右侧电机
sbit MOTOC=P1^2;
sbit MOTOD=P1^3; //左侧电机

//定义按键管脚
sbit k1=P1^4;
sbit k2=P1^5;


u16 time_cnt=0; //定时器中断计数次数
u16 freq=100; //PWM 输出频率 100HZ
u8 duty_cycle=20; //占空比 20%


//延时函数 10*us(us)

void delay_10us(u16 us)

{
    
    while(us--);
}



//ms 延时函数 ms

void delay_ms(u16 ms)

{
    
    u16 i,j;
    for(i=ms; i>0; i--)
        for(j=110; j>0; j--);
}
//定时器 0 初始化函数


//定时时间:0.1ms

void Time0_Init()

{
    
    TMOD|=0x01;
    TH0 = 0XFF;
    TL0 = 0X9C; //定时 0.1ms TR0 = 1;
    ET0 = 1;
    EA = 1;
}

void Car_ForwardRun()//前进
{
    
    MOTOA=1;
    MOTOB=0;
    MOTOC=1;
    MOTOD=0;
}

void Car_StopRun()//停止
{
    
    MOTOA=0;
    MOTOB=0;
    MOTOC=0;
    MOTOD=0;
}



//主函数 

void main()
{
    
    Time0_Init();
    
    while(1)
    {
    
        if(k1==0) //加速
        {
    
            delay_10us(1000);
            if(k1==0)
            {
    
                if(duty_cycle<100)
                    duty_cycle+=10;
            }
            while(!k1);
        }
        else if(k2==0) //减速
        {
    
            delay_10us(1000);
            if(k2==0)
            {
    
                if(duty_cycle>0) duty_cycle-=10;
            }
            while(!k2);
        }
    }
}
//定时器 0 中断函数



void Time0_Isr() interrupt 1
{
    
    TR0 = 0; //关闭定时器 0
    TH0 = 0XFF;
    TL0 = 0X9C; //定时 0.1ms
    time_cnt++;    

    if(time_cnt>=freq)
        time_cnt=0;

    else if(time_cnt<=duty_cycle)
    {
    
        Car_ForwardRun();
    }

    else
    {
    
        Car_StopRun();
    }
    TR0 = 1;//开启定时器 0
}

copyright notice
author[what's the matter],Please bring the original link to reprint, thank you.
https://caren.inotgo.com/2022/266/202209230257291873.html

Random recommended