Arduino程式設計->步進電機角度控制
阿新 • • 發佈:2019-01-01
#include<Stepper.h> #define KEY 2 //定義 key_1 I/O number is 2 // 參考檔案 /* 28BYJ-48.pdf 該引數根據電機每一轉的步數來修改 */ const int stepsPerRevolution = 256; const int stepsDelay = 10000; int stepin=0; int count=1; /* steps=5.68888 旋轉1度 steps=170.666 旋轉30度 steps=256 旋轉45度 steps=341.333 旋轉60度 steps=512 旋轉90度 steps=1024 旋轉180度 steps=2048 旋轉360度 */ // 初始化步進電機要使用的Arduino的引腳編號 Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11); void setup() { // 設定轉速,單位r/min myStepper.setSpeed(20); // 初始化串列埠 Serial.begin(9600); } void clockwise() { // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(stepsPerRevolution); delay(stepsDelay); } void anticlockwise() { // 逆時針一次旋轉 Serial.println("counterclockwise"); myStepper.step(-2048); delay(500); } void loop01() { int i; while(1) { i=analogRead(5); if(i>900) //開關開啟 { if((count==0)&&(stepin<8)) { clockwise(); count=1; stepin=stepin+1; } if((count==0)&&(stepin==8)) { anticlockwise(); count=1; stepin=0; } delay(1000); } else if(i<10)//開關關閉 { count=0; } } } void loop() { // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(stepsPerRevolution); delay(stepsDelay); // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(stepsPerRevolution); delay(stepsDelay); // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(stepsPerRevolution); delay(stepsDelay); // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(stepsPerRevolution); delay(stepsDelay); // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(stepsPerRevolution); delay(stepsDelay); // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(stepsPerRevolution); delay(stepsDelay); // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(stepsPerRevolution); delay(stepsDelay); // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(stepsPerRevolution); delay(stepsDelay); // 逆時針一次旋轉 Serial.println("counterclockwise"); myStepper.step(-2048); delay(500); } void main1() { int i; while(1) { i=analogRead(5); if(i>900) { // 順時針一次旋轉 Serial.println("clockwise"); myStepper.step(2048); delay(1000); // 逆時針一次旋轉 Serial.println("counterclockwise"); myStepper.step(-2048); delay(5000); } } }