I am currently working on a project on a atmega 2560 where I need to control multiple stepper motors synchronous. Meaning sometimes only one motor turns at a time and sometimes multiple motors need to turn at the exact same time for the exact same angle. While planning out my approach I ran into a problem I am not certain how to solve. So, I decided to see if anyone can give me valuable advice. I am writing the program in C++ and I wanted to create a class for the stepper motors(see attached UML) which has a method rotate() to, u guessed it, rotate the stepper for a specific angle in a defined direction. Now of course this presents a timing issue because I need to implement the function in such a way that it does not block any other code and enables me to turn multiple motors at the same time. I came up with two possible approaches:
- Using the timers of the atmega and interrupts to create a PWM signal which turns the motors one step per interrupt. In order to be able to turn multiple motors at once I thought about creating a table for active steppers. Each time the ISR is entered it checks what steppers are supposed to move and transfers the PWM signal to the corresponding pins. Of course, I would somehow need to keep track of the number of steps still left to turn (maybe by introducing another member variable).
- Not using interrupts at all and simply avoid blocking the code as much as possible, by not using while loops and using the system time for delays.
Now my question to all of you is whatever possibility you think would work best or if there is something else, I could try? I am pretty confident that I could implement either one of the above, but I am just not quite happy with both of them. It would feel right to use counters and interrupts in order to guarantee exact timing. However, the approach of having an external table for the active steppers makes the program less easy to understand. In addition, I had my problems of fitting ISRs into the object-oriented world.
Any ideas or contributions are highly appreciated.
Best regards Axodarap