Jump to content

Need help using a joystick/gamepad.

- - - - -

  • Please log in to reply
4 replies to this topic

#1
arthur92710

arthur92710

    Newbie

  • Members
  • Pip
  • 3 posts
Hi, I have some experience in c programing, but only for micro-controllers.

My project needs me to control a 6 axis robot arm with a joystick through a RS-232 port on the pc.
I have written a program that controls the robot in visual studio 2010. Its basically a 12 button form(see attachment pic). All it does is send @STEP 232,0,0,0,0,0,0,0 to the arm. 233 is the speed(0-245) and the "0" correspond to how far it moves. The Base has a max range (absolute left/right to absolute right/left) of 3700. in my program I move it in increments of 100. To move it in the opposite direction -100.

The program works fine but, now I need to get a joystick to either click the buttons or directly control it. I would prefer the second. I tried to use the direct x sdk but my windows c++ skills are severely lacking. I need some help using the windows API.

Oh, the joystick im using is a ps2 controller connected to a "2 controller to usb adapter" It shows up in control panel.

Thanks
-Arthur

Attached Files



#2
GeniusGeeko

GeniusGeeko

    Newbie

  • Members
  • PipPip
  • 15 posts
It wouldn't be that hard to learn Direct Input. Direct Input is used for joysticks and gamepads.

A good place to start is: DirectX Tutorial.com - DirectInput Tutorial

#3
arthur92710

arthur92710

    Newbie

  • Members
  • Pip
  • 3 posts
Thanks, but it does not talk about using a joystick. I would prefer using the windows api . Do you know of any example codes?

#4
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts
I think Windows uses DirectX to handle joystick input. I found a tutorial on Google that may help you: DirectX - Joystick Tutorial

Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#5
arthur92710

arthur92710

    Newbie

  • Members
  • Pip
  • 3 posts
Ok, I need alot of help. The only programing I have done is on uC's. Do it on windows is alot harder.
First I don't know which option to choose in visual studio for these examples. For my arm control test I knew I wanted buttons to control each direction and joint, so I used a form. Here I just want to display what button is pressed on the joy stick. What would be the best?

Second, I don't know where all the different parts of the code goes.

I hope im not asking to much.
Thanks
-Arthur

*EDIT*
I decided that it would just be easier to modify the sample code for the directx joystick. I tried to add a serial communication code to it but it kept giving me errors. I will post the original code:
//-----------------------------------------------------------------------------

// File: Joystick.cpp

//

// Desc: Demonstrates an application which receives immediate 

//       Joystick data in exclusive mode via a dialog timer.

//

// Copyright (c) Microsoft Corporation. All rights reserved.

//-----------------------------------------------------------------------------

#define STRICT

#define DIRECTINPUT_VERSION 0x0800

#define _CRT_SECURE_NO_DEPRECATE

#ifndef _WIN32_DCOM

#define _WIN32_DCOM

#endif


#include <windows.h>

#include <commctrl.h>

#include <basetsd.h>

#include <dinput.h>

#include <dinputd.h>

#include <assert.h>

#include <oleauto.h>

#include <shellapi.h>

#include <tchar.h>






#pragma warning( disable : 4996 ) // disable deprecated warning 

#include <strsafe.h>

#pragma warning( default : 4996 )

#include "resource.h"





//-----------------------------------------------------------------------------

// Function-prototypes

//-----------------------------------------------------------------------------

INT_PTR CALLBACK MainDlgProc( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam );

BOOL CALLBACK    EnumObjectsCallback( const DIDEVICEOBJECTINSTANCE* pdidoi, VOID* pContext );

BOOL CALLBACK    EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance, VOID* pContext );

HRESULT InitDirectInput( HWND hDlg );

VOID FreeDirectInput();

HRESULT UpdateInputState( HWND hDlg );


// Stuff to filter out XInput devices

#include <wbemidl.h>

HRESULT SetupForIsXInputDevice();

bool IsXInputDevice( const GUID* pGuidProductFromDirectInput );

void CleanupForIsXInputDevice();


struct XINPUT_DEVICE_NODE

{

    DWORD dwVidPid;

    XINPUT_DEVICE_NODE* pNext;

};


struct DI_ENUM_CONTEXT

{

    DIJOYCONFIG* pPreferredJoyCfg;

    bool bPreferredJoyCfgValid;

};


bool                    g_bFilterOutXinputDevices = false;

XINPUT_DEVICE_NODE*     g_pXInputDeviceList = NULL;





//-----------------------------------------------------------------------------

// Defines, constants, and global variables

//-----------------------------------------------------------------------------

#define SAFE_DELETE(p)  { if(p) { delete (p);     (p)=NULL; } }

#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }


LPDIRECTINPUT8          g_pDI = NULL;

LPDIRECTINPUTDEVICE8    g_pJoystick = NULL;





//-----------------------------------------------------------------------------

// Name: WinMain()

