USB Game Controller with Raspberry Pi

2021-04-12
2026-05-01
  • ben-mcdonnell - 2021-04-12

    Hi,

    I have a Revolution Pi system that I would like to use a USB Joystick with to control a robot. It is a standard HID device that I can read with jstest. I have been testing with a PS4 controller for now, with the correct drivers installed.

    What would be the best way to interface that with CODESYS? I have seen a few other people asking similar questions on the forum, but I haven't seen any resolutions posted.

    Thanks in advance!

     
  • TimvH

    TimvH - 2026-05-01

    I'm not sure it will work, but you could try it with the CmpCharDevice library.

    You could create a function block that looks something like this:

    As input for the filename, you have to use your Linux device, e.g.:
    '/dev/input/event0'
    '/dev/input/by-path/platform-button@23-event'

    Off course you must also pass the pointer to the memory where the data can be written to and the size (count in number of bytes) of the buffer.

    FUNCTION_BLOCK FB_CharDevice
    VAR_INPUT
        szFilename: STRING;
        pbyBuffer : POINTER TO BYTE;
        udCount : UDINT;
    END_VAR
    VAR_OUTPUT
        iState : INT := 0;
        nrBytesRead : DINT;
    END_VAR
    VAR
        xInit : BOOL := TRUE;
        dFlags: DINT := CmpCharDevice.ACCESS_MODE.O_RDONLY + DINT#4000; // see details for flags: http://linux.die.net/man/2/open, + DINT#4000 is for non-blocking
        hDevice: CmpCharDevice.CmpCharDevice_Implementation.RTS_IEC_HANDLE := -1;
        Result : CmpCharDevice.CmpCharDevice_Implementation.RTS_IEC_RESULT;
    END_VAR
    
    IF xInit THEN
        hDevice := CmpCharDevice.CDOpen(szFilename, dFlags ,Result);
        // if it would not succeed, the result is -1 (Invalid handle)
        IF hDevice <> 16#FFFFFFFF AND Result = 0 THEN
            iState := 5;
        END_IF
        xInit := FALSE;
    END_IF
    
    IF iState = 5 THEN
        nrBytesRead := CmpCharDevice.CDRead(hDevice, pbyBuffer, udCount, Result);
    ELSE
        nrBytesRead := 0;
    END_IF
    

    Make sure you close the connection properly, maybe by overwriting the default FB_Exit method of the FB:

    // Clean up device
    IF hDevice <> 16#FFFFFFFF THEN
        __TRY
            CmpCharDevice.CDClose(hDevice,Result);
        __CATCH
            ;
        __ENDTRY
        iState := 0;
    END_IF
    
     

Log in to post a comment.