| 
 | 
 
我想請問一下,我最近打了一個程式,但發現步進馬達常常位移,因此我想在旁加入一個極限開關,來取代步進馬達反轉750的動作, 
也就是說當我碼達碰到極限開關時即停止動作,等到下一個條件來臨時,再正轉750,請問這樣的程式要如何寫出來? 
 
以下是我目前沒加入極限開關的程式: 
 
#include<Stepper.h> 
const int PIRSensor1 = 7 ;                // 紅外線1動作感測器連接的腳位 
const int PIRSensor2 = 5;                // 紅外線2動作感測器連接的腳位 
Stepper stepper(200, 8, 10, 9, 11);       // 馬達1的PIN腳 
const int stepsPerRevolution1 = 200;      // 馬達1一圈200步 
const int openbutton = 0;                      // 紅色LED的PIN腳 
const int closebutton = 1; 
const int resetbutton = 3;  
const int ledr  = 13; 
int sensorValue1 = 0;                     // 紅外線動作感測器1訊號變數 
int sensorValue2 = 0;                     // 紅外線動作感測器2訊號變數 
int pos = 0;                              // 步進馬達動作變數 
int c = 0;                                // 偵測滿為變數 
int open1 = 0; 
int close1 = 0; 
int reset1 = 0; 
 
void setup() { 
  Serial.begin(9600);                     // 設定頻率 
  pinMode(PIRSensor1, INPUT);             // 人體紅外線1為輸入 
  pinMode(PIRSensor2, INPUT);             // 人體紅外線2為輸入 
  stepper.setSpeed(12);                  // 將馬達的速度設定成RPM        
  pinMode(openbutton,INPUT);                   // 設led為輸出 
  pinMode(closebutton,INPUT); 
  pinMode(resetbutton,INPUT); 
  pinMode(ledr,OUTPUT); 
   
} 
 
void loop(){ 
 
sensorValue1 = digitalRead(PIRSensor1);  // 讀取 PIR Sensor 的狀態 
sensorValue2 = digitalRead(PIRSensor2);  // 讀取 PIR Sensor 的狀態 
open1        = digitalRead(openbutton); 
close1       = digitalRead(closebutton); 
reset1       = digitalRead(resetbutton); 
 
if (open1 == HIGH && c == 0 && sensorValue1 == LOW){ 
  stepper.step(-750); 
  pos = 750; 
  c = 3; 
} 
 
if (close1 == HIGH && c == 4 && sensorValue1 == LOW){ 
  stepper.step(750);  
  pos = 0; 
  c = 4;  
} 
 
if (reset1 == HIGH && sensorValue1== LOW && c == 3 ){ 
  stepper.step(750);  
  pos = 0; 
  c = 0;  
} 
 
if (reset1 == HIGH && sensorValue1 == LOW && c == 4 ){ 
  pos = 0; 
  c = 0;  
} 
   
if (sensorValue1 == HIGH && pos == 0  && c == 0 ){    
stepper.step(-750);                     // 步進馬達反轉750步 
pos = 750; 
 
 } 
if(sensorValue1 == LOW && pos == 750)  { 
stepper.step(750);                     // 步進馬達正轉750步 
pos = 0; 
 } 
  
 
if  (sensorValue2 == LOW   ) {   
digitalWrite(ledr,LOW);  
c=0;  
} 
 
if (sensorValue2 == HIGH ) { 
digitalWrite(ledr,HIGH); 
c=1; 
 } 
 
  
} |   
 
 
 
 |