Skip to main content

Keyboard

Plug a USB keyboard into the Pi, and your program can read it one key at a time.

Add the Raspberry Pi library first

Pi and its devices come from a library, not from the language, so this code won't build without it. In IntelliJ, choose Tools | Nylon | Add Nylon Library… and pick raspberry-pi. That adds one line to your project's build.markup.code:

(+dependencies : RepositoryDependency coordinate={"com.grandtheorem:raspberry-pi:0.1.0"} /)

Read what's typed​

Keyboards comes from the Raspberry Pi library.

namespace typing

import grandtheorem.rpi.Keyboards

Keyboards.first() gives you the first keyboard plugged in.

entrypoint.default main() {
let keyboard = Keyboards.first()

readKey waits for the next key, up to the timeout. If none comes, there's no key, and if (let key? = ...) skips its block.

while (true) {
if (let key? = keyboard.readKey(1.seconds())) {

character is the text the key types. Keys like the arrows type nothing, so it may be missing, but every key has a code.

if (let character? = key.character) {
println(character)
} else {
println("key ${key.code} types nothing")
}
}
}
}

Each key you press shows up in the run window. The program loops forever, so press Stop in IntelliJ to end it.

React to a key​

For keys that don't type anything, use code. These are the common ones:

KeyCode
Right arrow79
Left arrow80
Down arrow81
Up arrow82
Enter40
Escape41
Space44

Name the codes you care about, so the code reads as what it means.

namespace arrows

import grandtheorem.rpi.Keyboards

let LEFT = 80
let RIGHT = 79

position changes as the program runs, so it's a var.

entrypoint.default main() {
let keyboard = Keyboards.first()
var position = 0

Compare each key's code. Any other key leaves position alone.

while (true) {
if (let key? = keyboard.readKey(1.seconds())) {
if (key.code == LEFT) {
position = position - 1
} elif (key.code == RIGHT) {
position = position + 1
}

println("position ${position}")
}
}
}

Good to know​

A held key counts once. Holding a key down doesn't repeat it, and there's no way yet to tell when it's released.

Letters follow Shift, not Caps Lock. A letter is a capital only while Shift is held. character assumes a US layout.

Enter types "\n". If you're sending text to something that expects \r\n, swap it yourself.

No keyboard is not an error. readKey just finds no key until one is plugged in.

USB only, for now. Bluetooth is coming, so a keyboard can pair without a cable.

note

These programs ran on a Raspberry Pi 4, as this page shows them.