KeyboardEmulator
Jump to navigation
Jump to search
Keyboard Emulator in CircuitPython[edit]
Connect D2 to GND to activate Keyboard[edit]
code for the keyboard emulator[edit]
#"""based on CircuitPython Essentials HID Keyboard example"""
# IF you connect D2 and GND it acts as keyboard
import time
import board
import digitalio
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
from adafruit_lsm6ds.lsm6dsox import LSM6DSOX
i2c = board.I2C() # uses board.SCL and board.SDA
# i2c = board.STEMMA_I2C() # For using the built-in STEMMA QT connector on a microcontroller
sensor = LSM6DSOX(i2c)
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
switch = DigitalInOut(board.D2)
switch.direction = Direction.INPUT
switch.pull = Pull.UP
def sensorRead():
a=(sensor.acceleration)
g=(sensor.gyro)
return (a+g)
# The keyboard object!
time.sleep(1) # Sleep for a bit to avoid a race condition on some systems
keyboard = Keyboard(usb_hid.devices)
keyboard_layout = KeyboardLayoutUS(keyboard) # We're in the US :)
while True:
readings = []
for _ in range(100):
reading = sensorRead()
readings.append(reading)
time.sleep(0.02) # Sleep for 100 milliseconds
sum_absolute_differences = [0] * 6
for i in range(1, len(readings)):
for j in range(6): # Assuming each reading has 6 components
sum_absolute_differences[j] += abs(readings[i][j] - readings[i-1][j])
x = sum(sum_absolute_differences)
print(x)
#for i, reading in enumerate(readings):
#print(f"Reading {i+1}: {reading}")
if switch.value:
led.value = False
write2keyboard = False
#print("Off")
else:
led.value = True
write2keyboard = True
#print("On")
#if write2keyboard:
# keyboard.press(Keycode.SHIFT, Keycode.A)
# keyboard.press(Keycode.ENTER)
if 0 <= x <= 20:
print("nothing")
elif 20 < x <= 180:
print("nice, I like this\n")
if write2keyboard:
keyboard_layout.write("nice, I like this\n")
elif 180 < x <= 300:
print("are you careful?")
if write2keyboard:
keyboard_layout.write("are zou careful_\n")
elif 300 < x <= 400:
print("be careful with me!")
if write2keyboard:
keyboard_layout.write("be careful with me!\n")
elif 400 < x <= 600:
print("no this is not nice!")
if write2keyboard:
keyboard_layout.write("no this is not nice!\n")
elif 600 < x <= 800:
print("this hurts!!!")
if write2keyboard:
keyboard_layout.write("this hurts!!!\n")
elif x > 800:
print("you are killing me")
if write2keyboard:
keyboard_layout.write("zou are killing me\n")
else:
print("Value out of range")
if write2keyboard:
time.sleep(1)
time.sleep(1)