单片机控制电机正反转及加减速控制
单片机源程序如下:
- #include<reg52.h>
- #define uchar unsigned char
- #define uint unsigned int
- sbit dula = P2^6;//数码管段选
- sbit wela = P2^7;//数码管位选
- sbit key1 = P3^4;//启动
- sbit key2 = P3^5;//正转/反转
- sbit key3 = P3^6;//加速
- sbit key4 = P3^7;//减速
- sbit pul = P2^0;//脉冲
- sbit dir = P2^1;//方向
- sbit ena = P2^2;//使能
- int flag=0;//计数、正反转标志
- int V = 0;//速度
- uint T,ge,shi;
- uchar temp,key;
- uchar code display[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};//数码管显示0-9
- //........................延时函数...........................//
- void delayms(uint xms)
- {
- uint i,j;
- for(i=xms;i>0;i--)
- for(j=110;j>0;j--);
- }
- //........................定时器0/1初始化函数...........................//
- void T0_T1_init()
- {
- TMOD=0x01;//设置定时器为工作方式1
- TH0=(65536-30000)/256;//定时器0定时30ms
- TL0=(65536-30000)%256;
- TH1=(65536-T)/256;//定时器1定时30ms
- TL1=(65536-T)%256;
- EA=1; //开总中断
- ET0=1; //开定时器0中断
- ET1=1; //开定时器1中断
- TR0=1; //启动定时器0
- TR1=0; //启动定时器1
-
- }
- //........................按键函数...........................//
- void keys()
- {
- if(key1 == 0)
- {
- delayms(5);
- if(key1 == 0)//消抖
- {
- TR1=~TR1;//开启定时器1
-
- }
- while(!key1);
- }
- if(key2 == 0)
- {
- delayms(5);
- if(key2 == 0)
- {
- dir=~dir;//正转,反转
- flag++;
- if(flag>1)flag=0;
- }
- while(!key2);
- }
- if(key3 == 0)
- {
- delayms(5);
- if(key3 == 0)//消抖
- {
- V=V+5;
- if(V>60)V=60;//加速
-
- }
- while(!key3);
- }
- if(key4 == 0)
- {
- delayms(5);
- if(key4 == 0)//消抖
- {
- V=V-5;
- if(V<0)V=0;//减速
-
- }
- while(!key4);
- }
- }
- void main()
- {
- T0_T1_init();
- while(1)
- {
- dula = 1;
- P0 = display[flag];//显示正反转
- dula = 0;
- P0 = 0xff;
- wela = 1;
- P0 = 0xfe;
- wela = 0;
- keys();
- T= 125000/V;
- }
- }
- void T0_time()interrupt 1
- {
- TH0=(65536-30000)/256;//定时器0定时30ms
- TL0=(65536-30000)%256;
- shi = V/10;
- ge = V%10;
- dula = 1;
- P0 = display[shi]; //显示速度十位
- dula = 0;
- P0 = 0xff;
- wela = 1;
- P0 = 0xfb;
- wela = 0;
- delayms(10);
- dula = 1;
- P0 = display[ge];//显示速度个位
- dula = 0;
- P0 = 0xff;
- wela = 1;
- P0 = 0xf7;
- wela = 0;
- delayms(10);
- }
- //........................定时器1函数,控制电机频率...........................//
- void T1_time()interrupt 3
- {
- TH1 = (uint)(65536-T)/256;
- TL1 = (uint)(65536-T)%256;
- pul=~pul;//脉冲反转
- }
复制代码
所有资料51hei提供下载:
伺服.rar
(18.2 KB, 下载次数: 21)
|