#include <Stepper.h>
const float turnSteps = 200; //2相励磁 2048がモータが1回転するステップ数
int rotation = 0; //初期値で0を設定
int PushButton = 2; //タクトスイッチのPIN番号
int rpm = 0; //ステップモーターの回転数
boolean flg=true; //正回転か逆回転を判断するFLG
Stepper myStepper(turnSteps, 4, 5, 6, 7); //Arduino nano
void setup() {
Serial.begin(9600);
pinMode(PushButton,INPUT_PULLUP); //押しボタン用
}
void loop() {
if(digitalRead(PushButton) == LOW){ //ボタンが押されたら
if(flg==true){ //正回転か逆回転を判断するFLG
switch_move(1); //正回転
// stop_motor();
delay(1000);
flg=false;
}
else{
switch_move(-1); //逆回転
// stop_motor();
delay(1000);
flg=true;
}
}
}
//モーター制御
void switch_move(int motorflg) {
rpm = 60; //回転速度 15以上は脱調で回転しません
myStepper.setSpeed(rpm);
rotation = 200 * motorflg; //2048で1回転 1024で半回転
myStepper.step(rotation);
Serial.print(rotation);
}
//ステップモーターを停止し電流をストップ
void stop_motor() {
rpm = 0;
rotation = 0;
digitalWrite(4, LOW);
digitalWrite(5, LOW);
digitalWrite(6, LOW);
digitalWrite(7, LOW);
}