RC car, steering issues

Hello everyone,

I have been working on an rc car, which I control remotely through a ps4 controller, but I have been running into some problems with the steering: as of right now the code I wrote enables the car to go forward and backward when I push the left joystick up or down, and it steers if I bring the left joystick ad idle and push the right joystick to the right or to the left. I wrote the code this way because I could not find a way to make the car steer while going forward: if I try to push the right joystick while the left is already pushed, the motors go in conflict and usually the steer signal (sent by the right joystick) prevails, making the car turn without going forward.

Here’s what I would want my motors to do: let’s suppose that the car is going forward, so the left joystick on the controller is pushed up, but not all the way, so that the two motors move at half speed; whenever I push the right joystick towards the right, the motor on the left should increase its speed and the one on the right should decrease it by the same amount (which is proportional to how far the right joystick is pushed).
something like: leftMotorSpeed = speed + steer
rightMotorSpeed = speed - steer

I should say that the code is not entirely mine, I downloaded it from this video on youtube, because I did not know how to write code to connect the ps4 controller to the esp32. The part regarding the motors is written by me.

Also, I know the code is a little long, the part you should be focusing on is in the game controller actions section (see the comments), inside the joysticks if cycles.

Components used:

-esp32: DevKitC V2 esp32-wroom-32 made by Az-Delivery. (datasheet: https://azde.ly/embeajwu)

-"TT motor" made bySunfounder (info: TT Motor — SunFounder 3in1 Kit documentation)

-L9110 Motor driver module (info/documentation)

-5V step down voltage regulator (bought here, I could not find an official datasheet)

-4 alkaline batteries to power the esp32, and a li-ion 18650 battery to power the motor driver module.

Schematics of the circuit:

Code:

#include <Bluepad32.h>

#define A1 4   //A-1A pin of the L9110
#define A2 16  //A-1B pin of the L9110
#define B1 18  //B-1A pin of the L9110
#define B2 19  //B-1B pin of the L9110

int speed = 0;
int steer = 0;

ControllerPtr myControllers[BP32_MAX_GAMEPADS];

// This callback gets called any time a new gamepad is connected.
// Up to 4 gamepads can be connected at the same time.
void onConnectedController(ControllerPtr ctl) {
  bool foundEmptySlot = false;
  for (int i = 0; i < BP32_MAX_GAMEPADS; i++) {
    if (myControllers[i] == nullptr) {
      Serial.printf("CALLBACK: Controller is connected, index=%d\n", i);
      // Additionally, you can get certain gamepad properties like:
      // Model, VID, PID, BTAddr, flags, etc.
      ControllerProperties properties = ctl->getProperties();
      Serial.printf("Controller model: %s, VID=0x%04x, PID=0x%04x\n", ctl->getModelName().c_str(), properties.vendor_id, properties.product_id);
      myControllers[i] = ctl;
      foundEmptySlot = true;
      break;
    }
  }

  if (!foundEmptySlot) {
    Serial.println("CALLBACK: Controller connected, but could not found empty slot");
  }
}

void onDisconnectedController(ControllerPtr ctl) {
  bool foundController = false;

  for (int i = 0; i < BP32_MAX_GAMEPADS; i++) {
    if (myControllers[i] == ctl) {
      Serial.printf("CALLBACK: Controller disconnected from index=%d\n", i);
      myControllers[i] = nullptr;
      foundController = true;
      break;
    }
  }

  if (!foundController) {
    Serial.println("CALLBACK: Controller disconnected, but not found in myControllers");
  }
}

// ========= SEE CONTROLLER VALUES IN SERIAL MONITOR ========= //

void dumpGamepad(ControllerPtr ctl) {
  Serial.printf(
    "idx=%d, dpad: 0x%02x, buttons: 0x%04x, axis L: %4d, %4d, axis R: %4d, %4d, brake: %4d, throttle: %4d, "
    "misc: 0x%02x, gyro x:%6d y:%6d z:%6d, accel x:%6d y:%6d z:%6d\n",
    ctl->index(),        // Controller Index
    ctl->dpad(),         // D-pad
    ctl->buttons(),      // bitmask of pressed buttons
    ctl->axisX(),        // (-511 - 512) left X Axis
    ctl->axisY(),        // (-511 - 512) left Y axis
    ctl->axisRX(),       // (-511 - 512) right X axis
    ctl->axisRY(),       // (-511 - 512) right Y axis
    ctl->brake(),        // (0 - 1023): brake button
    ctl->throttle(),     // (0 - 1023): throttle (AKA gas) button
    ctl->miscButtons(),  // bitmask of pressed "misc" buttons
    ctl->gyroX(),        // Gyro X
    ctl->gyroY(),        // Gyro Y
    ctl->gyroZ(),        // Gyro Z
    ctl->accelX(),       // Accelerometer X
    ctl->accelY(),       // Accelerometer Y
    ctl->accelZ()        // Accelerometer Z
  );
}

// ========= Movement functions =========== //

void MoveForwardMotor1(int velocita) {
  analogWrite(A1, velocita);
  analogWrite(A2, 0);
}

void MoveForwardMotor2(int velocita) {
  analogWrite(B1, 0);
  analogWrite(B2, velocita);
}

void MoveBackwardMotor1(int velocita) {
  analogWrite(A1, 0);
  analogWrite(A2, velocita);
}
void MoveBackwardMotor2(int velocita) {
  analogWrite(B1, velocita);
  analogWrite(B2, 0);
}

void Stop() {
  analogWrite(A1, 0);
  analogWrite(A2, 0);
  analogWrite(B1, 0);
  analogWrite(B2, 0);
}

// ========= GAME CONTROLLER ACTIONS SECTION ========= //

void processGamepad(ControllerPtr ctl) {
  // There are different ways to query whether a button is pressed.
  // By query each button individually:
  //  a(), b(), x(), y(), l1(), etc...

  //== PS4 X button = 0x0001 ==//
  if (ctl->buttons() == 0x0001) {
    // code for when X button is pushed

    Stop();
  }
  if (ctl->buttons() != 0x0001) {
    // code for when X button is released
  }

  //== PS4 Square button = 0x0004 ==//
  if (ctl->buttons() == 0x0004) {
    // code for when square button is pushed

    Brake();
  }
  if (ctl->buttons() != 0x0004) {
    // code for when square button is released
  }

  //== PS4 Triangle button = 0x0008 ==//
  if (ctl->buttons() == 0x0008) {
    // code for when triangle button is pushed
  }
  if (ctl->buttons() != 0x0008) {
    // code for when triangle button is released
  }

  //== PS4 Circle button = 0x0002 ==//
  if (ctl->buttons() == 0x0002) {
    // code for when circle button is pushed
  }
  if (ctl->buttons() != 0x0002) {
    // code for when circle button is released
  }

  //== PS4 Dpad UP button = 0x01 ==//
  if (ctl->buttons() == 0x01) {
    // code for when dpad up button is pushed
  }
  if (ctl->buttons() != 0x01) {
    // code for when dpad up button is released
  }

  //==PS4 Dpad DOWN button = 0x02==//
  if (ctl->buttons() == 0x02) {
    // code for when dpad down button is pushed
  }
  if (ctl->buttons() != 0x02) {
    // code for when dpad down button is released
  }

  //== PS4 Dpad LEFT button = 0x08 ==//
  if (ctl->buttons() == 0x08) {
    // code for when dpad left button is pushed
  }
  if (ctl->buttons() != 0x08) {
    // code for when dpad left button is released
  }

  //== PS4 Dpad RIGHT button = 0x04 ==//
  if (ctl->buttons() == 0x04) {
    // code for when dpad right button is pushed
  }
  if (ctl->buttons() != 0x04) {
    // code for when dpad right button is released
  }

  //== PS4 R1 trigger button = 0x0020 ==//
  if (ctl->buttons() == 0x0020) {
    // code for when R1 button is pushed
  }
  if (ctl->buttons() != 0x0020) {
    // code for when R1 button is released
  }

  //== PS4 R2 trigger button = 0x0080 ==//
  if (ctl->buttons() == 0x0080) {
    // code for when R2 button is pushed
  }
  if (ctl->buttons() != 0x0080) {
    // code for when R2 button is released
  }

  //== PS4 L1 trigger button = 0x0010 ==//
  if (ctl->buttons() == 0x0010) {
    // code for when L1 button is pushed
  }
  if (ctl->buttons() != 0x0010) {
    // code for when L1 button is released
  }

  //== PS4 L2 trigger button = 0x0040 ==//
  if (ctl->buttons() == 0x0040) {
    // code for when L2 button is pushed
  }
  if (ctl->buttons() != 0x0040) {
    // code for when L2 button is released
  }

  //== LEFT JOYSTICK - UP ==//
  if (ctl->axisY() <= -55) {
    // code for when left joystick is pushed up
    speed = map(ctl->axisY(), -55, -512, 0, 256);  //map the values of the joystick to the pwm values to send to the motor
    MoveForwardMotor1(speed);
    MoveForwardMotor2(speed);
  }

  //== LEFT JOYSTICK - DOWN ==//
  if (ctl->axisY() >= 55) {
    // code for when left joystick is pushed down
    // Set motors reverse

    speed = map(ctl->axisY(), 55, 512, 0, 256);   //map the values of the joystick to the pwm values to send to the motor


    MoveBackwardMotor1(speed);
    MoveBackwardMotor2(speed);
  }



  //== LEFT JOYSTICK - LEFT ==//
  if (ctl->axisX() <= -55) {
    // code for when left joystick is pushed left
  }

  //== LEFT JOYSTICK - RIGHT ==//
  if (ctl->axisX() >= 55) {
    // code for when left joystick is pushed right
  }

  //== LEFT JOYSTICK DEADZONE ==//
  if (ctl->axisY() > -55 && ctl->axisY() < 55) {
    // code for when left joystick is at idle on the y axis

    Stop();


  }
  if (ctl->axisX() > -25 && ctl->axisX() < 25) {
    // code for when left joystick is at idle on the x axis
  }

  //== RIGHT JOYSTICK - RIGHT ==//
  if (ctl->axisRX() >= 55) {
    // code for when right joystick moves towards the right

    steer = map(ctl->axisRX(), 55, 512, 0, 255);   //map the values of the right joystick to the steer values
    MoveForwardMotor2(steer);
    MoveBackwardMotor1(steer);
  }
  //== RIGHT JOYSTICK - LEFT ==//
  if (ctl->axisRX() <= -55) {
    // code for when right joystick moves towards the left

    steer = map(ctl->axisRX(), -55, -512, 0, 255);  //map the values of the right joystick to the steer values
    MoveForwardMotor1(steer);
    MoveBackwardMotor2(steer);
  }

  //== RIGHT JOYSTICK - Y AXIS ==//
  if (ctl->axisRY()) {
    // code for when right joystick moves along y-axis
  }
  
  dumpGamepad(ctl);
}

void processControllers() {
  for (auto myController : myControllers) {
    if (myController && myController->isConnected() && myController->hasData()) {
      if (myController->isGamepad()) {
        processGamepad(myController);
      } else {
        Serial.println("Unsupported controller");
      }
    }
  }
}

// Arduino setup function. Runs in CPU 1
void setup() {
  Serial.begin(115200);
  Serial.printf("Firmware: %s\n", BP32.firmwareVersion());
  const uint8_t* addr = BP32.localBdAddress();
  Serial.printf("BD Addr: %2X:%2X:%2X:%2X:%2X:%2X\n", addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);

  // Setup the Bluepad32 callbacks
  BP32.setup(&onConnectedController, &onDisconnectedController);

  // "forgetBluetoothKeys()" should be called when the user performs
  // a "device factory reset", or similar.
  // Calling "forgetBluetoothKeys" in setup() just as an example.
  // Forgetting Bluetooth keys prevents "paired" gamepads to reconnect.
  // But it might also fix some connection / re-connection issues.
  BP32.forgetBluetoothKeys();

  // Enables mouse / touchpad support for gamepads that support them.
  // When enabled, controllers like DualSense and DualShock4 generate two connected devices:
  // - First one: the gamepad
  // - Second one, which is a "virtual device", is a mouse.
  // By default, it is disabled.
  BP32.enableVirtualDevice(false);



  //pin dei motori:
  pinMode(A1, OUTPUT);
  pinMode(A2, OUTPUT);
  pinMode(B1, OUTPUT);
  pinMode(B2, OUTPUT);

  // Start with motors off
  analogWrite(A1, 0);
  analogWrite(A2, 0);
  analogWrite(B1, 0);
  analogWrite(B2, 0);
}

// Arduino loop function. Runs in CPU 1.
void loop() {
  // This call fetches all the controllers' data.
  // Call this function in your main loop.
  bool dataUpdated = BP32.update();
  if (dataUpdated)

    processControllers();



  // The main loop must have some kind of "yield to lower priority task" event.
  // Otherwise, the watchdog will get triggered.
  // If your main loop doesn't have one, just add a simple `vTaskDelay(1)`.
  // Detailed info here:
  // https://stackoverflow.com/questions/66278271/task-watchdog-got-triggered-the-tasks-did-not-reset-the-watchdog-in-time

  // vTaskDelay(1);
  delay(30);
}

Thank you in advance for your help, any suggestions are appreciated!

My suggestion is for you to pick just ONE problem and begin to work through your code to find what is causing that one problem and correct it. The reason people have problems is they attempt to program/code EVERYTHING into a single final product and then begin to test. That is proven over the years to be the wrong way to do a project.

One step at a time will get you a much better product.

When you move either stick up the code sets both motors to the same speed, hence the car moves forwards

Change the code so that each stick controls only one motor. When the left stick goes up set the speed of the left motor and when the right stick goes up set the speed of the right motor

Hi Bob, thank you for your answer

I guess that would work fine, but I was wondering if there was a way to use one joystick to move forward or backward and the other one to steer, just because it is more intuitive to control the car this way

Of course there is, but you will have to do some work, yourself, to make that happen!

Hi Paul, I certainly wasn’t asking you to write the code for me and I’m sorry if it’s been misunderstood. I was, however, asking for suggestions regarding ideas for the structure of the code: like maybe moving the “movement functions” into the loop function (which I tried but could not make work), or creating multiple if cycles which consider the positions of both joysticks (I also tried this, with 4 if cycles: 1) left joystick up and right joystick right; 2) left joystick up and right joystick left; 3) left joystick down and right joystick right; 3) left joystick down and right joystick left, but this also did not work)…

