Skip to content

Instantly share code, notes, and snippets.

@troygnichols
Last active October 29, 2015 17:59
Show Gist options
  • Select an option

  • Save troygnichols/677ed073b68928c6f0df to your computer and use it in GitHub Desktop.

Select an option

Save troygnichols/677ed073b68928c6f0df to your computer and use it in GitHub Desktop.
Uses the hidapi library to read analog stick inputs from a Logitech Dual Action USB controller
#include <stdio.h>
#include <stdlib.h>
#include <hidapi.h>
#include <signal.h>
void printctrl(unsigned char * buffer);
signed short throttle(unsigned char *byte);
void cleanup(int signum);
int main(void) {
signal(SIGINT, cleanup);
// Find the "Logitech Dual Action" device
int res;
hid_device *device_handle;
unsigned short vendor_id = 0x046d;
unsigned short product_id = 0xc216;
unsigned char buffer[8];
res = hid_init();
if (res != 0) {
fprintf(stderr, "Could not init hidapi, status: %s\n", res);
}
device_handle = hid_open(vendor_id, product_id, NULL);
if (device_handle) {
puts("Found USB controller");
} else {
fprintf(stderr, "USB controller not found: %s\n", device_handle);
exit(1);
}
while (1) {
res = hid_read(device_handle, buffer, sizeof(buffer));
if (res < 0) {
fprintf(stderr, "hid_read returned error code %d\n", res);
exit(1);
}
printctrl(buffer);
}
return 0;
}
void printctrl(unsigned char *buffer) {
int i;
printf("Throttle L: %d\t R: %d",
throttle(&buffer[1]),
throttle(&buffer[3]));
printf("\n");
}
/**
* Scale values from 0-255 to be "throttle" values, e.g.
*
* Full power reverse: -100 (0)
* Full power forward: 100 (255)
* No power: 0 (128)
*/
signed short throttle(unsigned char * byte) {
return -(((unsigned short) *byte - 128) / 1.28);
}
void cleanup(int signum) {
printf("\nCaught signal %d\n", signum);
hid_exit();
exit(signum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment