I am currently dealing with stepper motors and am trying to make a basic script that allow me to type how long I want to the motors to run for into the serial monitor however at the moment they just keep moving not matter what number I place in. I still struggle with the for command (I am kinda new) and was wondering if I could get some help
#include <Adafruit_PWMServoDriver.h>
int time;
#include <Wire.h>
#include <Adafruit_MotorShield.h>
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
String msg="What length?";
Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 1);
Adafruit_StepperMotor *myMotor2 = AFMS.getStepper(200, 2);
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
myMotor->setSpeed(10); // 10 rpm
myMotor2->setSpeed(10); // 10 rpm
AFMS.begin();
time=0;
Serial.println(msg);
}
void loop() {
while (Serial.available() == 0); //waiting for input
int time = Serial.parseInt(); //read as integer
for (int i = 0 ; i < time ;){
myMotor->step(1, BACKWARD, SINGLE);
myMotor2->step(1, BACKWARD, SINGLE);
Serial.print('.');
}
// put your main code here, to run repeatedly:
}
The above is an infinite loop, if time is greater than zero, because i is initialized to zero then never changed from 0. Perhaps you mean something like this:
I am still a bit confused on how for works. I made a test code here And whenever I use it I expected the serial monitor to print ".' repeatedly for 10 seconds however it only prints it once, do you know what I am doing wrong?
unsigned long msecPeriod;
unsigned long msecLst;
bool run;
void loop ()
{
// timer
unsigned long msec = millis ();
if (msecPeriod && msec - msecLst >= msecPeriod) {
msecPeriod = 0;
run = false;
Serial.println ("done");
}
// run when enabled
if (run) {
Serial.println (msec);
delay (500);
}
// enable run when there is input
if (Serial.available ()) { // wait for something to read
Serial.read (); // does it matter what is read?
run = true;
msecPeriod = 5000; // 5 sec
msecLst = msec;
}
}
void setup () {
Serial.begin (9600);
Serial.println ("ready");
}
No, if that code didn't have the offending semicolon it would print '.' to the screen 10,000 times. It would happen really really fast though. It would take a LOT less than 10 seconds.