Drives DC motors on all four shield channels.
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);
}