KPAD Library Overview

Introduction

The KPAD library is a high-level abstraction for the Wii remote controller and its extensions. Whereas the low-level WPAD library manages the logical functions and communication channels of the Wii remote, the KPAD library interprets the raw sensor data into meaningful events for applications.

Initialization

The KPAD library is initialized with either the KPADInit or KPADInitEx functions, one of which must be called before any other KPAD API.

KPADInit and KPADInitEx are similar, but the latter allows for an extra ring buffer to be used to augment KPAD internal processing. This allows for longer intervals before reading the data using KPADRead or KPADReadEx. The internal buffer size provided by the library is of length KPAD_RING_BUFS (currently equal to 16), and allows for queuing for each controller of KPAD_RING_BUFS samples.

KPADInitEx(NULL,0) is equivalent to KPADInit.

We recommend that you use the KPADInitEx function for future development of applications.

NOTE:
Wii U Bluetooth devices will stay connected through system restarts and process switches but only if the time that the library is stopped is less than 10 seconds. For this reason, KPAD initialization should be done early in the boot up process.

Pairing

For devices to communicate with the Wii U console, both the Wii U console and the device must first be registered with each other. This registration process is called pairing.

Paired device count

The Wii U retains up to ten Bluetooth controllers. If more devices are paired, the controller that has not been connected in the longest time is unpaired to make room for the new controller. The exception to this rule is the Wii U balance controller. It is never unpaired unless another Wii U balance controller is paired, in which case the new balance controller information replaces the older one.

Pairing APIs

Pairing can be started by pushing the SYNC Button on the front of the Wii U console, or programmatically by using the WPADStartSyncDevice function to start the pairing process on the console. Also, WPADSetSyncDeviceCallback is used to get a notification that the user has pressed the SYNC Button on the console, and when registration is completed.

Connecting Controllers and Controller Status

Connection callback

To receive a notification that a controller has been connected or disconnected, use the KPADSetConnectCallback function to register a callback function in advance; this registration is usually done just after KPADInit/KPADInitEx. After a controller connection, game applications should start polling or register a sampling callback to determine the correct controller type, which may take over a second to occur.

Other than connections and disconnections, the device type may also change due to the addition or removal of extensions like the MotionPlus extension, the Freestyle extension, or the Classic Controller extension. You can use polling or sampling callbacks to detect these changes. For information, see Reading Controller Data below.

Time to initialize

The KPAD connection callback occurs before the complete controller capabilities and extensions are known, and all controllers are initially reported as device type WPAD_DEV_CORE. After the initial connection, while the library determines the controller configuration, the device type may be reported as WPAD_DEV_UNKNOWN. Following verification, the library may report a device type value such as WPAD_DEV_FREESTYLE or WPAD_DEV_CLASSIC, depending on the type.

It is recommended that the game application ignore the initial transient controller types reported for a short while after a connection before notifying the user to change the controller configuration, for example, to attach a Freestyle extension.

Disconnecting

A controller can be disconnected by calling WPADDisconnect with the appropriate channel parameter.

An inactive controller is automatically disconnected after a period of non-use. The default disconnect time is five minutes, but this can be set using WPADSetAutoSleepTime function.

See Also

The WPADGetInfo and WPADGetInfoAsync functions can also be called to get the current information about the controller (remaining battery power, Player LED status, and so on).

Reading Controller Data

KPADRead and KPADReadEx

KPADRead and KPADReadEx are used to read the latest controller data and status.

The KPAD library uses a ring buffer to store the Wii remote input data for the internal processing of each channel in turn. A buffer of length KPAD_RING_BUFS (or possibly larger if KPADInitEx was used) is maintained for this purpose. The contents of this ring buffer are flushed every time KPADRead or KPADReadEx is called.

The KPADRead function returns the number of sets of sampling data, or zero if there are none. The KPADReadEx function also returns the WPAD error code (via a pointer variable argument) in addition to the KPADRead values. This error code can also be obtained from WPADProbe, but be aware that the values are not synchronized. Also note that this error code has a different meaning than the error code in the KPADStatus structure.

Even when the KPADRead function returns zero, there is a possibility that the contents of the sampling buffer passed to it as an argument have changed. There is also a chance that the KPADReadEx function will change the sampling buffer's contents, but if and only if KPAD_READ_ERR_NO_DATA is returned, then the contents at the start of the sampling buffer have not changed.

We recommend that you use the KPADReadEx function for future development of applications.

NOTE:
When the KPADRead or KPADReadEx functions are called, the ring buffer inside the KPAD library is flushed. For this reason, if data will be used by multiple threads, we recommend that you use a single thread and share the loaded data, rather than calling functions from multiple threads.

When the functions are called multiple times, they will return zero when they fail to gain processing rights. The KPADReadEx function will also return the error code KPAD_READ_ERR_LOCKED.

Using a Sampling Callback

Applications can register a sampling callback to receive a notification every time new controller data is received (roughly every 5 milliseconds) using KPADSetSamplingCallback. In the sampling callback, KPADRead or KPADReadEx can be used to read both the controller status (to determine the controller device type and data format), and the controller data.

Be aware that the callback registered through this function will not be released unless you either release it by specifying NULL for this function's argument or call the KPADShutdown function. Controller connection/disconnection will not release the callback.

Polling

Applications can obtain the controller status and HID data by periodically calling the KPADRead or KPADReadEx functions. The data obtained is only valid if there is valid controller data to read; if the return value of these functions is other than WPAD_READ_ERR_NONE then the data is invalid and KPADRead/KPADReadEx should be called again in a short time.

WPADProbe can also be used to read only the controller device type, and not the HID data.

NOTE:
If the data is not read often enough, it will be lost. If the default sample buffer size is used (for example, when using KPADInit or KPADInitEx(NULL,0)), the data needs to be read at least every 16 * 5ms = 80ms to prevent data loss.

Adjusting Controller Information

The controller information to be read may be adjusted by calling the following functions beforehand:

Shutting Down KPAD

To shutdown the KPAD library, the following steps are required:

Other Notes

KPADReset

In some cases, it might be effective to call the KPADReset function, such as during a change in scenes. However, because the KPADReset function will have an ill effect on button trigger processing, avoid calling the function where possible. It does not also need to be called when swapping external extension controllers.

Differences in Coordinate Systems

The coordinate system of the coordinates obtained with the KPAD library is different from that used in the WPAD library. For more information, see the KPADStatus and KPADEXStatus structure pages.

Effects of Signal Interference

Because the Wii U console and Wii remote use wireless communication, poor signal conditions in the surrounding area can cause signal interference, and the Wii U console may not be able to receive data from the Wii remote. If these conditions persist, the KPADRead function may return zero. Even in these circumstances the Wii U console and Wii remote maintain their connection status, so do not determine their connection status from the return value of this function. To determine connection status, use the WPADProbe or WPADSetConnectCallback function. It is also possible to use the return value of the KPADReadEx function. KPAD_READ_ERR_NO_DATA is used as the return value when data cannot be received. KPAD_READ_ERR_NO_CONTROLLER is used as the return value when not connected.

Wii MotionPlus

Overview

The sensors used in the Wii MotionPlus are rate sensors (gyroscopes). These rate sensors can get the angular velocity around the axes for pitch, yaw, and roll. The values for each axis are stored in the KPADMPStatus structure and obtained with the KPADRead function. The KPADMPStatus structure has the members mpls, angle, and dir. The first two are defined as type Vec. The Vec type direction components are as follows: x is the pitch, y is the yaw, and z is the roll. The mpls member represents the angular velocity in each direction and stores a value where 1.0 corresponds to 360 dps (degrees per second). The angle member represents the angle in each direction and stores a value where 1.0 corresponds to 360 degrees. The dir member represents the 3D attitude expressed as a 3x3 matrix.

See Wii MotionPlus for more detailed information on the Wii MotionPlus.

Starting and Stopping the Wii MotionPlus

