600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > 智能小车之PWM脉冲控制小车调速

智能小车之PWM脉冲控制小车调速

时间:2023-11-18 23:26:45

相关推荐

智能小车之PWM脉冲控制小车调速

目录

一、PWM脉冲控制小车调速

二、代码实现

一、PWM脉冲控制小车调速

原理:全速前进是LeftCon1A = 0;LeftCon1B= 1;完全停止是LeftCon1A = 0;LeftCon1B= 0;

那么单位时间内比如:20ms,有15ms是全速前进,5ms是完全停止,速度就会比5ms全速前进,15ms完全停止获得的功率多,相应的速度更快

二、代码实现

main.c

#include "motor.h"#include "delay.h"#include "uart.h"#include "time.h"extern char speed; //此变量/函数是在别处定义的,要在此处引用void main(){Time0Init(); //定时器初始化UartInit(); //串口初始化while(1){speed = 10; //10份单位时间全速运行,30份停止,所以慢,20ms是40份的500usDelay1000ms();Delay1000ms();speed = 20;Delay1000ms();Delay1000ms();speed = 40;Delay1000ms();Delay1000ms();}}

motor.c

#include "reg52.h"sbit RightCon1A = P3^2;sbit RightCon1B = P3^3;sbit LeftCon1A = P3^4;sbit LeftCon1B = P3^5;void goForWard(){ //小车前转LeftCon1A = 1;LeftCon1B = 0;RightCon1A = 1;RightCon1B = 0; }void goBack(){ //小车后转LeftCon1A = 0;LeftCon1B = 1;RightCon1A = 0;RightCon1B = 1; }void goLeft(){ //小车左转LeftCon1A = 0;LeftCon1B = 0;RightCon1A = 1;RightCon1B = 0; }void goRight(){ //小车右转LeftCon1A = 1;LeftCon1B = 0;RightCon1A = 0;RightCon1B = 0; }void stop(){ //小车停止LeftCon1A = 0;LeftCon1B = 0;RightCon1A = 0;RightCon1B = 0; }

motor.h

void goForWard();void goBack();void goLeft();void goRight();void stop();

delay.c

#include "intrins.h"void Delay1000ms()//@11.0592MHz{unsigned char i, j, k;_nop_();i = 8;j = 1;k = 243;do{do{while (--k);} while (--j);} while (--i);}void Delay10ms()//@11.0592MHz{unsigned char i, j;i = 18;j = 235;do{while (--j);} while (--i);}

delay.h

void Delay1000ms();void Delay10ms();

uart.c------串口初始化文件

#include "reg52.h"#include "motor.h"#include "string.h"#include "delay.h"#define SIZE 12sfr AUXR = 0x8E;char cmd;char buffer[SIZE];void UartInit(void)//9600bps@11.0592MHz{AUXR = 0x01; //降低时钟对外界的辐射SCON = 0x50; //串行口寄存器工作模式选择方式1,RNE=1,为串行允许接收状态TMOD &= 0x0F; //定时器1工作方式位8位自动重装TMOD |= 0x20;TH1 = 0xFD; TL1 = 0xFD; //9600波特率的初值TR1 = 1;//启动定时器EA = 1; //总中断寄存器,开启总中断ES = 1; //开启串口中断}

uart.h

void UartInit(void);

time.c ------定时器初始化及定时器开启中断文件

#include "motor.h"#include "reg52.h"char speed;char cnt = 0;void Time0Init(){//1、配置定时器0工作模式位16位计时TMOD = 0x01;//2、给定时器一个初值,每个周期都等于0.5msTL0 = 0x33;TH0 = 0xFE;//3、定时器开始计时TR0 = 1;TF0 = 0;//4、打开中断定时器ET0 = 1;//5、设置总中断定时器EA = 1;}void Time0Handler() interrupt 1 //定时器0的中断号为 interrupt 1{cnt ++; //统计爆表的次数//给定时器重新定义初值,每个周期都等于0.5msTL0 = 0x33;TH0 = 0xFE;//控制PWM波形if(cnt < speed){//前进goForWard();}else{//停止stop();}if(cnt == 40){ //要爆表40次,经过了20mscnt = 0;//当100次表示1s,重新让cnt从0开始,计算下一次的1s}}

time.h

void Time0Init();

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。