// Desc: Entry point for the application.  Since we use a simple dialog for 

//       user interaction we don't need to pump messages.

//-----------------------------------------------------------------------------

int APIENTRY WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, int )

{

    InitCommonControls();


    WCHAR* strCmdLine;

    int nNumArgs;

    LPWSTR* pstrArgList = CommandLineToArgvW( GetCommandLineW(), &nNumArgs );

    for( int iArg = 1; iArg < nNumArgs; iArg++ )

    {

        strCmdLine = pstrArgList[iArg];


        // Handle flag args

        if( *strCmdLine == L'/' || *strCmdLine == L'-' )

        {

            strCmdLine++;


            int nArgLen = ( int )wcslen( L"noxinput" );

            if( _wcsnicmp( strCmdLine, L"noxinput", nArgLen ) == 0 && strCmdLine[nArgLen] == 0 )

            {

                g_bFilterOutXinputDevices = true;

                continue;

            }

        }

    }

    LocalFree( pstrArgList );


    // Display the main dialog box.

    DialogBox( hInst, MAKEINTRESOURCE( IDD_JOYST_IMM ), NULL, MainDlgProc );


    return 0;

}





//-----------------------------------------------------------------------------

// Name: MainDialogProc

// Desc: Handles dialog messages

//-----------------------------------------------------------------------------

INT_PTR CALLBACK MainDlgProc( HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam )

{

    UNREFERENCED_PARAMETER( lParam );


    switch( msg )

    {

        case WM_INITDIALOG:

            if( FAILED( InitDirectInput( hDlg ) ) )

            {

                MessageBox( NULL, TEXT( "Error Initializing DirectInput" ),

                            TEXT( "DirectInput Sample" ), MB_ICONERROR | MB_OK );

                EndDialog( hDlg, 0 );

            }


            // Set a timer to go off 30 times a second. At every timer message

            // the input device will be read

            SetTimer( hDlg, 0, 1000 / 30, NULL );

            return TRUE;


        case WM_ACTIVATE:

            if( WA_INACTIVE != wParam && g_pJoystick )

            {

                // Make sure the device is acquired, if we are gaining focus.

                g_pJoystick->Acquire();

            }

            return TRUE;


        case WM_TIMER:

            // Update the input device every timer message

            if( FAILED( UpdateInputState( hDlg ) ) )

            {

                KillTimer( hDlg, 0 );

                MessageBox( NULL, TEXT( "Error Reading Input State. " ) \

                            TEXT( "The sample will now exit." ), TEXT( "DirectInput Sample" ),

                            MB_ICONERROR | MB_OK );

                EndDialog( hDlg, TRUE );

            }

            return TRUE;


        case WM_COMMAND:

            switch( LOWORD( wParam ) )

            {

                case IDCANCEL:

                    EndDialog( hDlg, 0 );

                    return TRUE;

            }


        case WM_DESTROY:

            // Cleanup everything

            KillTimer( hDlg, 0 );

            FreeDirectInput();

            return TRUE;

    }


    return FALSE; // Message not handled 

}





//-----------------------------------------------------------------------------

// Name: InitDirectInput()

// Desc: Initialize the DirectInput variables.

//-----------------------------------------------------------------------------

HRESULT InitDirectInput( HWND hDlg )

{

    HRESULT hr;


    // Register with the DirectInput subsystem and get a pointer

    // to a IDirectInput interface we can use.

    // Create a DInput object

    if( FAILED( hr = DirectInput8Create( GetModuleHandle( NULL ), DIRECTINPUT_VERSION,

                                         IID_IDirectInput8, ( VOID** )&g_pDI, NULL ) ) )

        return hr;



    if( g_bFilterOutXinputDevices )

        SetupForIsXInputDevice();


    DIJOYCONFIG PreferredJoyCfg = {0};

    DI_ENUM_CONTEXT enumContext;

    enumContext.pPreferredJoyCfg = &PreferredJoyCfg;

    enumContext.bPreferredJoyCfgValid = false;


    IDirectInputJoyConfig8* pJoyConfig = NULL;

    if( FAILED( hr = g_pDI->QueryInterface( IID_IDirectInputJoyConfig8, ( void** )&pJoyConfig ) ) )

        return hr;


    PreferredJoyCfg.dwSize = sizeof( PreferredJoyCfg );

    if( SUCCEEDED( pJoyConfig->GetConfig( 0, &PreferredJoyCfg, DIJC_GUIDINSTANCE ) ) ) // This function is expected to fail if no Joystick is attached

        enumContext.bPreferredJoyCfgValid = true;

    SAFE_RELEASE( pJoyConfig );


    // Look for a simple Joystick we can use for this sample program.

    if( FAILED( hr = g_pDI->EnumDevices( DI8DEVCLASS_GAMECTRL,

                                         EnumJoysticksCallback,

                                         &enumContext, DIEDFL_ATTACHEDONLY ) ) )

        return hr;


    if( g_bFilterOutXinputDevices )

        CleanupForIsXInputDevice();


    // Make sure we got a Joystick

    if( NULL == g_pJoystick )

    {

        MessageBox( NULL, TEXT( "Joystick not found. The sample will now exit." ),

                    TEXT( "DirectInput Sample" ),

                    MB_ICONERROR | MB_OK );

        EndDialog( hDlg, 0 );

        return S_OK;

    }


    // Set the data format to "simple Joystick" - a predefined data format 

    //

    // A data format specifies which controls on a device we are interested in,

    // and how they should be reported. This tells DInput that we will be

    // passing a DIJOYSTATE2 structure to IDirectInputDevice::GetDeviceState().

    if( FAILED( hr = g_pJoystick->SetDataFormat( &c_dfDIJoystick2 ) ) )

        return hr;


    // Set the cooperative level to let DInput know how this device should

    // interact with the system and with other DInput applications.

    if( FAILED( hr = g_pJoystick->SetCooperativeLevel( hDlg, DISCL_EXCLUSIVE |

                                                       DISCL_FOREGROUND ) ) )

        return hr;


    // Enumerate the Joystick objects. The callback function enabled user

    // interface elements for objects that are found, and sets the min/max

    // values property for discovered axes.

    if( FAILED( hr = g_pJoystick->EnumObjects( EnumObjectsCallback,

                                               ( VOID* )hDlg, DIDFT_ALL ) ) )

        return hr;


    return S_OK;

}



