基于51单片机的PWM+L293d控制直流电机程序
2020-03-02 来源:51hei
左侧开关减速,右侧加速。l293d芯片驱动直流电机
单片机源代码:
#include #define Tpwm 0xfc18//PWM周期对应的计数值1ms,基于12MHz晶振 unsigned int duty[]={0,/*0*/ 0xff9c/*100us*/,0xff38/*200us*/,0xfed4/*300us*/, 0xfe70/*400us*/,0xfe0c/*500us*/,0xfda8/*600us*/, 0xfd44/*700us*/,0xfce0/*800us*/,0xfc7c/*900us*/, 0xfc18/*1000us*/};//PWM高电平时间 unsigned char i=0; sbit P32 = P3^2; sbit P33 = P3^3; sbit PWMOUT = P2^0; sbit PWMIN1 = P2^1; sbit PWMIN2 = P2^2; bit flag = 1;//PWM输出电平状态,1为输出高电平时间,0为输出低电平时间 void delay10ms(int n); void main(void) { PWMOUT = 0;//初始化L293D ,停止电机 PWMIN1 = 0; PWMIN2 = 1; EA = 1; //开总中断 IT0 = 1; //中断方式为跳变 IT1 = 1; EX0 = 1; //打开外部中断0 EX1 = 1; //打开外部中断1 ET0 = 1; //开定时器0中断允许 TMOD = 0x01; //设置定时方式 while(1) //等待中断 { /*在此可以实现其它任务*/ } } //10ms延时函数 void delay10ms(int n) { int i=0,j; while(n--) { for(i=0;i<10;i++) { for(j = 0; j < 125; j++); } } } void keySpeeddownISR() interrupt 0 //按键中断服务程序 { EA = 0; //关中断 delay10ms(2); //延时消抖 if (!P32) //确认按键按下,滤除键盘抖动干扰 {//减少PWM高电平时间 if(i>0) i--; if((TR0=1) && (i == 0)) { TR0 = 0; PWMOUT = 0; } } EA = 1; } void keySpeedupISR() interrupt 2 //按键中断服务程序 { EA = 0; //关中断 delay10ms(2); //延时消抖 if (!P33) //确认按键按下,滤除键盘抖动干扰 {//增加PWM高电平时间 if(i<=10) i++; if((TR0 == 0) && (i > 0)) {//启动PWM,电机顺时针旋转 PWMIN1 = 0; PWMIN2 = 1; PWMOUT = 1; TH0 = duty[i]>>8; TL0 = duty[i]&0xff; TR0 = 1; flag = 1; } } EA = 1; } void T0ISR() interrupt 1 //定时器0中断服务程序 { EA = 0; //关中断 if(flag) {//高电平时间结束,输出低电平补齐PWM周期 PWMOUT = 0; TH0 = (65535-(duty[i]-Tpwm))>>8; TL0 = (65535-(duty[i]-Tpwm))&0xff; flag = 0; }else {//周期结束 PWMOUT = 1; TH0 = duty[i]>>8; TL0 = duty[i]&0xff; flag = 1; } EA = 1; }