Wprowadziłem poprawki do kodu zgodnie z twoimi sugestiami.
Kod się kompiluje. Teraz jeszcze został hardware do zrobiena.
Wielkie dzięki!
int DIR_PIN = 2; int STEP_PIN = 3; int POWER_PIN = 4; int SLEEP_PIN = 5; int FilterPos[5] = {0, 217, 435, 651, 869};
int CurrentFilter = 0; //Holds the Current Filter position int Direction = HIGH;
long NoOfSteps = 0; //required number of steps to make long Position = 0; //used to keep track of the current motorposition
String cmdString; String cmd; String arg;
void setup() {
Serial.begin(9600); Serial.flush(); pinMode(DIR_PIN, OUTPUT); pinMode(STEP_PIN, OUTPUT); pinMode(POWER_PIN, OUTPUT); pinMode(SLEEP_PIN, OUTPUT);
digitalWrite(POWER_PIN, LOW); } void loop() {
String cmd; if (Serial.available() > 0) { Serial.flush(); cmdString=Serial.readStringUntil('#'); // Read the serial buffer until we encounter # cmd = cmdString.substring(0,1); // The driver will pass all 1-character commands arg = cmdString.substring(1); // Everything else will be the position or distance to move.
if (cmd=="m") { // Serial.print("Who asks for a return value before completion?"); // Serial.println("#"); NoOfSteps = FilterPos[CurrentFilter] - FilterPos[arg.toInt()]; if (NoOfSteps < 0) { Direction = LOW; EasyDriverStep(Direction, abs(NoOfSteps)); Position = Position - NoOfSteps; } else { Direction = HIGH; EasyDriverStep(Direction, abs(NoOfSteps)); Position = Position - NoOfSteps; }
CurrentFilter = arg.toInt(); //Set CurrentFilter to the position we just moved to Serial.print(Position); Serial.println("#"); }
else if (cmd=="n") { NoOfSteps = arg.toInt(); if (NoOfSteps < 0) { Direction = HIGH; EasyDriverStep(Direction, abs(NoOfSteps)); Position = Position + NoOfSteps; } else { Direction = LOW; EasyDriverStep(Direction, abs(NoOfSteps)); Position = Position + NoOfSteps; } Serial.print(Position); Serial.println("#"); }
else if (cmd=="g") { Serial.print(CurrentFilter); Serial.println("#"); }
} }
void EasyDriverStep(int dir,long steps){
digitalWrite(DIR_PIN,dir); digitalWrite(SLEEP_PIN,HIGH); delay(100); for(int i=0;i<steps;i++){ digitalWrite(STEP_PIN, HIGH); delayMicroseconds(1000); digitalWrite(STEP_PIN, LOW); delayMicroseconds(1000); digitalWrite(SLEEP_PIN,LOW); if (Serial.available() > 0) { cmdString=Serial.readStringUntil('#'); // Read the serial buffer until we encounter # cmd = cmdString.substring(0,1); // The driver will pass all 1-character commands if (cmd=="g") { Serial.print(-1); Serial.println("#"); } else { Serial.print(999); Serial.println("#"); } } } }