/*
Arduino | coding-help
koyo — 5/19/25 4:42 PM
H-bridge control via joystick
Button toggles headlights, maybe it should be a horn button?
(See https://docs.wokwi.com/parts/wokwi-analog-joystick)
*/
#define FWD 0
#define FWDL 1
#define FWDR 2
#define REV 3
#define REVL 4
#define REVR 5
#define LEFT 6
#define RIGHT 7
#define STOP 8
const int SW_PIN = 32;
const int LIGHT_PIN = 26;
const int HORIZ_PIN = 33;
const int VERT_PIN = 25;
const int IN_PINS[] = {13, 12, 14, 27};
const byte MOVES[][4] = { // IN1 - IN4
{255, 0, 255, 0}, // forward
{64, 0, 255, 0}, // forward left
{255, 0, 64, 0}, // forward right
{0, 255, 0, 255}, // reverse
{0, 64, 0, 255}, // reverse left
{0, 255, 0, 64}, // reverse right
{0, 255, 255, 0}, // left
{255, 0, 0, 255}, // right
{0, 0, 0, 0} // stop
};
const char MODE_NAME[][12] = {
{"Forward"},
{"Fwd Left"},
{"Fwd Right"},
{"Reverse"},
{"Rev Left"},
{"Rev Right"},
{"Left"},
{"Right"},
{"Stop"}
};
bool ledState = false;
int oldBtnState = 0;
int oldMode = STOP;
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++) {
analogWrite(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;
int yPos = 0;
int xPos = 0;
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) {
xPos = -1;
} else if (xValue >= 2096) {
xPos = 1;
} else {
xPos = 0;
}
if (yValue <= 2000) {
yPos = -1;
} else if (yValue >= 2096) {
yPos = 1;
} else {
yPos = 0;
}
}
if (yPos == 1 && xPos == 0) { // forward
mode = FWD;
} else if (yPos == 1 && xPos == -1) { // forward right
mode = FWDR;
} else if (yPos == 0 && xPos == -1) { // right
mode = RIGHT;
} else if (yPos == -1 && xPos == -1) { // reverse right
mode = REVR;
} else if (yPos == -1 && xPos == 0) { // reverse
mode = REV;
} else if (yPos == -1 && xPos == 1) { // reverse left
mode = REVL;
} else if (yPos == 0 && xPos == 1) { // left
mode = LEFT;
} else if (yPos == 1 && xPos == 1) { // forward left
mode = FWDL;
}
if (mode != oldMode) {
oldMode = mode;
move(mode);
Serial.print("Mode: ");
Serial.println(MODE_NAME[mode]);
}
}
IN1 - IN4
Headlights