Keyboard Serial

Reads a byte from the serial port, and sends back a keystroke.

This example listens for a byte coming from the serial port. When received, the board sends a keystroke back to the computer. The sent keystroke is one higher than what is received, so if you send an "a" from the serial monitor, you'll receive a "b" from the board connected to the computer. A "1" will return a "2" and so on.

NB: When you use the Keyboard.print() command, the Leonardo, Micro or Due board takes over your computer's keyboard! To insure you don't lose control of your computer while running a sketch with this function, make sure to set up a reliable control system before you call Keyboard.print(). This sketch is designed to only send a Keyboard command after the board has received a byte over the serial port.

Hardware Required

  • Arduino Leonardo, Micro, or Due board

Circuit

Connect your board to your computer with a micro-USB cable.

Once programmed, open your serial monitor and send a byte. The board will reply with a keystroke that is one number higher.

circuit

Code

1/*
2
3 Keyboard test
4
5 For the Arduino Leonardo, Micro or Due
6
7 Reads a byte from the serial port, sends a keystroke back.
8
9 The sent keystroke is one higher than what's received, e.g. if you send a,
10
11 you get b, send A you get B, and so forth.
12
13 The circuit:
14
15 - none
16
17 created 21 Oct 2011
18
19 modified 27 Mar 2012
20
21 by Tom Igoe
22
23 This example code is in the public domain.
24
25 https://www.arduino.cc/en/Tutorial/KeyboardSerial
26
27*/
28
29#include "Keyboard.h"
30
31void setup() {
32
33 // open the serial port:
34
35 Serial.begin(9600);
36
37 // initialize control over the keyboard:
38
39 Keyboard.begin();
40}
41
42void loop() {
43
44 // check for incoming serial data:
45
46 if (Serial.available() > 0) {
47
48 // read incoming serial data:
49
50 char inChar = Serial.read();
51
52 // Type the next ASCII value from what you received:
53
54 Keyboard.write(inChar + 1);
55
56 }
57}

Learn more

You can find more basic tutorials in the built-in examples section.

You can also explore the language reference, a detailed collection of the Arduino programming language.

Last revision 2015/08/11 by SM

Suggest changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.

License

The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.