1
0

hidfifo.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * HID fifo library
  3. * Contains fifo (circular buffer) for HID input codes
  4. * Initially created for keyboard codes, but SNES controller codes could also be used
  5. * (although SNES is not supported anymore, an USB controller could also work for this)
  6. *
  7. * USAGE:
  8. * - Use HID_FifoWrite in interrupt handler for input device
  9. * - Check for key in main loop using HID_FifoAvailable
  10. * - If available, read using HID_FifoRead
  11. */
  12. #define HID_FIFO_SIZE 0x20
  13. word hidfifo[HID_FIFO_SIZE];
  14. word hidreadIdx = 0;
  15. word hidwriteIdx = 0;
  16. word hidbufSize = 0;
  17. void HID_FifoWrite(word c)
  18. {
  19. // We do not want to write null values
  20. if (c == 0)
  21. return;
  22. if (hidbufSize == HID_FIFO_SIZE)
  23. {
  24. uprintln("E: HID Buffer full");
  25. return;
  26. }
  27. word *p_hidfifo = hidfifo;
  28. *(p_hidfifo+hidwriteIdx) = c;
  29. hidbufSize++; // Increase buffer size after writing
  30. hidwriteIdx++; // Increase hidwriteIdx position to prepare for next write
  31. // If at last index in buffer, set hidwriteIdx back to 0
  32. if (hidwriteIdx == HID_FIFO_SIZE)
  33. hidwriteIdx = 0;
  34. }
  35. word HID_FifoAvailable()
  36. {
  37. return (hidbufSize != 0);
  38. }
  39. word HID_FifoRead()
  40. {
  41. // Check if buffer is empty
  42. if (hidbufSize == 0)
  43. {
  44. uprintln("E: HID Buffer empty");
  45. return 0;
  46. }
  47. word *p_hidfifo = hidfifo;
  48. word retval = *(hidfifo+hidreadIdx);
  49. hidbufSize--; // Decrease buffer size after reading
  50. hidreadIdx++; // Increase hidreadIdx position to prepare for next read
  51. // If at last index in buffer, set hidreadIdx back to 0
  52. if (hidreadIdx == HID_FIFO_SIZE)
  53. hidreadIdx = 0;
  54. return retval;
  55. }