/*
  Arduino | coding-help
  Nika — 11:03 AM Saturday, October 18, 2025
  Hello
  In Wokwi, use CTRL+Click to keep a button pressed.
*/
#include <Servo.h>
// --- DC Motor Pins ---
#define AIN1 7
#define AIN2 6
#define BIN1 5
#define BIN2 4
// --- Buttons ---
#define FWD_BTN 10
#define BACK_BTN 9
#define LEFT_BTN 11
#define RIGHT_BTN 8
// --- Servo ---
Servo myServo;
int servoPos = 90;  // Neutral
// --- Debounce ---
unsigned long lastDebounce[4] = {0, 0, 0, 0};
bool btnState[4] = {0, 0, 0, 0};
const int debounceDelay = 50;
void setup() {
  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);
  pinMode(BIN1, OUTPUT);
  pinMode(BIN2, OUTPUT);
  pinMode(FWD_BTN, INPUT_PULLUP);
  pinMode(BACK_BTN, INPUT_PULLUP);
  pinMode(LEFT_BTN, INPUT_PULLUP);
  pinMode(RIGHT_BTN, INPUT_PULLUP);
  myServo.attach(3);
  myServo.write(servoPos);
  stopMotors();
}
void loop() {
  // Update button states
  readButton(FWD_BTN, 0);
  readButton(BACK_BTN, 1);
  readButton(LEFT_BTN, 2);
  readButton(RIGHT_BTN, 3);
  // Motor control
  if (btnState[0] && !btnState[1]) forward();
  else if (btnState[1] && !btnState[0]) backward();
  else stopMotors();
  // Servo control
  if (btnState[2] && !btnState[3]) turnLeft();
  else if (btnState[3] && !btnState[2]) turnRight();
  else centerServo();
  delay(10);  // small loop delay
}
// ====== FUNCTIONS ======
void readButton(int pin, int index) {
  bool reading = !digitalRead(pin); // active LOW
  if (reading != btnState[index]) {
    if (millis() - lastDebounce[index] > debounceDelay) {
      btnState[index] = reading;
      lastDebounce[index] = millis();
    }
  }
}
void forward() {
  digitalWrite(AIN1, HIGH);
  digitalWrite(AIN2, LOW);
  digitalWrite(BIN1, HIGH);
  digitalWrite(BIN2, LOW);
}
void backward() {
  digitalWrite(AIN1, LOW);
  digitalWrite(AIN2, HIGH);
  digitalWrite(BIN1, LOW);
  digitalWrite(BIN2, HIGH);
}
void stopMotors() {
  digitalWrite(AIN1, LOW);
  digitalWrite(AIN2, LOW);
  digitalWrite(BIN1, LOW);
  digitalWrite(BIN2, LOW);
}
void turnLeft() {
  myServo.write(35);
}
void turnRight() {
  myServo.write(125);
}
void centerServo() {
  myServo.write(90);
}
FWD
REV
RIGHT
LEFT
AIN1
AIN2
BIN1
BIN2