f0ff

Untitled

Dec 5th, 2021
1,018
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <ps2_Keyboard.h>
  2. #include <ps2_NeutralTranslator.h>
  3. #include <ps2_NullDiagnostics.h>
  4. #include <Wire.h>
  5.  
  6. #define KBD_PIN_CLOCK PIN_PD2
  7. #define KBD_PIN_DATA PIN_PD3
  8. #define BUFFER_SIZE 16  // Max size is 16 entires (32 bytes), as the I2C library supports up to 32 bytes in a transaction
  9. #define I2C_ADDRESS 8
  10.  
  11. using namespace ps2;
  12.  
  13. typedef NullDiagnostics Diagnostics;
  14. static Diagnostics diagnostics;
  15. static Keyboard<KBD_PIN_DATA, KBD_PIN_CLOCK, 4, Diagnostics> ps2Keyboard(diagnostics);
  16. static NeutralTranslator neutralTranslator;
  17. static KeyboardLeds lastLedSent = ps2::KeyboardLeds::numLock;
  18.  
  19. byte buffer[BUFFER_SIZE*2];
  20. uint8_t buffer_len = 0;
  21.  
  22. void send_buffer() {
  23.   if (buffer_len < 1)
  24.     return;
  25.  
  26.   Wire.write(buffer, buffer_len*2);
  27.   buffer_len = 0;  // Don't worry about resetting the buffer
  28. }
  29.  
  30. void setup() {
  31.   ps2Keyboard.begin();
  32.   ps2Keyboard.reset();
  33.   ps2Keyboard.awaitStartup();
  34.  
  35.   ps2Keyboard.setScanCodeSet(ScanCodeSet::ps2);
  36.   ps2Keyboard.disableBreakAndTypematic();
  37.   ps2Keyboard.sendLedStatus(KeyboardLeds::numLock);
  38.  
  39.   Wire.begin(I2C_ADDRESS);
  40.   Wire.onRequest(send_buffer);
  41. }
  42.  
  43. void loop() {
  44.   ps2::KeyboardOutput scanCode = ps2Keyboard.readScanCode();
  45.   switch (scanCode) {
  46.     case KeyboardOutput::garbled:
  47.       neutralTranslator.reset();
  48.       break;
  49.     default:
  50.       uint16_t key = neutralTranslator.translatePs2Keycode(scanCode);
  51.  
  52.       // Add to buffer
  53.       if (buffer_len >= BUFFER_SIZE)
  54.         return;  // Drop if ran out of space in the buffer
  55.      
  56.       buffer[buffer_len*2] = (byte) key >> 8;    // Modifiers - top 8 bits
  57.       buffer[buffer_len*2+1] = (byte) key;         // Key - lower 8 bits
  58.       buffer_len++;
  59.   }
  60. }
RAW Paste Data