/*
  Motors.cpp  --  the KITCHEN. HOW the three commands from Motors.h work.

  ONE wiring, shared by all three cars (IR / RF / Bluetooth), so this module
  is written once and every remote's sketch includes it unchanged.

  It is the same L298N driver and the same moves as Lesson 3, with ONE change:
  IN1 sits on D8 instead of D2. Why? The RF car must receive the radio on the
  interrupt pin D2 -- so we keep D2 free on EVERY car and put IN1 on D8. That
  way the one Motors.cpp fits all three remotes.

    L298N ch. A (LEFT motors):   ENA -> D5   IN1 -> D8   IN2 -> D3
    L298N ch. B (RIGHT motors):  ENB -> D6   IN3 -> D4   IN4 -> D7
*/

#include <Arduino.h>
#include "Motors.h"

const byte ENA = 5, IN1 = 8, IN2 = 3;   // left side  (IN1 on D8, not D2)
const byte ENB = 6, IN3 = 4, IN4 = 7;   // right side

// Drive one side. Positive = forward, negative = reverse, 0 = stop.
static void oneSide(byte en, byte a, byte b, int speed) {
  digitalWrite(a, speed > 0 ? HIGH : LOW);
  digitalWrite(b, speed < 0 ? HIGH : LOW);
  analogWrite(en, abs(speed));
}

void beginMotors() {
  pinMode(ENA, OUTPUT); pinMode(IN1, OUTPUT); pinMode(IN2, OUTPUT);
  pinMode(ENB, OUTPUT); pinMode(IN3, OUTPUT); pinMode(IN4, OUTPUT);
  stopCar();
}

void drive(int left, int right) {
  oneSide(ENA, IN1, IN2, left);
  oneSide(ENB, IN3, IN4, right);
}

void stopCar() {
  drive(0, 0);
}