//-----------------------------------------------------------------------------

// Enum each PNP device using WMI and check each device ID to see if it contains 

// "IG_" (ex. "VID_045E&PID_028E&IG_00").  If it does, then it’s an XInput device

// Unfortunately this information can not be found by just using DirectInput.

// Checking against a VID/PID of 0x028E/0x045E won't find 3rd party or future 

// XInput devices.

//

// This function stores the list of xinput devices in a linked list 

// at g_pXInputDeviceList, and IsXInputDevice() searchs that linked list

//-----------------------------------------------------------------------------

HRESULT SetupForIsXInputDevice()

{

    IWbemServices* pIWbemServices = NULL;

    IEnumWbemClassObject* pEnumDevices = NULL;

    IWbemLocator* pIWbemLocator = NULL;

    IWbemClassObject* pDevices[20] = {0};

    BSTR bstrDeviceID = NULL;

    BSTR bstrClassName = NULL;

    BSTR bstrNamespace = NULL;

    DWORD uReturned = 0;

    bool bCleanupCOM = false;

    UINT iDevice = 0;

    VARIANT var;

    HRESULT hr;


    // CoInit if needed

    hr = CoInitialize( NULL );

    bCleanupCOM = SUCCEEDED( hr );


    // Create WMI

    hr = CoCreateInstance( __uuidof( WbemLocator ),

                           NULL,

                           CLSCTX_INPROC_SERVER,

                           __uuidof( IWbemLocator ),

                           ( LPVOID* )&pIWbemLocator );

    if( FAILED( hr ) || pIWbemLocator == NULL )

        goto LCleanup;


    // Create BSTRs for WMI

    bstrNamespace = SysAllocString( L"\\\\.\\root\\cimv2" ); if( bstrNamespace == NULL ) goto LCleanup;

    bstrDeviceID = SysAllocString( L"DeviceID" );           if( bstrDeviceID == NULL )  goto LCleanup;

    bstrClassName = SysAllocString( L"Win32_PNPEntity" );    if( bstrClassName == NULL ) goto LCleanup;


    // Connect to WMI 

    hr = pIWbemLocator->ConnectServer( bstrNamespace, NULL, NULL, 0L,

                                       0L, NULL, NULL, &pIWbemServices );

    if( FAILED( hr ) || pIWbemServices == NULL )

        goto LCleanup;


    // Switch security level to IMPERSONATE

    CoSetProxyBlanket( pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,

                       RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0 );


    // Get list of Win32_PNPEntity devices

    hr = pIWbemServices->CreateInstanceEnum( bstrClassName, 0, NULL, &pEnumDevices );

    if( FAILED( hr ) || pEnumDevices == NULL )

        goto LCleanup;


    // Loop over all devices

    for(; ; )

    {

        // Get 20 at a time

        hr = pEnumDevices->Next( 10000, 20, pDevices, &uReturned );

        if( FAILED( hr ) )

            goto LCleanup;

        if( uReturned == 0 )

            break;


        for( iDevice = 0; iDevice < uReturned; iDevice++ )

        {

            // For each device, get its device ID

            hr = pDevices[iDevice]->Get( bstrDeviceID, 0L, &var, NULL, NULL );

            if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL )

            {

                // Check if the device ID contains "IG_".  If it does, then it’s an XInput device

                // Unfortunately this information can not be found by just using DirectInput 

                if( wcsstr( var.bstrVal, L"IG_" ) )

                {

                    // If it does, then get the VID/PID from var.bstrVal

                    DWORD dwPid = 0, dwVid = 0;

                    WCHAR* strVid = wcsstr( var.bstrVal, L"VID_" );

                    if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 )

                        dwVid = 0;

                    WCHAR* strPid = wcsstr( var.bstrVal, L"PID_" );

                    if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 )

                        dwPid = 0;


                    DWORD dwVidPid = MAKELONG( dwVid, dwPid );


                    // Add the VID/PID to a linked list

                    XINPUT_DEVICE_NODE* pNewNode = new XINPUT_DEVICE_NODE;

                    if( pNewNode )

                    {

                        pNewNode->dwVidPid = dwVidPid;

                        pNewNode->pNext = g_pXInputDeviceList;

                        g_pXInputDeviceList = pNewNode;

                    }

                }

            }

            SAFE_RELEASE( pDevices[iDevice] );

        }

    }


LCleanup:

    if( bstrNamespace )

        SysFreeString( bstrNamespace );

    if( bstrDeviceID )

        SysFreeString( bstrDeviceID );

    if( bstrClassName )

        SysFreeString( bstrClassName );

    for( iDevice = 0; iDevice < 20; iDevice++ )

    SAFE_RELEASE( pDevices[iDevice] );

    SAFE_RELEASE( pEnumDevices );

    SAFE_RELEASE( pIWbemLocator );

    SAFE_RELEASE( pIWbemServices );


    return hr;

}



//-----------------------------------------------------------------------------

// Returns true if the DirectInput device is also an XInput device.

// Call SetupForIsXInputDevice() before, and CleanupForIsXInputDevice() after

//-----------------------------------------------------------------------------

bool IsXInputDevice( const GUID* pGuidProductFromDirectInput )

{

    // Check each xinput device to see if this device's vid/pid matches

    XINPUT_DEVICE_NODE* pNode = g_pXInputDeviceList;

    while( pNode )

    {

        if( pNode->dwVidPid == pGuidProductFromDirectInput->Data1 )

            return true;

        pNode = pNode->pNext;

    }


    return false;

}



//-----------------------------------------------------------------------------

// Cleanup needed for IsXInputDevice()

//-----------------------------------------------------------------------------

void CleanupForIsXInputDevice()

{

    // Cleanup linked list

    XINPUT_DEVICE_NODE* pNode = g_pXInputDeviceList;

    while( pNode )

    {

        XINPUT_DEVICE_NODE* pDelete = pNode;

        pNode = pNode->pNext;

        SAFE_DELETE( pDelete );

    }

}




//-----------------------------------------------------------------------------

// Name: EnumJoysticksCallback()

// Desc: Called once for each enumerated Joystick. If we find one, create a

//       device interface on it so we can play with it.

//-----------------------------------------------------------------------------

BOOL CALLBACK EnumJoysticksCallback( const DIDEVICEINSTANCE* pdidInstance,

                                     VOID* pContext )

{

    DI_ENUM_CONTEXT* pEnumContext = ( DI_ENUM_CONTEXT* )pContext;

    HRESULT hr;


    if( g_bFilterOutXinputDevices && IsXInputDevice( &pdidInstance->guidProduct ) )

        return DIENUM_CONTINUE;


    // Skip anything other than the perferred Joystick device as defined by the control panel.  

    // Instead you could store all the enumerated Joysticks and let the user pick.

    if( pEnumContext->bPreferredJoyCfgValid &&

        !IsEqualGUID( pdidInstance->guidInstance, pEnumContext->pPreferredJoyCfg->guidInstance ) )

        return DIENUM_CONTINUE;


    // Obtain an interface to the enumerated Joystick.

    hr = g_pDI->CreateDevice( pdidInstance->guidInstance, &g_pJoystick, NULL );


    // If it failed, then we can't use this Joystick. (Maybe the user unplugged

    // it while we were in the middle of enumerating it.)

    if( FAILED( hr ) )

        return DIENUM_CONTINUE;


    // Stop enumeration. Note: we're just taking the first Joystick we get. You

    // could store all the enumerated Joysticks and let the user pick.

    return DIENUM_STOP;

}





//-----------------------------------------------------------------------------

// Name: EnumObjectsCallback()

// Desc: Callback function for enumerating objects (axes, buttons, POVs) on a 

//       Joystick. This function enables user interface elements for objects

//       that are found to exist, and scales axes min/max values.

//-----------------------------------------------------------------------------

BOOL CALLBACK EnumObjectsCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,

                                   VOID* pContext )

{

    HWND hDlg = ( HWND )pContext;


    static int nSliderCount = 0;  // Number of returned slider controls

    static int nPOVCount = 0;     // Number of returned POV controls


    // For axes that are returned, set the DIPROP_RANGE property for the

    // enumerated axis in order to scale min/max values.

    if( pdidoi->dwType & DIDFT_AXIS )

    {

        DIPROPRANGE diprg;

        diprg.diph.dwSize = sizeof( DIPROPRANGE );

        diprg.diph.dwHeaderSize = sizeof( DIPROPHEADER );

        diprg.diph.dwHow = DIPH_BYID;

        diprg.diph.dwObj = pdidoi->dwType; // Specify the enumerated axis

        diprg.lMin = -1000;

        diprg.lMax = +1000;


        // Set the range for the axis

        if( FAILED( g_pJoystick->SetProperty( DIPROP_RANGE, &diprg.diph ) ) )

            return DIENUM_STOP;


    }



    // Set the UI to reflect what objects the Joystick supports

    if( pdidoi->guidType == GUID_XAxis )

    {

        EnableWindow( GetDlgItem( hDlg, IDC_X_AXIS ), TRUE );

        EnableWindow( GetDlgItem( hDlg, IDC_X_AXIS_TEXT ), TRUE );

    }

    if( pdidoi->guidType == GUID_YAxis )

    {

        EnableWindow( GetDlgItem( hDlg, IDC_Y_AXIS ), TRUE );

        EnableWindow( GetDlgItem( hDlg, IDC_Y_AXIS_TEXT ), TRUE );

    }

    if( pdidoi->guidType == GUID_ZAxis )

    {

        EnableWindow( GetDlgItem( hDlg, IDC_Z_AXIS ), TRUE );

        EnableWindow( GetDlgItem( hDlg, IDC_Z_AXIS_TEXT ), TRUE );

    }

    if( pdidoi->guidType == GUID_RxAxis )

    {

        EnableWindow( GetDlgItem( hDlg, IDC_X_ROT ), TRUE );

        EnableWindow( GetDlgItem( hDlg, IDC_X_ROT_TEXT ), TRUE );

    }

    if( pdidoi->guidType == GUID_RyAxis )

    {

        EnableWindow( GetDlgItem( hDlg, IDC_Y_ROT ), TRUE );

        EnableWindow( GetDlgItem( hDlg, IDC_Y_ROT_TEXT ), TRUE );

    }

    if( pdidoi->guidType == GUID_RzAxis )

    {

        EnableWindow( GetDlgItem( hDlg, IDC_Z_ROT ), TRUE );

        EnableWindow( GetDlgItem( hDlg, IDC_Z_ROT_TEXT ), TRUE );

    }

    if( pdidoi->guidType == GUID_Slider )

    {

        switch( nSliderCount++ )

        {

            case 0 :

                EnableWindow( GetDlgItem( hDlg, IDC_SLIDER0 ), TRUE );

                EnableWindow( GetDlgItem( hDlg, IDC_SLIDER0_TEXT ), TRUE );

                break;


            case 1 :

                EnableWindow( GetDlgItem( hDlg, IDC_SLIDER1 ), TRUE );

                EnableWindow( GetDlgItem( hDlg, IDC_SLIDER1_TEXT ), TRUE );

                break;

        }

    }

    if( pdidoi->guidType == GUID_POV )

    {

        switch( nPOVCount++ )

        {

            case 0 :

                EnableWindow( GetDlgItem( hDlg, IDC_POV0 ), TRUE );

                EnableWindow( GetDlgItem( hDlg, IDC_POV0_TEXT ), TRUE );

                break;


            case 1 :

                EnableWindow( GetDlgItem( hDlg, IDC_POV1 ), TRUE );

                EnableWindow( GetDlgItem( hDlg, IDC_POV1_TEXT ), TRUE );

                break;


            case 2 :

                EnableWindow( GetDlgItem( hDlg, IDC_POV2 ), TRUE );

                EnableWindow( GetDlgItem( hDlg, IDC_POV2_TEXT ), TRUE );

                break;


            case 3 :

                EnableWindow( GetDlgItem( hDlg, IDC_POV3 ), TRUE );

                EnableWindow( GetDlgItem( hDlg, IDC_POV3_TEXT ), TRUE );

                break;

        }

    }


    return DIENUM_CONTINUE;

}





//-----------------------------------------------------------------------------

// Name: UpdateInputState()

// Desc: Get the input device's state and display it.

//-----------------------------------------------------------------------------

HRESULT UpdateInputState( HWND hDlg )

{

    HRESULT hr;

    TCHAR strText[512] = {0}; // Device state text

    DIJOYSTATE2 js;           // DInput Joystick state 


    if( NULL == g_pJoystick )

        return S_OK;


    // Poll the device to read the current state

    hr = g_pJoystick->Poll();

    if( FAILED( hr ) )

    {

        // DInput is telling us that the input stream has been

        // interrupted. We aren't tracking any state between polls, so

        // we don't have any special reset that needs to be done. We

        // just re-acquire and try again.

        hr = g_pJoystick->Acquire();

        while( hr == DIERR_INPUTLOST )

            hr = g_pJoystick->Acquire();


        // hr may be DIERR_OTHERAPPHASPRIO or other errors.  This

        // may occur when the app is minimized or in the process of 

        // switching, so just try again later 

        return S_OK;

    }


    // Get the input's device state

    if( FAILED( hr = g_pJoystick->GetDeviceState( sizeof( DIJOYSTATE2 ), &js ) ) )

        return hr; // The device should have been acquired during the Poll()


    // Display Joystick state to dialog


    // Axes

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.lX );

    SetWindowText( GetDlgItem( hDlg, IDC_X_AXIS ), strText );

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.lY );

    SetWindowText( GetDlgItem( hDlg, IDC_Y_AXIS ), strText );

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.lZ );

    SetWindowText( GetDlgItem( hDlg, IDC_Z_AXIS ), strText );

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.lRx );

    SetWindowText( GetDlgItem( hDlg, IDC_X_ROT ), strText );

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.lRy );

    SetWindowText( GetDlgItem( hDlg, IDC_Y_ROT ), strText );

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.lRz );

    SetWindowText( GetDlgItem( hDlg, IDC_Z_ROT ), strText );


    // Slider controls

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.rglSlider[0] );

    SetWindowText( GetDlgItem( hDlg, IDC_SLIDER0 ), strText );

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.rglSlider[1] );

    SetWindowText( GetDlgItem( hDlg, IDC_SLIDER1 ), strText );


    // Points of view

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.rgdwPOV[0] );

    SetWindowText( GetDlgItem( hDlg, IDC_POV0 ), strText );

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.rgdwPOV[1] );

    SetWindowText( GetDlgItem( hDlg, IDC_POV1 ), strText );

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.rgdwPOV[2] );

    SetWindowText( GetDlgItem( hDlg, IDC_POV2 ), strText );

    StringCchPrintf( strText, 512, TEXT( "%ld" ), js.rgdwPOV[3] );

    SetWindowText( GetDlgItem( hDlg, IDC_POV3 ), strText );


	if(IDC_POV3 > 0)

	{

	


	}


    // Fill up text with which buttons are pressed

    StringCchCopy( strText, 512, TEXT( "" ) );

    for( int i = 0; i < 128; i++ )

    {

        if( js.rgbButtons[i] & 0x80 )

        {

            TCHAR sz[128];

            StringCchPrintf( sz, 128, TEXT( "%02d " ), i );

            StringCchCat( strText, 512, sz );

        }

    }


    SetWindowText( GetDlgItem( hDlg, IDC_BUTTONS ), strText );


    return S_OK;

}





//-----------------------------------------------------------------------------

// Name: FreeDirectInput()

// Desc: Initialize the DirectInput variables.

//-----------------------------------------------------------------------------

VOID FreeDirectInput()

{

    // Unacquire the device one last time just in case 

    // the app tried to exit while the device is still acquired.

    if( g_pJoystick )

        g_pJoystick->Unacquire();


    // Release any DirectInput objects.

    SAFE_RELEASE( g_pJoystick );

    SAFE_RELEASE( g_pDI );

}






And my serial program:
#pragma once

#define STRICT

#include <tchar.h>


#include <windows.h>

#include "stdafx.h"






namespace ARMcont {


	using namespace System;

	using namespace System::ComponentModel;

	using namespace System::Collections;

	using namespace System::Windows::Forms;

	using namespace System::Data;

	using namespace System::Drawing;

	using namespace System;

	using namespace System::IO::Ports;



	/// <summary>

	/// Summary for Form1

	/// </summary>

	public ref class Form1 : public System::Windows::Forms::Form

