3 #include "stepper_motor.h" 6 const PROGMEM uint8_t STEP_SEQUENCE[] = {
19 for(uint8_t pin : pins) {
21 this->pins[i++] = pin;
28 uint8_t rotations = -degree / 360;
29 degree = -degree % 360;
31 for(uint16_t steps = 0; steps < rotations * steps_per_rotation; ++steps) {
34 turnTo(((int16_t)current_degree_position - degree + 360) % 360);
36 uint8_t rotations = degree / 360;
37 degree = degree % 360;
39 for(uint16_t steps = 0; steps < rotations * steps_per_rotation; ++steps) {
42 turnTo(((int16_t)current_degree_position + degree) % 360);
47 target_angle = target_angle % 360;
48 uint16_t target_step_position = ((uint32_t)target_angle * steps_per_rotation / 360) % steps_per_rotation;
50 while(target_step_position != current_step_position) {
51 if(current_step_position > target_step_position && current_step_position - target_step_position < steps_per_rotation / 2 ||
52 current_step_position < target_step_position && target_step_position - current_step_position > steps_per_rotation / 2) {
59 current_degree_position = target_angle;
64 steps_per_rotation = steps;
68 this->waiter = waiter;
72 void StepperMotor::Driver::stepForward() {
73 current_step_position = (current_step_position + 1) % steps_per_rotation;
74 for(
size_t i = 0; i < 8; ++i) {
75 executeStep(pgm_read_byte_near(STEP_SEQUENCE + i));
80 void StepperMotor::Driver::stepBackward() {
81 current_step_position = (current_step_position + steps_per_rotation - 1) % steps_per_rotation;
82 for(
size_t i = 0; i < 8; ++i) {
83 executeStep(pgm_read_byte_near(STEP_SEQUENCE + (7 - i)));
88 void StepperMotor::Driver::executeStep(uint8_t step) {
90 for(uint8_t pin : pins) {
91 digitalWrite(pin, (step & 1 << j++) != 0);
95 void StepperMotor::Driver::resetPins() {
96 for(uint8_t pin : pins) {
97 digitalWrite(pin,
false);
Driver(std::initializer_list< uint8_t > pins)
Create a new driver instance using the given pins.
void turn(int16_t degree)
Relative turn.
void turnTo(uint16_t target_angle)
Absolute turn.
void setStepsPerRotation(uint16_t steps)
Set the steps needed for one complete rotation.
void setWaiter(void(*waiter)(unsigned int))
Set a custom waiter.