Can the Teensy keyboard "see" current state of NUMLOCK, CAPSLOCK etc

REmery

New member
Hello,

So I'm building a keyboard thing and I'm hitting the issue that when I plug the device into a new PC, I have no way of knowing whether capslock, scrolllock and numlock are enabled already. So my indicator can end up out of sync with other keyboards that are plugged in. This is built on a Teensy LC at the moment (because that's what I had sitting around, I am aware it's not recommended for new designs)

I've looked through usb_keyboard.h and I can't see anything obvious for the teensy to be able to read the state of the lock keys but I assume it must be possible because if I plug in a commercial keyboard, it sets its LEDs to be the same as the current state.

Can anyone enlighten me as to how this works?

Thanks,
Rob
 
Sadly, no. That state exists only on the PC. As far as I know, the HID protocol used by nearly all USB keyboards does not provide any way to explicitly communicate that state from the PC to the keyboard.

However, the LEDs are communicated. You could assume which LED is which state. The USB code puts it into a "keyboards_leds" variable.

From Arduino sketch code, add this to get access to keyboards_leds.

Code:
extern "C" volatile uint8_t keyboard_leds;
 
I know the USB Host code can tell keyboards the logical state of these through the LEDS( code, which sends out a control packet:
Code:
driver_[0]->sendControlPacket(0x21, 9, 0x200, 0, sizeof(leds_.byte), (void*) &leds_.byte);

Not sure if we listen to it on the USB Device side...
looks like we keep the state of it:
Code:
// 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
volatile uint8_t keyboard_leds=0;

Not sure if/when the host will tell you the changed states. Also looks maybe like you probably keep routinely checking the state of this variable.
 
Last edited:
It is certainly possible. At one point I created a USB rickroll device, it would pretend to be a keyboard and turn on caps lock. When capslock was turned off (because someone was using the computer) it would detect the LED change, wait 30 seconds and then launch a youtube video of a certain song (windows key + R to bring up a command prompt, hit the keys for the URL and enter. Press the windows media key for volume up 50 times.)

That was using mbed where there was a function keyboard.lockStatus() that would give the current LED status as a bit mask.

This is a standard part of the protocol, if I hit numlock on my laptop the led on the USB keyboard toggles.

So USB keyboard HID certainly includes the required functionality. How you can access it via the Teensy/arduino libraries is another matter...
 
Aha! Thanks for the input everyone, the LEDs are exactly what I'm after for the initial state. Works a treat!
 
Back
Top