As you can see it’s not that I haven’t tried and wanted you to do the work for me… I just thought that your experience could point me in the right direction.

Anyway I’ll take the blame for not being specific enough

How many different joystick positions can you distinguish between ?

For instance, can you distinguish between forward alone and forward combined with left ?

Yes, you can, or at least that’s what I would like my code to do, I’ll try to explain it better through some examples of the behaviour I would like my motors to have:

Left joystick pushed up (and right joystick at idle) : both motors go full speed

left joystick pushed up and right joystick pushed all the way to the right: left motor goes full speed and right motor stops

I guess you can have as many distinguished positions as the different combinations of left and right joystick values
I hope this answers your question

Start by writing all of the possible stick position combinations along with the associated rules for what the axisX and axisY values would

Taking your example

the axisY() value would be less than or equal to -55 and the axisXR() value would be greater than or equal to 55. I got those values from your sketch

Determine the corresponding values for all other joystick combinations and write them down. Having done that add what motor commands should be executed when the sticks are in each position

Once you have done that you can write the code to test for the stick combinations and to output the corresponding motor commands

You only need one joystick using the concept of "skid steering" and PWM.

Here is a simulation that shows "steering" with LEDs and descriptive text.

It shows basic steering, skid steering and PWM steering... This is the output of the simulation...

