Confusion with do {} while();

Hey guys,

First time posting, but I am working on my senior project and am having some issues understanding why my code isn't executing how I'd expect. My project aims to control a payload in 3D space via 6 electric motors (2 per axis). I'm currently trying to debug 1 axis / 2 motor control. Both motors use PID control with feedback in the form of rotational encoders at the end of of the motors.

The position is currently being controlled with a joystick. So for this single axis, we have 1 potentiometer that reads from 0-1000 with 500 being the "0" of the potentiometer. My goal is to separate forward and reverse motion of the payload by motor. One motor drives the positive direction and one motor drives the negative direction.

To accomplish this I thought separating each direction into its own do {} while() with the while containing the difference between position (encoder counts) and desired position (joystick positioning) and a boolean comparison. So, if I rescale the potentiometer to read between -500, and 500 with true 0 at 0 then while the desired position - position (or the error in controls terms) is positive this should cause positive axis motion while if the error is negative it should cause negative axis motion.

This brings me to the code: So, my code seems to work for the positive axis motion. Motor 1 turns on and rotates until it approaches the desired position, but for some reason no matter what I do I can't get the reverse direction to work / trigger. I've also tried using if else statements instead of do while, but I read that for an unknown number of iterations do while is better and because the system will be continuously changing the do while seemed to fit better.

Any tips or advice would be greatly appreciated. Also if its important, using an Arduino Mega 2560 rev 3.

Thanks,

Hayes

Double_Motor_Control_do.ino (7.47 KB)

Your code is eventually going to control 6 motors. Will it work by exquisitely positioning them.one-at-a-time? Probably not. I expect you will need to move them in a coordinated way.

So your main loop needs to make small adjustments on every motor, every time through the loop. You need to use if() instead of while().