dc-motors

nkrkv/af-motor/dc-motors

Drives DC motors on all four shield channels.
dc-motors
@/dc-motors
Drives DC motors on all four shield channels.
M1number
Speed of motor at channel `M1` in range [-1, 1]
M2number
Speed of motor at channel `M2` in range [-1, 1]
M3number
Speed of motor at channel `M3` in range [-1, 1]
M4number
Speed of motor at channel `M4` in range [-1, 1]
dc-motors
M1
M2
M3
M4
To use the node in your project you should have the nkrkv/af-motor library installed. Use the “File → Add Library” menu item in XOD IDE if you don’t have it yet. See Using libraries for more info.

C++ implementation

struct State {
    bool begun;
};

{{ GENERATED_CODE }}


// Derive pinout from schematic
// https://cdn-learn.adafruit.com/assets/assets/000/009/769/original/mshieldv1-schem.png

constexpr uint8_t DIR_LATCH = 12;
constexpr uint8_t DIR_SER = 8;
constexpr uint8_t DIR_CLK = 4;
constexpr uint8_t DIR_EN = 7;

constexpr uint8_t M1_PWM = 11; // PMW2A
constexpr uint8_t M1_A = 1 << 2;
constexpr uint8_t M1_B = 1 << 3;

constexpr uint8_t M2_PWM = 3; // PMW2B
constexpr uint8_t M2_A = 1 << 1;
constexpr uint8_t M2_B = 1 << 4;

constexpr uint8_t M3_PWM = 5; // PMW0B
constexpr uint8_t M3_A = 1 << 0;
constexpr uint8_t M3_B = 1 << 6;

constexpr uint8_t M4_PWM = 6; // PMW0A
constexpr uint8_t M4_A = 1 << 5;
constexpr uint8_t M4_B = 1 << 7;


void evaluate(Context ctx) {
    State* state = getState(ctx);
    if (!state->begun) {
        pinMode(DIR_LATCH, OUTPUT);
        pinMode(DIR_SER, OUTPUT);
        pinMode(DIR_CLK, OUTPUT);
        pinMode(DIR_EN, OUTPUT);
        pinMode(M1_PWM, OUTPUT);
        pinMode(M1_A, OUTPUT);
        pinMode(M1_B, OUTPUT);
        pinMode(M2_PWM, OUTPUT);
        pinMode(M2_A, OUTPUT);
        pinMode(M2_B, OUTPUT);
        pinMode(M3_PWM, OUTPUT);
        pinMode(M3_A, OUTPUT);
        pinMode(M3_B, OUTPUT);
        pinMode(M4_PWM, OUTPUT);
        pinMode(M4_A, OUTPUT);
        pinMode(M4_B, OUTPUT);

        state->begun = true;
    }
    
    Number m1Speed = getValue<input_M1>(ctx);
    Number m2Speed = getValue<input_M2>(ctx);
    Number m3Speed = getValue<input_M3>(ctx);
    Number m4Speed = getValue<input_M4>(ctx);
    
    // Send direction data to L293s through 74HC595
    uint8_t dirByte =
        (m1Speed < 0 ? M1_A : M1_B) |
        (m2Speed < 0 ? M2_A : M2_B) |
        (m3Speed < 0 ? M3_A : M3_B) |
        (m4Speed < 0 ? M4_A : M4_B);
    
    digitalWrite(DIR_LATCH, LOW);
    shiftOut(DIR_SER, DIR_CLK, MSBFIRST, dirByte);
    digitalWrite(DIR_LATCH, HIGH);
    
    // Adjust EN’s of L293s
    analogWrite(M1_PWM, abs(m1Speed) * 255);
    analogWrite(M2_PWM, abs(m2Speed) * 255);
    analogWrite(M3_PWM, abs(m3Speed) * 255);
    analogWrite(M4_PWM, abs(m4Speed) * 255);
}