The Wii MotionPlus does not start immediately after it is plugged into the Wii remote. Start the Wii MotionPlus by sending it the start command. Start and stop the Wii MotionPlus using the KPADEnableMpls and KPADDisableMpls functions, respectively. When these functions are called, the KPAD library checks the device's current state against the specified state and operates to bring about the specified state. If the state is not the specified state (for example, the Wii MotionPlus is not attached), then the function continues to send a startup command until the specified state comes into being. In addition, if you register a callback ahead of time using the KPADSetControlMplsCallback function, the following notifications are used: KPAD_STATE_CTRL_MPLS_START is sent when processing to start or stop the Wii MotionPlus is started, and KPAD_STATE_CTRL_MPLS_FINISHED is sent when processing is finished. If an error occurs during processing, a KPAD_STATE_CTRL_MPLS_FAILED_STD, KPAD_STATE_CTRL_MPLS_FAILED_FS, or KPAD_STATE_CTRL_FAILED_CL notification is sent, depending on the state passed to the KPADEnableMpls function. In addition to registering callbacks, you can also directly check the state of the Cafe MotionPlus using the KPADGetMplsStatus function.

To prevent MotionPlus from interfering with non-MotionPlus controllers (e.g. WBC, URCC), you should only enable MotionPlus if the controller supports MotionPlus. A good way to do this is to set a WPADIsMplsAttached callback function from within the connection callback, and let your "myMplsAttachedCallback" function catch the result. When your "myMplsIsAttachedCallback" is called, and if MotionPlus is attached, then enable MotionPlus at that time.

The only case where you will need to disable MotionPlus is if the MotionPlus extension is removed from a connected Wii remote. You can detect this case by registering a KPADSetControlMplsCallback function. If the callback function is called with a reason of FAIL, then MotionPlus is not working with the current controller, and KPADDisableMpls should be called.

For example, suppose you pass WPAD_MPLS_FS to the KPADEnableMpls function and call it while the Wii MotionPlus is running in normal mode. A KPAD_STATE_CTRL_MPLS_START notification is issued, and a Wii MotionPlus mode change is initiated because the current state (WPAD_MPLS_STD) differs from the specified state (WPAD_MPLS_FS). Because the Wii MotionPlus must be temporarily stopped when switching between normal mode and extension mode, the KPAD library first stops the Wii MotionPlus. Note that the device type obtained by the WPADProbe function at this point is WPAD_DEV_CORE. After the Wii MotionPlus has stopped, the Cafe MotionPlus can be started in extension mode. Unless the state specified in the KPADEnableMpls or KPADDisableMpls function is changed, the KPAD library performs this entire series of operations.

Detecting if MotionPlus has been attached or detached

Currently, adding a MotionPlus extension to a connected Wii remote is not automatically detected, either as change in the device type, via a connection callback, or via an extension callback. (It is detected correctly if the extension is present at the time of connection.) If your application requires MotionPlus and the controller does not have the extension, you should periodically poll the state using the WPADIsMplsAttached function and callback. After the MotionPlus extension is attached, KPADEnableMpls can be called.

Wii MotionPlus Startup and the Wii remote Speaker

To output audio from the Wii remote speaker, audio output commands are sent to the Wii remote. This process can be affected by processes sending other commands. This does not happen except when commands are being sent frequently. Note that because the KPADEnableMpls function sends the startup command to the Wii MotionPlus until a specified condition is met, the Wii remote speaker cannot output audio if the Wii MotionPlus is detached while this function is called.

HOME Menu

In some cases the HOME Menu outputs audio from the Wii remote speaker. If the HOME Menu is started and the Wii MotionPlus is detached while the KPADEnableMpls function is called, the Wii remote speaker cannot output audio. You can avoid this problem by stopping the Wii MotionPlus when the HOME Menu is started.

Work Area for Wii MotionPlus Data Processing

A dedicated work area is required for the KPAD library to process Wii MotionPlus data. Be sure to first set the work area using the KPADSetMplsWorkarea function if the KPAD library will be processing data. To get the amount of memory making up the work area, use the KPADGetMplsWorkSize function.

To deallocate the work area specified by the KPADSetMplsWorkarea function, pass NULL to the function. Memory is destroyed if the work area is deallocated while even one Wii MotionPlus is operating, so do not deallocate the work area at such times. Before deallocation, verify that Wii MotionPlus is not operating on any Wii remote.

Wii MotionPlus Calibration Settings

