Hi!
I'm making a really simple library to control my stepper motors, and it's also for learning, I'm pretty sure there's already a lot of libraries for this. As I want to make it as efficient as possible, my idea is to use templates to avoid storing the pin addresses in variables and so on. The stepper is a BYJ28-48, and the way I control it is by going through a list of "coil status" (Yeah, I'm not sure how to call it). Anyways, so I can use different modes for that, for example, I can enable one coil at a time, or two at a time, or I can mix both methods and enable the first, then the first and second, then the second only, and so on...
What I used to do before was this:
#if MOTOR_MODE == MODE_PHASE_SINGLE
#define MOTOR_STEPS 4
const uint8_t motor_step_table[MOTOR_STEPS] = {B1000, B0100, B0010, B0001};
#elif MOTOR_MODE == MODE_PHASE_DUAL
#define MOTOR_STEPS 4
const uint8_t motor_step_table[MOTOR_STEPS] = {B1100, B0110, B0011, B1001};
#elif MOTOR_MODE == MODE_PHASE_HALF
#define MOTOR_STEPS 8
const uint8_t motor_step_table[MOTOR_STEPS] = {B1000, B1100, B0100, B0110, B0010, B0011, B0001, B1001};
#else
#error you must define MOTOR_MODE as MODE_PHASE_SINGLE, MODE_PHASE_DUAL or MODE_PHASE_HALF
#endif
And I would use that array (and the const MOTOR_STEPS) in the sketch. As I'm doing it in a library now, I'm not quite sure how I can imitate that same behavior when using templates. The idea would be to pass the MOTOR_MODE value to the initializator list and then have the compiler figure it out (somehow, I'm not even sure if it's technically possible, but I guess there's a workaround). Sure, I could have the constructor set those values (and yeah, I would be losing around 4 + 1 bytes of RAM space), but I actually want to learn if this is possible.
My code [NoDriverStepper.h]:
#ifndef NODRIVERSTEPPER_N
#define NODRIVERSTEPPER_N
/**
* Possible modes:
* MODE_PHASE_SINGLE: one phase at a time (4 steps)
* MODE_PHASE_DUAL: two phases at a time (4 steps, more strength)
* MODE_PHASE_HALF: half step (8 steps, more precise, slightly less strength, uses one and two phases depending on the step)
*/
#define MODE_PHASE_SINGLE 1
#define MODE_PHASE_DUAL 2
#define MODE_PHASE_HALF 3
#if ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#define NDS_TEMPLATE uint8_t MOTOR_PIN1, uint8_t MOTOR_PIN2, uint8_t MOTOR_PIN3, uint8_t MOTOR_PIN4, uint8_t MOTOR_MODE = MODE_PHASE_HALF
#define NDS_TEMPLATE_NOTYPE MOTOR_PIN1, MOTOR_PIN2, MOTOR_PIN3, MOTOR_PIN4, MOTOR_MODE
template <NDS_TEMPLATE>
class NoDriverStepper
{
private:
// any way to define an array here?
// It would be of a fixed length (either 4 or 8 bytes), depending on MOTOR_MODE value (1 and 2 = 4 bytes),
public:
};
#endif
Thank you all!