#include <SoftwareSerial.h>
#include <AccelStepper.h>
// Define a stepper and the pins it will use
AccelStepper stepperR(1, 4, 5);
AccelStepper stepperL(1, 8, 9);
SoftwareSerial BT(11,12); // 接收腳(RX) pin 12, 傳送腳(TX) pin 13
int acc = 80;
int vel = 60;
int ms1L=7,ms2L=6,ms1R=2,ms2R=3;
int posL=0,posR=0;
char ch;
boolean ifChange = false;
void setup(){
stepperR.setMaxSpeed(100);
stepperR.setAcceleration(acc);
stepperL.setMaxSpeed(100);
stepperL.setAcceleration(acc);
pinMode(ms1L,OUTPUT);
pinMode(ms2L,OUTPUT);
pinMode(ms1R,OUTPUT);
pinMode(ms2R,OUTPUT);
digitalWrite(ms1L,LOW);
digitalWrite(ms1R,LOW);
digitalWrite(ms2L,LOW);
digitalWrite(ms2R,LOW);
Serial.begin(9600);
Serial.println("BT is ready!");
BT.begin(9600);
}
void loop(){
if (BT.available()) {
ch = BT.read();
ifChange = true;
Serial.print(ch);
}
if(ifChange){
ifChange = false;
switch(ch){
case 'F': stepperL.setCurrentPosition (0);stepperR.setCurrentPosition (0);goF();break;
case 'B': stepperL.setCurrentPosition (0);stepperR.setCurrentPosition (0);goB();break;
case 'L': stepperL.setCurrentPosition (0);stepperR.setCurrentPosition (0);goL();break;
case 'R': stepperL.setCurrentPosition (0);stepperR.setCurrentPosition (0);goR();break;
case 'S': stepperL.setCurrentPosition (0);stepperR.setCurrentPosition (0);goS();break;
}
}
if(abs(stepperL.currentPosition())>900){
stepperL.setCurrentPosition(0);
}
if(abs(stepperR.currentPosition())>900){
stepperR.setCurrentPosition(0);
}
if (stepperL.distanceToGo() != 0){
stepperL.run();
}
if (stepperR.distanceToGo() != 0){
stepperR.run();
}
}
void goB(){
stepperL.move(-1000);
stepperL.setMaxSpeed(vel);
stepperL.setAcceleration(acc);
stepperR.move(-1000);
stepperR.setMaxSpeed(vel);
stepperR.setAcceleration(acc);
}
void goF(){
stepperL.move(1000);
stepperL.setMaxSpeed(vel);
stepperL.setAcceleration(acc);
stepperR.move(1000);
stepperR.setMaxSpeed(vel);
stepperR.setAcceleration(acc);
}
void goR(){
stepperL.setMaxSpeed(0);
stepperR.move(1000);
stepperR.setMaxSpeed(vel);
stepperR.setAcceleration(acc);
}
void goL(){
stepperL.move(1000);
stepperL.setMaxSpeed(vel);
stepperL.setAcceleration(acc);
stepperR.setMaxSpeed(0);
}
void goS(){
stepperL.setMaxSpeed(0);
stepperR.setMaxSpeed(0);
}