[SOLVED] [0.6.0.rc2] Keyboard.press() - how to?

@avtolstoy, seeing we are on a run with my testing… can you quickly assist here:

I want to sent a Control A via the USB keyboard interface. I would have thought that the following should work, but it doesn’t:

#include "spark_wiring_usbkeyboard_scancode.h"

Keyboard.press(‘a’); // MUST be lower case

Thanks! Harry

(There is no need to include spark_wiring_usbkeyboard_scancode.h)

If you take a look at PR #1110 (since we don’t have the docs up yet), it says:

Keyboard.write() uses ASCII map to press appropriate keyboard buttons, see https://github.com/spark/firmware/blob/8870980a4bfcaae30823cff27a0cee85ab52d379/wiring/src/spark_wiring_usbkeyboard.cpp#L33

Keyboard.writeKey(), Keyboard.press(), Keyboard.release() and Keyboard.click() use keycodes and modifier codes defined in UsbKeyboardScanCode and UsbKeyboardModifier, see https://github.com/spark/firmware/blob/8870980a4bfcaae30823cff27a0cee85ab52d379/wiring/inc/spark_wiring_usbkeyboard_scancode.h

So, you cannot use press() with ASCII characters, you have to use keycodes and modifiers. The only functions that can be used with ASCII characters are write() which behaves like click() but takes ASCII chars and maps them to keycodes, and print()/println() etc which behave also like click() but take a string and click all the keys consecutively. (Calling Keyboard.print("Hello"); would click SHIFT+h, e, l, l, o consecutively)

There are several ways to achieve what you need:

1. Click both a key and a modifier (CTRL) at the same time. There. Done. That's it. :)

    Keyboard.click(KEY_A, MOD_LEFTCTRL);

2. Press CTRL, press A, release

    Keyboard.release(KEY_LEFTCTRL); // or just Keyboard.releaseAll();

3. Press CTRL, print 'a', release

    Keyboard.print('a'); // or Keyboard.write('a');
1 Like

@avtolstoy, that’s what I get for jumping ahead of the documentation!

Didn’t even know about .click()

Was confused about the ASCII vs scan code usage with .press() etc, so that is now very clear and consistent.

Case closed (again)!