包含程序和仿真
功能:按键或串口发送字符指令,控制步进电机正转、反转、停止、加速、减速动作
单片机源程序如下:
- #include<reg52.h>
- #define uint unsigned int
- #define uchar unsigned char
- //------8拍-----
- uchar code zz[]={0x01,0x03,0x02,0x06,0x04,0x0c,0x08,0x09}; //正转
- uchar code fz[]={0x09,0x08,0x0c,0x04,0x06,0x02,0x03,0x01}; //反转
- sbit K1=P3^0; //停止
- sbit K2=P3^1; //正转
- sbit K3=P3^2; //反转
- sbit K4=P3^3; //加速
- sbit K5=P3^4; //减速
- uchar state=0; //状态变量
- uint Time=60; //延时时间,用于调速
- unsigned char receiveData='0';
- void UsartConfiguration(); //初始化串口
- void delay(uint ms) //延时,用于调速
- {
- uint t;
- while(ms--)
- for(t=0;t<120;t++);
- }
- void motor_zz() //正传函数
- {
- uint j;
- for(j=0;j<8;j++)
- {
- if(P3==0xfb)
- break;
- P1=zz[j];
- delay(Time);
- }
- }
- void motor_fz() //反转函数
- {
- uint j;
- for(j=0;j<8;j++)
- {
- if(P3==0xfb)
- break;
- P1=fz[j];
- delay(Time);
- }
- }
- void main()
- {
- UsartConfiguration();
- while(1)
- {
- while(state==0) //状态0,停止
- {
- if((K2==0)||(receiveData=='z')) //按下K2或串口接收到'z',电机正转
- {
- state=1;
- receiveData='0';
- break;
- }
- if((K3==0)||(receiveData=='f')) //按下K3或串口接收到'f',电机反转
- {
- state=2;
- receiveData='0';
- break;
- }
- P0=0xfb;
- P1=0x03;
- }
-
- while(state==1) //状态1,正转
- {
- if((K1==0)||(receiveData=='t')) //按下K1或串口接收到'f',电机反转
- {
- state=0;
- receiveData='0';
- break;
- }
- if((K2==0)||(receiveData=='z')) //按下K2或串口接收到'z',电机正转
- {
- state=1;
- receiveData='0';
- break;
- }
- if((K3==0)||(receiveData=='f')) //按下K3或串口接收到'f',电机反转
- {
- state=2;
- receiveData='0';
- break;
- }
- if((K4==0)||(receiveData=='+')) //按下K4或串口接收到'+',电机加速
- {
- Time=Time-5;
- if(Time<20)
- Time=20;
- while(K4==0);
- }
- if((K5==0)||(receiveData=='-')) //按下K5或串口接收到'-',电机减速
- {
- Time=Time+5;
- if(Time>100)
- Time=100;
- while(K5==0);
- }
- motor_zz(); //状态1,正转
- }
- while(state==2) //状态2,反转
- {
- if((K1==0)||(receiveData=='t')) //按下K1或串口接收到'f',电机反转
- {
- state=0;
- receiveData='0';
- break;
- }
- if((K2==0)||(receiveData=='z')) //按下K2或串口接收到'z',电机正转
- {
- state=1;
- receiveData='0';
- break;
- }
- if((K3==0)||(receiveData=='f')) //按下K3或串口接收到'f',电机反转
- {
- state=2;
- receiveData='0';
- break;
- }
- if((K4==0)||(receiveData=='+')) //按下K4或串口接收到'+',电机加速
- {
- Time=Time-5;
- if(Time<20)
- Time=20;
- while(K4==0);
- }
- if((K5==0)||(receiveData=='-')) //按下K5或串口接收到'-',电机减速
- {
- Time=Time+5;
- if(Time>100)
- Time=100;
- while(K5==0);
- }
- motor_fz(); //状态2,反转
- }
- }
- }
- /************************************************************************
- * 函数名 :UsartConfiguration()
- * 函数功能 :设置串口
- * 输入 : 无
- * 输出 : 无
- *************************************************************************/
- void UsartConfiguration()
- {
- SCON=0X50; //设置为工作方式1
- //TMOD=0X20; //设置计数器工作方式2
- TMOD=0X21; //设置计数器工作方式2 和定时器0
- PCON=0X80; //波特率加倍
- ……………………
- …………限于本文篇幅 余下代码请从51黑下载附件…………
复制代码
所有资料51hei提供下载:
按键&串口控制步进电机正反转调速.zip
(163.03 KB, 下载次数: 644)
|