3键控制电机,1键开关电机,2键加速,3键减速
[复制链接]
#include <pic.h> __CONFIG(0X1832);// 877A,硬件已经调试通过 #define keyO3 RB5 //接上拉做键盘输入 #define keyO4 RB4 // #define keyI2 RB2 //做输出与RB4\RB5\RB1组成4个按键,1键开关电机,2键加速,3键减速。CCP2输出接三极管驱动电机 #define keyI3 RB1 // #define LED RC4 // #define beep RD2 //按键的提示音 unsigned char keycon; unsigned char pwmcon; unsigned char pwmbuf; unsigned int fengcon; bit keybit; bit motor_onoff; bit beepbit; const unsigned char pwm_table[16]={15,30,45,60,75,90,105,120,135,150,165,180,195,210,225,240}; void init(void) { asm("CLRWDT"); OPTION=0x81; TRISB=0B00110000; TRISC=0B00000100; TRISD=0B00000000; PORTB=0x00; PORTC=0x00; PORTD=0x00; PORTE=0x00; RBIE=0; } //名称: 按键扫描函数 unsigned char key(void) { keyI2=0; keyI3=1; asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP"); if(keyO3==0) { return 1; } else if(keyO4==0) { return 2; } keyI2=1; keyI3=0; asm("NOP"); asm("NOP"); asm("NOP"); asm("NOP"); if(keyO3==0) { return 3; } else if(keyO4==0) { return 4; } return 5; }
//名称: 按键处理函数 void keypro(void) { unsigned char keybuf; keybuf=key(); if(keybuf==5) { if(keybit==0) { if(++keycon>5) { keycon=0; keybit=1; } } } else { if(keybit==1) { keybit=0; beepbit=1; if(keybuf==1) //【1】键作为开关电机用 { if(motor_onoff==0) { motor_onoff=1; pwmcon=1; } else { motor_onoff=0; } } else if(keybuf==2) //【2】键作为电机速度加用 { if(motor_onoff==1) { if(pwmcon<15) { pwmcon++; //加速操作 beepbit=1; } } } else if(keybuf==3) //【3】键作为电机速度减用 { if(motor_onoff==1) { if(pwmcon>0) { pwmcon--; //减速操作 beepbit=1; } } } } } }
//名称: PWM初始化函数 void CCP_INIT(void) { CCPR2L=0x7f; CCP2CON=0x3c; PR2=63; //频率15.625KHZ T2CKPS1=0; T2CKPS0=0; //前分频为1:1 TRISC1=0; //将RC1设置为输入,暂时关闭PWM TMR2ON=1; //启动TIMER2 }
//名称: 蜂鸣器函数 void fengpro(void) { if(beepbit==1) { beep=1; if(++fengcon>10) { fengcon=0; beepbit=0; } } else { fengcon=0; beep=0; } }
//名称: 主函数 void main(void) { init(); CCP_INIT(); while(1) { asm("CLRWDT"); keypro(); fengpro(); if(motor_onoff==1) { pwmbuf=pwm_table[pwmcon]; //查表得到不同速度档的实际PWM预置参数 } else { pwmbuf=0; } CCPR2L=pwmbuf; } }
|