Using the USBHost Library

Article thumbnail


arduino software

Reading from a keyboard with USBHost on the Arduino Due


The Arduino Due supports reading from USB devices through the Arduino USBHost library.

This guide it to print the key presses of a USB keyboard to the serial monitor.

In the Arduino IDE, go to Sketch > Include Library > Manage Libraries (or Tools > Manage Libraries… in the Arduino IDE v2).

In the library manager, type “usbhost” in the search bar and click Install in the box with the USBHost library.

Arduino IDE library manager Library installation

In the Arduino IDE v2:

Arduino IDE v2 library manager Library installation in the Arduino IDE v2


Connect the adapter cable to the native USB port and the cable for programming into the programming port. In this case, the blue cable is for programming and the black cable connects the keyboard. Then, connect the keyboard to the adapter cable.

Cables plugged into the Arduino Due


// Include the KeyboardController library
#include <KeyboardController.h>

// Initialize USB Controller
USBHost usb;

// Attach Keyboard controller to USB
KeyboardController keyboard(usb);

void setup() {
  Serial.begin(9600); // open a serial port

void loop() {

void keyPressed() {
  // Get the ASCII value of the key pressed.
  int key = keyboard.getKey();
  if (key != 19) {
    // Pressed key is not 'Enter'
  else {
    // Enter key pressed, start a new line

Code Explanation

First, we include the KeyboardController library and set up the keyboard.

In the setup function, we initialize a serial port. In the loop function, we call usb.Task to process keyboard input.

When a key is pressed, we print the key to the serial monitor with Serial.write. If the pressed key is the enter key, we start a new line.

Running the Code

Make sure the keyboard is plugged into the adapter. Then, open the serial monitor and press some keys on the keyboard.

The serial monitor should behave like a text editor, displaying each pressed key. Press enter to start a new line. This is the output of pressing some keys:

this is a test for usbhost library on arduino due