The Wii MotionPlus hardware maintains calibration values set during a constant-speed rotation and calibration values set at the zero point. However, it is necessary to reset the zero point as quickly as possible after startup because there is a possibility that the zero point after actual startup may differ from the calibrated value. The KPAD library therefore starts the calibration process after the Wii MotionPlus starts. The calibration process completes by momentarily stilling all motion of the Wii MotionPlus. Note that the calibration process does not complete if you keep moving the Wii MotionPlus.

We strongly recommend that you use Wii MotionPlus information after the calibration process completes.

The calibration process can be started at any time using the KPADStartMplsCalibration function.

Getting Wii MotionPlus Data

Using the KPADRead function, the specified channel's Wii MotionPlus status is read into a KPADMPStatus structure, a member of the KPADStatus structure. The KPADRead function processes the WPADMPStatus structure in the order received and updates each member of the WPADMPStatus structure. Note that attitude correction using acceleration and DPD is performed only on the latest status.

Considering Error Accumulation

Because attitude and angle are calculated based on angular velocity, when the Wii MotionPlus accessory is used for long periods of time, errors in angular velocity can accumulate, and discrepancies in attitude and angle become greater. Attitude can be corrected with the KPAD library. If you disable any of the types of correction, you must use the KPADSetMplsDirection function to reset those uncorrected attitude elements to appropriate values. The angle cannot be corrected with the KPAD library, so you must use the KPADSetMplsAngle function to reset it to an appropriate value.

Correction Processing

The KPAD library can perform the following corrections on Wii MotionPlus data.

Excluding zero-point drift correction, these correction processes can each be freely enabled or disabled. (Zero-point drift correction is always enabled.) Parameters can be used to adjust the degree of drift correction.

Zero-Point Play Tolerance

If this feature is enabled, the system does not respond to small movements. This feature is effective in situations, for example, where you want to capture only large movements in a particular direction. Specifically, there is no response to motion smaller than radius, specified by the KPADSetMplsZeroPlayParam function. The closer the current angular velocity is to the specified radius, the closer to zero the return value of the KPADIsEnableMplsZeroPlay function becomes.

Zero-Point Drift Correction

The zero point may drift due to effects such as temperature while the Wii MotionPlus is in use. This correction process works by first determining whether the Cafe MotionPlus is stationary. This is performed by checking whether the Wii MotionPlus continues to return the same value for some interval of time. If the device is deemed to be stationary, the zero point is corrected to reflect the value. Also, three types of determination criteria have been prepared. Any one of these may be applied. The zero point is constantly corrected based on information such as how well current acceleration and past angular acceleration being buffered internally fit in the specified determination criteria. Get information regarding how well data fits from the return value of the KPADIsEnableMplsZeroDrift function. The closer the value is to 1, the better the fit. You can also assume that the closer to 1, the more stable the motion.

NOTE:
Because this type of processing is performed, this correction may also be performed unintentionally during constant, uniform motion. Be sure to consider this issue in scenes that request precise movements from the player. In such scenes, this issue can be addressed either by making stricter determination criteria or by setting up a play tolerance around the zero point.
NOTE:
The zero-point of the accelerometer built into the Wii U GamePad and Wii Remote controllers can accumulate a drift of up to ±0.13G over time (approximately up to 12 degrees in angle). For this reason, be sure that there is no problem even with the drift of 0.13G when using at-rest determination or small changes in attitude information in the application. For example, make allowances for an input play tolerance of 0.13G in your application, or prepare modes with such a feature.

Attitude Correction for the Base Attitude

By configuring a certain attitude as the base attitude, even vigorous swinging that cannot be handled by other correction processing stops causing the attitude to shift far from the base attitude. For example, this correction can be used when swinging a sword to set the ready stance as the base attitude.

Attitude Correction Using Acceleration

When this compensation is enabled, correction is applied using an acceleration value in cases where the acceleration obtained from the accelerometer fits inside the range given by the force of gravity plus revise_range, specified by the KPADSetMplsAccReviseParam function.

Attitude Correction Using the DPD

If you enable this feature, correction processing is applied whenever the DPD detects and maintains sight of an object. Although this feature can apply precise corrections for the yaw and roll axes, corrections cannot be applied to the pitch axis because the position of the sensor bar differs by environment.

NOTE:
In some cases, at-rest noise occurs on the Wii Remote that is larger than the standard margin of error (roughly 0.02G). When this noise occurs, the system may behave as though the Wii Remote has received acceleration input even though it is at rest. The noise occurs randomly and ranges from approximately 0.04G to 0.1G. When handling small acceleration values within the application, consider using a workaround that either rounds down inputs of less than approximately 0.1G (when considering a margin, we recommend approximately 0.13G) or providing a mode that would perform this rounding-down and could be enabled by the user when the symptoms occur. Adjust the cut-off value as necessary, be aware of its effects on sensitivity and gameplay in your title. In addition, the at-rest noise from the Wii U GamePad is used as an approximate standard by which to measure the margin of error.

Temperature Drift and Integration Error

You can expect some degree of improvement in temperature drift when using the zero-point drift correction process. In addition, you should be able to mitigate drift to a certain degree by: correcting acceleration and DPD before the error becomes too large, and setting the base model beforehand for scenes in which motions are so small that these corrections are not triggered.

Calibration Value Errors

As stated in the specifications for Wii MotionPlus rate sensors, the scale value for the written calibration values can vary by as much as ±8 percent due to the effects of humidity, air temperature, and device age. This error cannot be mitigated by the KPAD library. When designing for the Wii MotionPlus, therefore, do not attempt to require an exact degree of accuracy.

When the KPADSetMplsMagnification function operates internally to calculate angular speed, you can set a different scaling factor for each direction of motion. Because you can use this function to evaluate the effect that these errors in attitude and angle will actually have on calculations, use it when verifying that your game can be played within the range of error.

Determining Whether the Wii Remote Is at Rest

The following figure illustrates one of the algorithms used to determine whether the Wii Remote is at rest.

The following sections detail the conditions shown in the preceding figure that are used to determine whether the Wii Remote is at rest.

IS THE VARIATION SMALL?

To use variation in accelerometer readings that is "acc" element of KPADStatus as a condition for determining whether the Wii Remote is at rest, at-rest accelerometer noise must also be considered. Controller acceleration in each coordinate direction (axis) includes measurement error of up to ±0.13G due to at-rest noise. The actual accelerometer readings should not change if the Wii Remote is at rest, so the maximum possible error when comparing values sampled from the accelerometer is ±0.26 G. Therefore, the Wii Remote is determined to be at rest if the difference between consecutive readings from the accelerometer is less than ±0.26 G.

IS IT STABLE ENOUGH?

After the Wii Remote is in the at-rest state described above for a certain continuous period of time, the overall at-rest determination is successful. The actual threshold for this period of time can be configured individually as appropriate for the game application at hand.

TIMEOUT?

The at-rest determination algorithm times out if the Wii Remote does not continuously remain in the at-rest state for the prescribed period of time. Without this timeout, the application could get stuck running the at-rest determination process indefinitely until it succeeds. Icon For more information on at-rest noise in the Wii Remote accelerometer, see "At-Rest Noise from Wii Remote" in the Wii U Guidelines.

The following figure shows the acceleration values sampled in each coordinate direction.

Classic Controller and Classic Controller Pro

The Classic Controller and the Classic Controller Pro have different shapes for the left and right analog buttons. The quantity of analog input also differs. However, the Classic Controller Pro is recognized as a regular Classic Controller when it is attached to the Wii remote, so applications cannot distinguish between the two.

For this reason, L and R analog button input is not allowed and always returns zero.Also, it is harder to send input from the L Button and the R Button of the Classic Controller than from the Classic Controller Pro because the buttons must be pressed down. Now, even partially pressing the L Button or the R Button is recognized as button input.

Revision History

2014/02/19 Added a description about Zero-Point Drift Correction.
2014/02/19 Added a description about at-rest noise on Wii remote.
2014/01/23 Terminology fix.
2013/05/08 Automated cleanup pass.
2012/06/27 Removed references to WPADRegisterAllocator.
2012/03/03 DRAFT.


CONFIDENTIAL