	{

	public:

		Form1(void)

		{

			InitializeComponent();

			//

			//TODO: Add the constructor code here

			//

		}


	protected:

		/// <summary>

		/// Clean up any resources being used.

		/// </summary>

		~Form1()

		{

			if (components)

			{

				delete components;

			}

		}

	private: System::Windows::Forms::Button^  button1;

	protected: 

	private: System::Windows::Forms::Button^  button2;

	private: System::Windows::Forms::Button^  button3;

	private: System::Windows::Forms::Button^  button4;

	private: System::Windows::Forms::Button^  button5;

	private: System::Windows::Forms::Button^  button6;

	private: System::Windows::Forms::Button^  button7;

	private: System::Windows::Forms::Button^  button8;

	private: System::Windows::Forms::Button^  button9;

	private: System::Windows::Forms::Button^  button10;

	private: System::Windows::Forms::Button^  button11;

	private: System::Windows::Forms::Button^  button12;

	private: System::Windows::Forms::Button^  button13;




	private: System::ComponentModel::IContainer^  components;


	private:

		/// <summary>

		/// Required designer variable.

		/// </summary>



#pragma region Windows Form Designer generated code

		/// <summary>

		/// Required method for Designer support - do not modify

		/// the contents of this method with the code editor.

		/// </summary>

		void InitializeComponent(void)

		{

			this->button1 = (gcnew System::Windows::Forms::Button());

			this->button2 = (gcnew System::Windows::Forms::Button());

			this->button3 = (gcnew System::Windows::Forms::Button());

			this->button4 = (gcnew System::Windows::Forms::Button());

			this->button5 = (gcnew System::Windows::Forms::Button());

			this->button6 = (gcnew System::Windows::Forms::Button());

			this->button7 = (gcnew System::Windows::Forms::Button());

			this->button8 = (gcnew System::Windows::Forms::Button());

			this->button9 = (gcnew System::Windows::Forms::Button());

			this->button10 = (gcnew System::Windows::Forms::Button());

			this->button11 = (gcnew System::Windows::Forms::Button());

			this->button12 = (gcnew System::Windows::Forms::Button());

			this->button13 = (gcnew System::Windows::Forms::Button());

			this->SuspendLayout();

			// 

			// button1

			// 

			this->button1->Location = System::Drawing::Point(12, 10);

			this->button1->Name = L"button1";

			this->button1->Size = System::Drawing::Size(103, 32);

			this->button1->TabIndex = 0;

			this->button1->Text = L"Base Left";

			this->button1->UseVisualStyleBackColor = true;

			this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);

			// 

			// button2

			// 

			this->button2->Location = System::Drawing::Point(157, 10);

			this->button2->Name = L"button2";

			this->button2->Size = System::Drawing::Size(103, 32);

			this->button2->TabIndex = 1;

			this->button2->Text = L"Base Right";

			this->button2->UseVisualStyleBackColor = true;

			this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);

			// 

			// button3

			// 

			this->button3->Location = System::Drawing::Point(12, 64);

			this->button3->Name = L"button3";

			this->button3->Size = System::Drawing::Size(103, 32);

			this->button3->TabIndex = 2;

			this->button3->Text = L"Shoulder Left";

			this->button3->UseVisualStyleBackColor = true;

			this->button3->Click += gcnew System::EventHandler(this, &Form1::button3_Click);

			// 

			// button4

			// 

			this->button4->Location = System::Drawing::Point(157, 64);

			this->button4->Name = L"button4";

			this->button4->Size = System::Drawing::Size(103, 32);

			this->button4->TabIndex = 3;

			this->button4->Text = L"Shoulder Right";

			this->button4->UseVisualStyleBackColor = true;

			this->button4->Click += gcnew System::EventHandler(this, &Form1::button4_Click);

			// 

			// button5

			// 

			this->button5->Location = System::Drawing::Point(12, 116);

			this->button5->Name = L"button5";

			this->button5->Size = System::Drawing::Size(103, 32);

			this->button5->TabIndex = 4;

			this->button5->Text = L"Elbow Left";

			this->button5->UseVisualStyleBackColor = true;

			this->button5->Click += gcnew System::EventHandler(this, &Form1::button5_Click);

			// 

			// button6

			// 

			this->button6->Location = System::Drawing::Point(157, 116);

			this->button6->Name = L"button6";

			this->button6->Size = System::Drawing::Size(103, 32);

			this->button6->TabIndex = 5;

			this->button6->Text = L"Elbow Right";

			this->button6->UseVisualStyleBackColor = true;

			this->button6->Click += gcnew System::EventHandler(this, &Form1::button6_Click);

			// 

			// button7

			// 

			this->button7->Location = System::Drawing::Point(12, 173);

			this->button7->Name = L"button7";

			this->button7->Size = System::Drawing::Size(103, 32);

			this->button7->TabIndex = 6;

			this->button7->Text = L"Right Wrist 1";

			this->button7->UseVisualStyleBackColor = true;

			this->button7->Click += gcnew System::EventHandler(this, &Form1::button7_Click);

			// 

			// button8

			// 

			this->button8->Location = System::Drawing::Point(157, 173);

			this->button8->Name = L"button8";

			this->button8->Size = System::Drawing::Size(103, 32);

			this->button8->TabIndex = 7;

			this->button8->Text = L"Right Wrist 2";

			this->button8->UseVisualStyleBackColor = true;

			this->button8->Click += gcnew System::EventHandler(this, &Form1::button8_Click);

			// 

			// button9

			// 

			this->button9->Location = System::Drawing::Point(12, 230);

			this->button9->Name = L"button9";

			this->button9->Size = System::Drawing::Size(103, 32);

			this->button9->TabIndex = 8;

			this->button9->Text = L"Left Wrist 1";

			this->button9->UseVisualStyleBackColor = true;

			this->button9->Click += gcnew System::EventHandler(this, &Form1::button9_Click);

			// 

			// button10

			// 

			this->button10->Location = System::Drawing::Point(157, 230);

			this->button10->Name = L"button10";

			this->button10->Size = System::Drawing::Size(103, 32);

			this->button10->TabIndex = 9;

			this->button10->Text = L"Left Wrist 2";

			this->button10->UseVisualStyleBackColor = true;

