Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
The USB Host Shield is an essential component for Arduino enthusiasts who want to connect USB devices to their projects. It allows the Arduino to interface with USB peripherals such as keyboards, mice, and game controllers, expanding the range of possible applications. This article will guide you through the process of setting up and using a USB Host Shield with an Arduino, providing a detailed example project to demonstrate its capabilities.
Project: In this project, we will create a simple system that allows an Arduino to read input from a USB keyboard and display the typed characters on the Serial Monitor. The objective is to demonstrate how to interface a USB device with an Arduino using the USB Host Shield, and to provide a foundation for more complex USB-based projects.
Components List:
Examples: Below is the code example for interfacing a USB keyboard with an Arduino using the USB Host Shield. This example uses the USB Host Shield library, which needs to be installed in the Arduino IDE.
Install the USB Host Shield Library:
Connect the USB Host Shield to the Arduino:
Connect the USB Keyboard to the USB Host Shield:
Upload the Code to the Arduino:
// Include the necessary libraries
#include <hidboot.h>
#include <usbhub.h>
// Initialize USB and keyboard objects
USB Usb;
HIDBoot<HID_PROTOCOL_KEYBOARD> Keyboard(&Usb);
// Function to handle keyboard input
class KbdRptParser : public KeyboardReportParser {
protected:
void OnKeyDown(uint8_t mod, uint8_t key);
void OnKeyPressed(uint8_t key);
};
KbdRptParser KbdPrs;
void setup() {
// Initialize serial communication
Serial.begin(115200);
Serial.println("Start");
// Initialize USB communication
if (Usb.Init() == -1) {
Serial.println("OSC did not start.");
}
// Set the keyboard report parser
Keyboard.SetReportParser(0, (HIDReportParser*)&KbdPrs);
}
void loop() {
// Process USB tasks
Usb.Task();
}
// Handle key down events
void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key) {
uint8_t c = OemToAscii(mod, key);
if (c) {
OnKeyPressed(c);
}
}
// Handle key pressed events
void KbdRptParser::OnKeyPressed(uint8_t key) {
Serial.print((char)key);
}
Explanation of the Code:
hidboot.h
and usbhub.h
libraries are included to handle USB and HID (Human Interface Device) protocols.USB
and HIDBoot
objects are initialized to manage USB communication and keyboard input.KbdRptParser
class is defined to handle keyboard events, specifically key down and key pressed events.setup
function, serial communication is initialized, and the USB host shield is started. If the initialization fails, an error message is printed.loop
function continuously processes USB tasks to detect and handle keyboard input.OnKeyDown
and OnKeyPressed
functions are used to process and print the characters typed on the keyboard to the Serial Monitor.