对于 Leonardo 来说,最大的特点就是可以直接模拟USB键盘鼠标。
一般来说,当我们需要发送某一个按键的时候可以直接使用Keyboard.print(‘a’)这样的方式,或者在Keyboard.h 中找到定义好的键值,比如:#define KEY_F1 0xC2。
我最近遇到一个问题:这个文件中定义的键值我无法在其他资料上找到,让人非常恼火,例如:没有一份资料上说 CAPS LOCK值为0xC1,但是使用Keyboard.h中定义的 #define KEY_CAPS_LOCK 0xC1 确实是好用的。最后才想起来应该去看一下对应的代码(开源的优点)。最终,找到的代码如下:
[mw_shl_code=applescript,true]size_t Keyboard_::press(uint8_t k)
{
uint8_t i;
if (k >= 136) { // it's a non-printing key (not a modifier)
k = k - 136;
} else if (k >= 128) { // it's a modifier key
_keyReport.modifiers |= (1<<(k-128));
k = 0;
} else { // it's a printing key
k = pgm_read_byte(_asciimap + k);
if (!k) {
setWriteError();
return 0;
}
if (k & 0x80) { // it's a capital letter or other character reached with shift
_keyReport.modifiers |= 0x02; // the left shift modifier
k &= 0x7F;
}
}
// Add k to the key report only if it's not already present
// and if there is an empty slot.
if (_keyReport.keys[0] != k && _keyReport.keys[1] != k &&
_keyReport.keys[2] != k && _keyReport.keys[3] != k &&
_keyReport.keys[4] != k && _keyReport.keys[5] != k) {
for (i=0; i<6; i++) {
if (_keyReport.keys == 0x00) {
_keyReport.keys = k;
break;
}
}
if (i == 6) {
setWriteError();
return 0;
}
}
sendReport(&_keyReport);
return 1;
}
[/mw_shl_code]
就是说,当我们使用KEY_CAPS_LOCK ==0xC1,会先有一个 193-136=57的动作,最后发送出去的实际上是 57(0x39),在USB HID Usage Tables 有下面的定义:
同样的文档中我们可以查到 Scroll Lock == 71(0x47) Num Lock == 83 (0x53)。于是,定义如下:
#define KEY_SCROLL_LOCK 0xCF #define KEY_NUM_LOCK 0xDB 最终,我们编写一个代码,能让键盘上的三个LED逐次亮灭
[mw_shl_code=applescript,true] #include "Keyboard.h"
#define KEY_SCROLL_LOCK 0xCF
#define KEY_NUM_LOCK 0xDB
void setup() {
pinMode(A0, INPUT_PULLUP);
Keyboard.begin();
while (digitalRead(A0) == HIGH) {
// do nothing until pin 2 goes low
delay(500);
}
}
void loop() {
Keyboard.write(KEY_NUM_LOCK);
Keyboard.releaseAll();
delay(1000);
Keyboard.write(KEY_NUM_LOCK);
Keyboard.releaseAll();
delay(1000);
Keyboard.write(KEY_CAPS_LOCK);
Keyboard.releaseAll();
delay(1000);
Keyboard.write(KEY_CAPS_LOCK);
Keyboard.releaseAll();
delay(1000);
Keyboard.write(KEY_SCROLL_LOCK);
Keyboard.releaseAll();
delay(1000);
Keyboard.write(KEY_SCROLL_LOCK);
Keyboard.releaseAll();
delay(1000);
}
[/mw_shl_code]
|