			this->button10->Click += gcnew System::EventHandler(this, &Form1::button10_Click);

			// 

			// button11

			// 

			this->button11->Location = System::Drawing::Point(12, 279);

			this->button11->Name = L"button11";

			this->button11->Size = System::Drawing::Size(103, 32);

			this->button11->TabIndex = 10;

			this->button11->Text = L"Gripper Open";

			this->button11->UseVisualStyleBackColor = true;

			this->button11->Click += gcnew System::EventHandler(this, &Form1::button11_Click);

			// 

			// button12

			// 

			this->button12->Location = System::Drawing::Point(157, 279);

			this->button12->Name = L"button12";

			this->button12->Size = System::Drawing::Size(103, 32);

			this->button12->TabIndex = 11;

			this->button12->Text = L"Gripper Close";

			this->button12->UseVisualStyleBackColor = true;

			this->button12->Click += gcnew System::EventHandler(this, &Form1::button12_Click);

			// 

			// button13

			// 

			this->button13->Location = System::Drawing::Point(19, 331);

			this->button13->Name = L"button13";

			this->button13->Size = System::Drawing::Size(95, 32);

			this->button13->TabIndex = 12;

			this->button13->Text = L"button13";

			this->button13->UseVisualStyleBackColor = true;

			this->button13->Click += gcnew System::EventHandler(this, &Form1::button13_Click);

			// 

			// Form1

			// 

			this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);

			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;

			this->ClientSize = System::Drawing::Size(284, 379);

			this->Controls->Add(this->button13);

			this->Controls->Add(this->button12);

			this->Controls->Add(this->button11);

			this->Controls->Add(this->button10);

			this->Controls->Add(this->button9);

			this->Controls->Add(this->button8);

			this->Controls->Add(this->button7);

			this->Controls->Add(this->button6);

			this->Controls->Add(this->button5);

			this->Controls->Add(this->button4);

			this->Controls->Add(this->button3);

			this->Controls->Add(this->button2);

			this->Controls->Add(this->button1);

			this->Name = L"Form1";

			this->Text = L"Form1";

			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);

			this->ResumeLayout(false);


		}

#pragma endregion

	private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

	

				SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,-100,0,0,0,0,0,0 \r");


				_serialPort->Close();


			 

			 

			 }

private: System::Void button13_Click(System::Object^  sender, System::EventArgs^  e) {

		 }

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {

			 	SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,100,0,0,0,0,0,0 \r");


				_serialPort->Close();

		 }

private: System::Void button3_Click(System::Object^  sender, System::EventArgs^  e) {

			 	SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,-100,0,0,0,0,0 \r");


				_serialPort->Close();

		 }

private: System::Void button4_Click(System::Object^  sender, System::EventArgs^  e) {

			 SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,100,0,0,0,0,0 \r");


				_serialPort->Close();

		 }

private: System::Void button5_Click(System::Object^  sender, System::EventArgs^  e) {

			 SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,0,-100,0,0,0,0 \r");


				_serialPort->Close();

		 }

private: System::Void button6_Click(System::Object^  sender, System::EventArgs^  e) {

			 SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,0,100,0,0,0,0 \r");


				_serialPort->Close();

		 }

private: System::Void button7_Click(System::Object^  sender, System::EventArgs^  e) {

			 SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,0,0,-100,0,0,0 \r");


				_serialPort->Close();

		 }

private: System::Void button8_Click(System::Object^  sender, System::EventArgs^  e) {

			 SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,0,0,100,0,0,0 \r");


				_serialPort->Close();

		 }

private: System::Void button9_Click(System::Object^  sender, System::EventArgs^  e) {

			 SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,0,0,-100,0,0,0 \r");


				_serialPort->Close();

		 }

private: System::Void button10_Click(System::Object^  sender, System::EventArgs^  e) {

			 SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,0,0,0,100,0,0 \r");


				_serialPort->Close();

		 }

private: System::Void button11_Click(System::Object^  sender, System::EventArgs^  e) {

			 SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,0,0,0,0,-100,0 \r");


				_serialPort->Close();

		 }

private: System::Void button12_Click(System::Object^  sender, System::EventArgs^  e) {

			 SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,0,0,0,0,100,0 \r");


				_serialPort->Close();

		 }

private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

		 }

};

}


//////   @STEP 232,00,0,0,0,0,0,0   ///////

I noticed that the second is form1.h while the first is joystick.cpp. Why cant I just pull out:
using namespace System;

	using namespace System::IO::Ports;


and 


SerialPort^ _serialPort;

					

				_serialPort = gcnew SerialPort();


				_serialPort->Open();


				_serialPort->Write("@STEP 232,0,0,0,0,0,100,0 \r");


				_serialPort->Close();


from form1.h and put it into joystick.cpp?

I understand that I would need some if statement. Something like if("the value of a button is over 1") {send this command to the robot}

Edited by arthur92710, 07 July 2010 - 07:48 PM.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users