標(biāo)題: 單片機(jī)控制步進(jìn)電機(jī)東拼西湊改出來(lái)的程序有問(wèn)題 [打印本頁(yè)]

作者: dzm8365    時(shí)間: 2018-1-21 01:30
標(biāo)題: 單片機(jī)控制步進(jìn)電機(jī)東拼西湊改出來(lái)的程序有問(wèn)題
下面是單片機(jī)控制步進(jìn)單機(jī)的程序,由于本人沒(méi)學(xué)過(guò)C語(yǔ)言,不是很懂,這些程序都是在網(wǎng)上找的,東拼西湊改出來(lái)的
現(xiàn)在所有功能都實(shí)現(xiàn)了,但是還有一點(diǎn)問(wèn)題:

單片機(jī)上電,步進(jìn)電機(jī)復(fù)位,按住KEY1,電機(jī)正轉(zhuǎn),松手反轉(zhuǎn),可以循環(huán),但是按KEY2,電機(jī)不動(dòng)。
如果單片機(jī)上電后,先按key2,電機(jī)正轉(zhuǎn),松手反轉(zhuǎn),再按key2就不轉(zhuǎn)了。按key1同樣可以循環(huán)。

程序應(yīng)該怎么改,請(qǐng)高手指點(diǎn)

  1. #include<reg52.h>
  2. #define uchar unsigned char
  3. #define uint unsigned int

  4. sbit key1=P3^2;   //按鍵1
  5. sbit key2=P3^3;   //按鍵2
  6. sbit key3=P3^4;   //傳感器

  7. uchar code ffw[8]={0x01,0x03,0x02,0x06,0x04,0x0c,0x08,0x09};
  8. uchar code rev[8]={0x09,0x08,0x0c,0x04,0x06,0x02,0x03,0x01};

  9. void delay(uint t)
  10. {                           
  11.    uint k;
  12.    while(t--)
  13.    {
  14.      for(k=0; k<125; k++)
  15.      { }
  16.    }
  17. }


  18. void  motor_ffw(uint n)      //步進(jìn)電機(jī)正轉(zhuǎn)
  19. {
  20.    uchar i;
  21.    uint  j;
  22.    for(j=0; j<6*n; j++)     //轉(zhuǎn)1*n圈
  23.     {
  24.       for(i=0; i<8; i++)      //一個(gè)周期轉(zhuǎn)60度
  25.         {
  26.           P1 = ffw[i];      
  27.           delay(15);         
  28.         }
  29.     }
  30.                 P1=0xff;
  31.                 while(key1==0||key2==0);
  32. }

  33. void  motor_rev(uint n)      //步進(jìn)電機(jī)反轉(zhuǎn)
  34. {
  35.     uchar i;
  36.     uint j;
  37.     for(j=0; j<6*n; j++)   
  38.        {  
  39.           for(i=0;i<8;i++)     
  40.              {
  41.                 if(key3==0)  
  42.                    {  
  43.                         break;           
  44.                    }
  45.                 P1=rev[i];      
  46.                 delay(15);      
  47.              }  
  48.     }
  49.                 P1=0xff;
  50.                 while(key1==1);
  51. }
  52.                
  53.         
  54. void main()
  55. {
  56.     while(1)
  57.         {
  58.             if(key3==1)
  59.                 {
  60.                     delay(50);
  61.                     if(key3==1)
  62.                       {
  63.                           motor_rev(11);
  64.                         }
  65.                   }
  66.               if(key1==0||key2==0)
  67.                  {
  68.                      delay(50);
  69.                      if(key1==0||key2==0)
  70.                        {
  71.                            motor_ffw(10);
  72.                         }
  73.                   }
  74.        }
  75. }
復(fù)制代碼

作者: 阿飛132    時(shí)間: 2018-1-21 09:31
你這個(gè)代碼是按KEY3電機(jī)反轉(zhuǎn),按住KEY1和KEY2電機(jī)正轉(zhuǎn),你可以在主函數(shù)里加按鍵消抖,按下KEY1時(shí),調(diào)用正轉(zhuǎn)函數(shù),松開時(shí),調(diào)用反轉(zhuǎn)函數(shù),下面的同理




歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1