|
| 1 | +#include <Arduino.h> |
| 2 | + |
| 3 | +const uint8_t PHASETAB[8] = { |
| 4 | + 0b0001, |
| 5 | + 0b0011, |
| 6 | + 0b0010, |
| 7 | + 0b0110, |
| 8 | + 0b0100, |
| 9 | + 0b1100, |
| 10 | + 0b1000, |
| 11 | + 0b1001 |
| 12 | +}; |
| 13 | + |
| 14 | +// use an enum here ?? |
| 15 | +#define BASE 6 |
| 16 | +#define SHOULDER 5 |
| 17 | +#define ELBOW 4 |
| 18 | +#define WRIST_LEFT 2 |
| 19 | +#define WRIST_RIGHT 3 |
| 20 | +#define GRIPPER 1 |
| 21 | +#define ACCESSORY 7 |
| 22 | +#define JACKS 8 |
| 23 | + |
| 24 | +class AbstractArmdroid { |
| 25 | + private: |
| 26 | + int64_t current_positions[8]; |
| 27 | + int64_t target_positions[8]; |
| 28 | + uint8_t phases[8]; |
| 29 | + uint8_t dividers[8]; |
| 30 | + uint8_t counters[8]; |
| 31 | + public: |
| 32 | + AbstractArmdroid() { |
| 33 | + // noop |
| 34 | + } |
| 35 | + void motorGoto(uint8_t m, long pos) { |
| 36 | + this->target_positions[m] = pos; |
| 37 | + } |
| 38 | + void motorMoveby(uint8_t m, long pos) { |
| 39 | + this->target_positions[m] += pos; |
| 40 | + } |
| 41 | + bool isStopped(uint8_t m) { |
| 42 | + return this->current_positions[m] == this->target_positions[m]; |
| 43 | + } |
| 44 | + long getPos(uint8_t m) { |
| 45 | + return this->current_positions[m]; |
| 46 | + } |
| 47 | + void setDivider(uint8_t m, uint8_t div) { |
| 48 | + this->dividers[m] = div; |
| 49 | + } |
| 50 | + void tick() { |
| 51 | + // update phases |
| 52 | + uint8_t changed_flags = 0, motor = 0; |
| 53 | + for (motor = 0; motor < 8; motor++) { |
| 54 | + if (this->isStopped(motor)) { |
| 55 | + this->counters[motor] = 0; |
| 56 | + } else { |
| 57 | + this->counters[motor]++; |
| 58 | + if (this->counters[motor] >= this->dividers[motor]) { |
| 59 | + this->counters[motor] = 0; |
| 60 | + if (this->current_positions[motor] < this->target_positions[motor]) { |
| 61 | + this->current_positions[motor]++; |
| 62 | + this->phases[motor] = (this->phases[motor] + 1) & 7; |
| 63 | + } else { |
| 64 | + this->current_positions[motor]--; |
| 65 | + this->phases[motor] = (this->phases[motor] + 7) & 7; |
| 66 | + } |
| 67 | + changed_flags |= 1 << motor; |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + // write to port |
| 72 | + for (motor = 0; motor < 8; motor++) { |
| 73 | + if ((changed_flags & (1 << motor)) == 0) continue; |
| 74 | + this->writeToPort(motor, PHASETAB[this->phases[motor]]); |
| 75 | + } |
| 76 | + } |
| 77 | + void torqueOff() { |
| 78 | + for (uint8_t i = 0; i < 8; i++) { |
| 79 | + this->writeToPort(i, 0); |
| 80 | + } |
| 81 | + } |
| 82 | + virtual void writeToPort(uint8_t address, uint8_t data); |
| 83 | +}; |
0 commit comments