Skip to content
ben-mkiv edited this page Feb 20, 2021 · 10 revisions

Keypad

A Keypad with buttons you can press to raise events to attached computers

Methods

keypad = require("component").os_keypad
keypad.setEventName("eventName") -- Sets the event name returned when you press a button, default is keypad
keypad.setDisplay("displayText", optional int:textColor) -- textColor is a minecraft color code
    
keypad.setVolume(0.5); -- sets the keypad beep volume (expects double numbers as input)
keypad.getVolume(); -- returns the current volume of the keypad beep


-- Custom button labels and colors

-- This is the default order, change any of them to change the button label in that place.
customButtons = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#"} 

-- This works the same as button labels, but it takes a color code to color the button label in that position.
customButtonColor = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} 

keypad.setKey(customButtons, customButtonColor)

Events

See OpenComputers wiki for more informations about events => OpenComputers Event API

event = require("event")
eventName, address, button, button_label = event.pull("keypad")
print("key pressed: " .. button)

Button is the button id, button_label is the current button label.

Example Script

keypad = require("component").os_keypad
event = require("event")

local pin = "1234"
local keypadInput = ""

-- set this to true if you want to run the script as daemon
local runScriptInBackground = false

function updateDisplay()
    local displayString = ""
    for i=1,#keypadInput do
        displayString = displayString .. "*"
    end

    keypad.setDisplay(displayString, 7)
end

function checkPin()
    if keypadInput == pin then
        keypad.setDisplay("granted", 2)
    else
        keypad.setDisplay("denied", 4)
    end    
    keypadInput = ""
    os.sleep(1)
end

function keypadEvent(eventName, address, button, button_label)
    print("button pressed: " .. button_label)
  
    if button_label == "*" then
        -- remove last character from input cache
        keypadInput = string.sub(keypadInput, 1, -2)
    elseif button_label == "#" then
        -- check the pin when the user confirmed the input
        checkPin()
    else
        -- add key to input cache if none of the above action apply
        keypadInput = keypadInput .. button_label
    end

    updateDisplay()  
end

-- listen to keypad events
event.listen("keypad", keypadEvent)

-- clear keypad display
keypad.setDisplay("")


if not runScriptInBackground then
    -- sleep until the user interrupts the program with CTRL + C
    local stopMe = false
    event.listen("interrupted", function() stopMe = true; end)
    while not stopMe do os.sleep(0.1) end

    -- ignore keypad events on exit
    event.ignore("keypad", keypadEvent)

    -- show that the keypad is inactive
    keypad.setDisplay("inactive", 6)
end