BASIC STEERING (FOUR plus STOP)

Enable motors... All motors Stop. (L STOP R STOP)
	Forward.	        (L FWD R FWD)	Reverse.	         (L REV R REV)
	Rotate Left.	    (L REV R FWD)	Rotate Right.	     (L FWD R REV)
All motors Stop. (L STOP R STOP)... Disable motors.

SKID STEERING (FOUR plus STOP)

Enable motors... All motors Stop. (L STOP R STOP)
	Forward Skid-Left.  (L STOP R FWD)	Reverse Skid-Right.  (L STOP R REV)
	Forward Skid-Right. (L FWD R STOP)	Reverse Skid-Left.   (L REV R STOP)
All motors Stop. (L STOP R STOP)... Disable motors.

PWM STEERING (SIX plus STOP)

Forward (L FWD R FWD) 
Increase PWM speed: 0 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 
Decrease PWM speed: 255 240 225 210 195 180 165 150 135 120 105 90 75 60 45 30 15 0 
Stop PWM

Reverse (L REV R REV) 
Increase PWM speed: 0 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 
Decrease PWM speed: 255 240 225 210 195 180 165 150 135 120 105 90 75 60 45 30 15 0 
Stop PWM

Right rotate (L FWD R OFF) 
Increase PWM speed: 0 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 
Decrease PWM speed: 255 240 225 210 195 180 165 150 135 120 105 90 75 60 45 30 15 0 
Stop PWM

Left rotate (L OFF R FWD) 
Increase PWM speed: 0 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 
Decrease PWM speed: 255 240 225 210 195 180 165 150 135 120 105 90 75 60 45 30 15 0 
Stop PWM

Right spin (L FWD R REV) 
Increase PWM speed: 0 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 
Decrease PWM speed: 255 240 225 210 195 180 165 150 135 120 105 90 75 60 45 30 15 0 
Stop PWM

Left spin (L REV R FWD) 
Increase PWM speed: 0 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 240 255 
Decrease PWM speed: 255 240 225 210 195 180 165 150 135 120 105 90 75 60 45 30 15 0 
Stop PWM

Fin.