- #include<reg51.h>
- #include<math.h> //包含單片機寄存器的頭文件
- #define uchar unsigned char
- #define uint unsigned int
- #define MotorData P0 //水平控制接口定義
- #define MG90 P2 // 豎直控制接口定義
- uchar phasecw[4] ={0x08,0x04,0x02,0x01};//正轉 x導通相序 D-C-B-A
- uchar phaseccw[4]={0x01,0x02,0x04,0x08};
- uchar mg9cw[4] ={0x08,0x04,0x02,0x01};//正轉 y導通相序 D-C-B-A
- uchar mg9ccw[4]={0x01,0x02,0x04,0x08};
- sbit K5=P3^5;
- sbit L0=P1^0;
- sbit L1=P1^1;
- sbit L2=P1^2;
- sbit L3=P1^3;
- sbit L4=P1^4;
- sbit L5=P1^5;
- int z;z=0 ;//將z初始化為0
- int g;
- int h;
- int a;
- a=0;
- int b;
- b=0;
- /*****************************
- 函數功能:延時一段時間
- *****************************/
- void Delay_xms(uint x)
- {
- uint i,j;
- for(i=0;i<x;i++)
- for(j=0;j<112;j++);
- }
- void MotorCW(void)//x順時針轉動
- {
-
-
- uchar i;
- for(i=0;i<4;i++) //循環輸出脈沖
- {
- MotorData=phasecw[i];
- Delay_xms(2);//轉速調節
-
- }
- }
-
-
-
-
- mg90CW() //y順時針
- {
-
- if (a==0)
- {
-
-
- uchar i;
- for(i=0;i<4;i++)
- {
- MG90=mg9cw[i];
-
- g++;
- //角度計數,0-512
- Delay_xms(2);//轉速調節
- a=(g>512);
-
- }
-
- }
- else
- {
- h=512;
- }
- return g;
- }
- void MotorCCW(void)//逆時針轉動
- {
- uchar i;
- for(i=0;i<4;i++)
- {
- MotorData=phaseccw[i];
- Delay_xms(2);//轉速調節
- }
- }
- mg90CCW()//y逆時針
- {
-
- if (b==0)
- {
-
-
- uchar i;
- for(i=0;i<4;i++)
- {
- MG90=mg9ccw[i];
-
- h--; //角度計數 512-0
-
- Delay_xms(2);//轉速調節
- b=(h<0);
- }
-
- }
- else
- {
- g=0;
- }
- return h;
- }
- //停止轉動
- void MotorStop(void)
- {
- MotorData=0x00;
- }
- void mg90Stop(void)//y停止
- {
- MG90=0x00;
- }
-
- /*****************************
- 函數功能:主函數
- *****************************/
- main()
- {
-
- while(1)
- {
-
- if(K5==0) //如果鍵按下
- {
- Delay_xms(1000); //延時一段時間 按鍵消抖
- if(K5==0)//如果再次檢測到S1鍵按下
- z++; //z自增1
- if(z==7) //如果z=7,重新將其置為1
- z=1;
- }
-
- switch(z) //使用多分支選擇語句
- {
- case 1: MotorCCW(),L0=0,L1=1,L2=1; //第一個LED亮
- break;
- case 2: MotorCW(),L1=0,L0=1,L2=1; //第二個LED亮
- break;
- case 3: MotorStop(),L2=0,L1=1,L0=1,h=512;
- break; //第三個LED亮
- case 4: mg90CCW(),L3=0,L4=1,L5=1,g=0; //第四個LED亮 ,y逆時針
- break;
- case 5: mg90CW(),L4=0,L3=1,L5=1; //第五個LED亮 ,y順時針
- break;
- case 6: mg90Stop(),L5=0,L3=1,L4=1,h=512,g=0; //第六個LED亮
- break;
-
-
- }
- }
- }
復制代碼 |