Reading buttons from PS4 controller

Admin, please move if I’m in the wrong section of the forum.

I’m trying to use a button on the PS4 controller to swith headlights on my RC truck. Ideally I wish to use one button (SQUARE) to switch between off, low and high beam using a relay and the digitalWrite() funtion.

If I do like this I’m only able to switch it off once, and not on again.

digitalWrite(lowbeam, HIGH);

From other examples this should be enough to switch both on and off pins.

Could someone explain how to read and count button-pushes from a PS4 controller?

I’ve also attached my sketch if someone want’s to take a look.

BT_Scania_setup.ino (3.94 KB)

Create a global variable to keep track of the beam state.

uint8_t SquareCount = 0;  // 0=off,1=low, 2=high

The following will cycle from 0-1-2 the back to 0.

   if (PS4.getButtonClick(SQUARE)) {
      Serial.print(F("SquareCount=")); Serial.println(SquareCount);
      switch (SquareCount) {
        default:SquareCount = 0;
                /* fall through */
        case 0: digitalWrite(...);  // turn off
        case 1: digitalWrite(...);  // low beam
        case 2: digitalWrite(...);  // high beam

Thanks gdsports! Code works perfect, the case method was new to me.

I can't see any reset function, guess it resets once it run out of cases?

When the value goes to 3 (or any value other than 0, 1, 2), the default: case forces the counter back to 0.