I am using an Arduino Mega2560 While my motor is moving I can not receive anything from the UARTs. When the motor ends movement, I receive data from UART.
How can I make my motor move without stopping the reception of data from UART?
I am using an Arduino Mega2560 While my motor is moving I can not receive anything from the UARTs. When the motor ends movement, I receive data from UART.
How can I make my motor move without stopping the reception of data from UART?
If you look at AccelStepper.cpp code of the library you're using, you'll notice that runToNewPosition() is:
void AccelStepper::runToNewPosition(long position)
{
moveTo(position);
runToPosition();
}
which, in turns calls:
// Blocks until the target position is reached
void AccelStepper::runToPosition()
{
while (run())
;
}
In turn, run() returns false only when the position is reached, as shown here:
boolean AccelStepper::run()
{
if (_targetPos == _currentPos)
return false;
if (runSpeed())
computeNewSpeed();
return true;
}
As you can see, your program is blocked until the position is not reached.
Data can be still received by the serial port (until buffer is exceed), but you won't be able to read it until that while ends.
To make the motor running without blocking the program, you should implement the AccelStepper functions in the loop function, in a non-blocking way.
In particular, (I only help you to set the position to 1100. You'll make the effort to bring it back to 0, with small modifications), in rotate_motor()
call only:
stepper1.moveTo(1100);
Then in the loop, write somewhere:
stepper1.run();
EDIT:
Hint for having the motor moving forward and then backward as in your original code:
Add a state variable (say you call it "m
"), where you store if you need to move forward (e.g. 2), backward (e.g. 1) or stop (0). Then, before calling stepper1.run()
, check if you actually must move (if (m != 0)
). When you call the stepper1.run()
method, check if it returns false
. In this case it means it reached the position, then you must change the value of m accordingly.