use PS4

PS4Serial.cpp

Committer:
Suzutomo
Date:
2018-08-29
Revision:
2:ebf134f6c2ef
Parent:
1:f953b9de204e
Child:
5:3b887515b46e

File content as of revision 2:ebf134f6c2ef:

#include "PS4Serial.h"

PS4Serial::PS4Serial(PinName tx, PinName rx) : WirelessSerial(tx, rx, 115200), rp(0)
{
    for(int i = 0; i < 8; i++) ControllerData[i] = 2 <= i && i <= 5 ? 127 : 0;
    WirelessSerial.attach(this, &PS4Serial::WirelessRecive, RawSerial::RxIrq);
}

void PS4Serial::WirelessRecive()
{
    t.stop();
    t.reset();
    char data = WirelessSerial.getc();
    if(data == 0xff) {
        rp = 0;
        for (int i = 0; i < 8; i++) ControllerData_OLD[i] = ControllerData[i];
    } else if(rp > 8) {
        //nothing
    } else {
        ControllerData[rp] = data;
        rp++;
    }
    t.start();
}

int PS4Serial::getButtonPress(PS4Button button)
{
    if(button < 7) {
        return (ControllerData[0] >> button) & 1;
    } else if(button < 14) {
        return (ControllerData[1] >> (button - 7)) & 1;
    } else {
        return ControllerData[button - 12];
    }
}
int PS4Serial::getButtonClick( PS4Button button, bool mode )
{
    //mode:0 -> Rising
    //mode:1 -> Falling

    if(button <= 13) {
        return mode*(ControllerData[button]*!ControllerData_OLD[button])
               + !mode*(!ControllerData[button]*ControllerData_OLD[button]);

    } else if( (19<=button) && (button<=20) ) {
        return mode*((ControllerData[button]>127)*!(ControllerData_OLD[button]>127))
               + !mode*(!(ControllerData[button]>127)*(ControllerData_OLD[button]>127));

    } else {
        return 0;
    }
}

bool PS4Serial::connected()
{
    return t.read_ms() < 500;
}