Arduino 简明教程
Arduino - Keyboard Logout
此示例使用键盘库,当 ARDUINO UNO 上的引脚 2 拉至接地时,使你退出计算机上的用户会话。此草图模拟了同时按两个或三个键的顺序的按键,并且在短延迟后释放它们。
Warning − 当你使用 Keyboard.print() 命令时,Arduino 将接管你的计算机键盘。为确保在使用此函数运行草图时不会失去对计算机的控制,请在调用 Keyboard.print() 之前设置一个可靠的控制系统。此草图设计为仅在引脚拉至接地后发送键盘命令。
Components Required
您将需要以下组件:
-
1 × Breadboard
-
1 × Arduino Leonardo、Micro 或 Due 电路板
-
1 × pushbutton
-
1 × Jumper
Sketch
在计算机上打开 Arduino IDE 软件。使用 Arduino 语言进行编码将控制您的电路。单击“新建”以新建一个草图文件。
以下示例中,需要使用 Arduino IDE 1.6.7
Note − 必须在 Arduino 库文件中包含键盘库。将键盘库文件复制并粘贴到名为 libraries 的文件夹中(高亮),如下面的屏幕截图所示。
Arduino Code
/*
Keyboard logout
This sketch demonstrates the Keyboard library.
When you connect pin 2 to ground, it performs a logout.
It uses keyboard combinations to do this, as follows:
On Windows, CTRL-ALT-DEL followed by ALT-l
On Ubuntu, CTRL-ALT-DEL, and ENTER
On OSX, CMD-SHIFT-q
To wake: Spacebar.
Circuit:
* Arduino Leonardo or Micro
* wire to connect D2 to ground.
*/
#define OSX 0
#define WINDOWS 1
#define UBUNTU 2
#include "Keyboard.h"
// change this to match your platform:
int platform = WINDOWS;
void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}
void loop() {
while (digitalRead(2) == HIGH) {
// do nothing until pin 2 goes low
delay(500);
}
delay(1000);
switch (platform) {
case OSX:
Keyboard.press(KEY_LEFT_GUI);
// Shift-Q logs out:
Keyboard.press(KEY_LEFT_SHIFT);
Keyboard.press('Q');
delay(100);
// enter:
Keyboard.write(KEY_RETURN);
break;
case WINDOWS:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(100);
Keyboard.releaseAll();
//ALT-l:
delay(2000);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press('l');
Keyboard.releaseAll();
break;
case UBUNTU:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(1000);
Keyboard.releaseAll();
// Enter to confirm logout:
Keyboard.write(KEY_RETURN);
break;
}
// do nothing:
while (true);
}
Keyboard.releaseAll();
// enter:
Keyboard.write(KEY_RETURN);
break;
case WINDOWS:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(100);
Keyboard.releaseAll();
//ALT-l:
delay(2000);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press('l');
Keyboard.releaseAll();
break;
case UBUNTU:
// CTRL-ALT-DEL:
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_ALT);
Keyboard.press(KEY_DELETE);
delay(1000);
Keyboard.releaseAll();
// Enter to confirm logout:
Keyboard.write(KEY_RETURN);
break;
}
// do nothing:
while (true);
}