- /*******************************************************************************
- * 實 驗 名 : 步進電機實驗
- * 使用的IO : 電機用P1口,鍵盤使用P3.0、P3.1、P3.5、P3.6
- * L298N p1.1-p1.3 接 IN1--IN4 OUT1---OUT4 A+ A_ B+ B-
- * 實驗效果 : 按下K1鍵,順時針轉,按下K2鍵,逆時針轉,按下K3鍵,加速,按下K4鍵,減速
- * 注 意 :由于P3.2口跟紅外線共用,所以做按鍵實驗時為了不讓紅外線影響實驗
- * 效果,最好把紅外線先取下來。
- *******************************************************************************/
- #include "reg51.h"
- //電機IO
- #define GPIO_MOTOR P1
- //按鍵IO
- sbit K1=P3^0; //正轉
- sbit K2=P3^1; //反轉
- sbit K3=P3^5; //加速
- sbit K4=P3^6; //減速
- unsigned char code FFW[8]={0xf4,0xf5,0xf1,0xf9,0xf8,0xfa,0xf2,0xf6}; //逆時針
- unsigned char code FFZ[8]={0xf2,0xfa,0xf8,0xf9,0xf1,0xf5,0xf4,0xf6}; //順時針
- unsigned char Direction=0,Speed=0;
- void Delay(unsigned int t);
- void Motor();
- /*******************************************************************************
- * 函 數 名 : main
- * 函數功能 : 主函數
- * 輸 入 : 無
- * 輸 出 : 無
- *******************************************************************************/
- void main(void)
- {
- unsigned char i;
- Speed=180; //默認初始速度 數字越小 延時時間越短 速度越快
- while(1)
- {
- if(K1==0) //檢測按鍵K1是否按下
- {
- Delay(1); //消除抖動
- if(K1==0)
- {
- Direction=1;
- }
- while((i<200)&&(K1==0)) //檢測按鍵是否松開
- {
- Delay(1);
- i++;
- }
- i=0;
- }
- if(K2==0) //檢測按鍵K1是否按下
- {
- Delay(1); //消除抖動
- if(K2==0)
- {
- Direction=2;
- }
- while((i<200)&&(K2==0)) //檢測按鍵是否松開
- {
- Delay(1);
- i++;
- }
- i=0;
- }
- if(K3==0) //檢測按鍵K1是否按下
- {
- Delay(1); //消除抖動
- if(K3==0)
- {
- Speed-=1;
- }
- while((i<200)&&(K3==0)) //檢測按鍵是否松開
- {
- Delay(1);
- i++;
- }
- i=0;
- }
- if(K4==0) //檢測按鍵K1是否按下
- {
- Delay(1); //消除抖動
- if(K4==0)
- {
- Speed+=1;
- }
- while((i<200)&&(K4==0)) //檢測按鍵是否松開
- {
- Delay(1);
- i++;
- }
- i=0;
- }
-
-
- Motor();
-
-
- }
- }
- /*******************************************************************************
- * 函 數 名 : Motor
- * 函數功能 : 電機旋轉函數
- * 輸 入 : 無
- * 輸 出 : 無
- *******************************************************************************/
- void Motor()
- {
- unsigned char i;
- for(i=0;i<8;i++)
- {
- if(Direction==1)
- {
- GPIO_MOTOR = FFW[i];
- }
- if(Direction==2)
- {
- GPIO_MOTOR = FFZ[i];
- }
- Delay(Speed); //調節轉速
- }
- }
- /*******************************************************************************
- * 函 數 名 : Delay
- * 函數功能 : 延時
- * 輸 入 : t
- * 輸 出 : 無
- *******************************************************************************/
- void Delay(unsigned int t)
- {
- while(t--)
- {
- ;
- }
- }
復制代碼
|