Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Computer Lock Button Using CircuitPython
# SPDX-FileCopyrightText: 2021 John Furcean
# SPDX-License-Identifier: MIT
import time
import board
from digitalio import DigitalInOut, Direction, Pull
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.keycode import Keycode
def button_pressed(button):
return not button.value
kbd = Keyboard(usb_hid.devices)
# Digital input with pullup on D1
# this is the pin that the button is connected to
button = DigitalInOut(board.D1)
button.direction = Direction.INPUT
button.pull = Pull.UP
# LED button light
# comment out if your button doesn't have an LED
button_led = DigitalInOut(board.D0)
button_led.direction = Direction.OUTPUT
button_led.value = True
button_held_in = False
button_index = 0
change_button = False
while True:
# detect if the button is recently pressed in
if button_pressed(button) and not button_held_in:
button_held_in = True
# detect if the button has been released
if not button_pressed(button) and button_held_in:
#Send Lock Command
# Uncomment for Windows
#kbd.send(Keycode.WINDOWS , Keycode.L)
# Uncomment for Mac
kbd.send(Keycode.CONTROL, Keycode.COMMAND, Keycode.Q)
# Uncomment for (most) Linux
#kbd.send(Keycode.ALT, Keycode.CONTROL, Keycode.L)
# update the state of the my_button_held_in Boolean
button_held_in = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment