/*
Arduino | coding-help
koyo — 5/19/25 4:42 PM
L298 control via joystick
Button toggles headlights, maybe it should be a horn button?
*/
#define FWD 0
#define REV 1
#define LEFT 2
#define RIGHT 3
#define STOP 4
const int HORIZ_PIN = 32;
const int VERT_PIN = 33;
const int SW_PIN = 25;
const int LIGHT_PIN = 13;
const int IN_PINS[] = {12, 14, 27, 26};
const byte MOVES[][4] = { // IN1 - IN4
{1, 0, 1, 0}, // forward
{0, 1, 0, 1}, // reverse
{0, 1, 1, 0}, // left
{1, 0, 0, 1}, // right
{0, 0, 0, 0} // stop
};
const char MODE_NAME[][8] = {
{"Forward"},
{"Reverse"},
{"Left"},
{"Right"},
{"Stop"}
};
bool ledState = false;
int oldBtnState = 0;
int oldMode = 0;
bool checkButton() {
bool isPressed = false;
int btnState = digitalRead(SW_PIN);
if (btnState != oldBtnState) {
oldBtnState = btnState;
if (btnState == LOW) {
isPressed = true;
//Serial.println("Button pressed");
}
delay(20); // debounce
}
return isPressed;
}
void move(int index) {
for (int pin = 0; pin < 4; pin++) {
digitalWrite(IN_PINS[pin], MOVES[index][pin]);
}
}
void setup() {
Serial.begin(115200);
pinMode(SW_PIN, INPUT_PULLUP);
for (int i = 0; i < 4; i++) {
pinMode(IN_PINS[i], OUTPUT);
}
pinMode(LIGHT_PIN, OUTPUT);
Serial.println("\nJoystick Test... ready");
}
void loop() {
delay(10); // this speeds up the Wokwi simulation
int mode = STOP;
if (checkButton()) {
ledState = !ledState;
digitalWrite(LIGHT_PIN, ledState);
Serial.print("Headlights ");
Serial.println(ledState ? "on" : "off");
}
int xValue = analogRead(HORIZ_PIN);
int yValue = analogRead(VERT_PIN);
if (xValue > 2000 && xValue < 2096 &&
yValue > 2000 && yValue < 2096) { // centered
mode = STOP;
} else if (xValue <= 2000) {
mode = RIGHT;
} else if (xValue >= 2096) {
mode = LEFT;
} else if (yValue >= 2000) {
mode = FWD;
} else if (yValue <= 2096) {
mode = REV;
}
if (mode != oldMode) {
oldMode = mode;
move(mode);
Serial.print("Mode: ");
Serial.println(MODE_NAME[mode]);
}
}
IN1 IN2 IN3 IN4
Headlights