In the Atmega 32u4 Based USB Controlled LED Series Project, it was demonstrated how to use control transfer to receive data from computer to the peripheral. In this project, it will be demonstrated to transfer data from microcontroller to the host computer. For this, the device will be configured as HID Class Device again. An HID Class device has USB communication over two types of transfers – Control transfer and Interrupt transfer. When data has to be exchanged from default endpoints i.e. endpoint 0 IN and endpoint 0 OUT only, the control transfer is sufficient to perform the data communication. Usually, HID devices only use control transfer for enumerating with the host. After enumeration, they send real-time data to the host computer using Interrupt Transfer for which additional endpoints are configured during enumeration process. In this project, an LED board will be designed and status of the LEDs will be transmitted to the host computer using Interrupt transfer.
The project will need a controller chip to handle USB data from the device to the host computer and to keep track of LED’s status in real-time. The 8-bit USB AVR – Atmega 32u4 is used as the device controller chip in the project. The project uses AVR based Lightweight USB Framework (LUFA) as the firmware which will be modified to implement the project’s functioning. The device is tested on a Linux system using Pyusb and Libusb frameworks for receiving data from peripheral device to the host computer.
Fig. 1: Prototype of Arduino based DIY USB LED Status Monitor
The Generic HID device driver class of the LUFA firmware is used and modified to program the project. With the use of LUFA firmware, the device driver code to implement USB protocol is not needed to be written explicitly. Modifying the firmware code will be sufficient to implement the USB protocol. The device has two LEDs connected to it which will be operated ON or OFF by a tactile switch.
PREREQUISITES
This project is based on Arduino Pro Micro which has the USB AVR – Atmega 32u4 as the sitting MCU. In order to understand this project, one must have basic knowledge of the AVR microcontrollers and the embedded C programming for AVRs. WinAVR Studio is used to write, edit and compile the project code, so closely following the project shall require familiarizing with the above stated IDE as well. Though LUFA framework takes care of implementing the USB protocol and has APIs to abstract the lower level codes, understanding USB protocol is recommended to understand how actually the project is working. In fact, if anyone has already worked on some other microcontroller, it will not be much pain to understand and follow this project as the project code is more or less about modifying the LUFA device driver to work as generic HID device. One must have additional knowledge of Linux operating system (Ubuntu) and should be knowing basic Linux commands. One having knowledge of Python programming language is recommended but not mandatory for implementing the project.
COMPONENTS REQUIRED
1. Arduino Pro Micro
2. Breadboard
3. Connecting wires
4.LEDs
5. Tactile switch – 1
6. Micro USB cable
7. 10K resistors
SOFTWARE TOOLS REQUIRED
1. WinAVR Studio
2. AVR Dude
5. Pyserial 2.7
BLOCK DIAGRAMS
Fig. 2: Block Diagram of Arduino based DIY USB LED Status Monitor
CIRCUIT CONNECTIONS
The project uses Arduino Pro Micro as the USB controller. A series of two LEDs is connected at the port B of the Arduino. The LEDs are connected at pins 4 and 5 of the port B. The 220 Ω pull up resistors are used to interface the LEDs. The LEDs are connected between the pins and the ground with anode connected to the pin and cathode connected to the ground. Therefore, when a HIGH logic is output from the pin, the LED starts glowing and when a LOW logic is output from the pin, the LED stops glowing. A tactile switch is connected at pin 2 of Port B between ground and the pin. The PB2 by default is connected to VCC through a 10 K Ω resistor. On pressing the switch, the pin is short circuited to the ground.
Fig. 3: Table listing Arduino pins and component interfaced at them
The Program code for the project is burnt to the Arduino Pro Micro using AVR Dude. The Arduino board is connected to the USB port of a PC by a USB cable.
HOW THE PROJECT WORKS
In this project the USB protocol is implemented by the LUFA framework. For configuring the controller chip to work as Generic HID device, the HID Class Driver of the LUFA framework will be used. The Human Interface Device (HID) class takes care of the transfers between the host device and the human controlled USB peripherals like USB Keyboard, Mouse or Joystick. However, the Generic HID device designed in this project uses Interrupt transfers to communicate LED status data to the host computer.
When a USB device is attached to the host (PC), the host sends request for configuration details in the form of control transfer. The connected device has to respond with appropriate descriptors to get configured and ready for further operations. Only after configuration, the device can communicate with the host in the form of interrupt, isochronous or bulk transfers for executing the operations for which the device has been made. This process of identification and configuration of the device with the host is called enumeration.
Fig. 4: Prototype of Arduino based DIY USB LED Status Monitor
In case of this project, after configuring with the host device, it has to communicate with the host in the form of Interrupt transfers for sending data to the host computer. The Interrupt Transfer is always used for exchanging real-time data to the computer. The project uses interrupt transfer to communicate user-defined data packets to the computer. The data can be exchanged using Class-Specific Requests. These Requests are sent by Host to Device via Control Transfer. The Get_Report is the request by which Host can receive data from the device.
The project is based HID class driver of USB and LUFA framework has HID class related module in the LUFA-Source-Folder /LUFA/Drivers/USB/Class/Device folder. Other device class related module are also in the same folder. The LUFA framework has demo projects for different USB device classes in the LUFA-Source-FolderDemosDeviceClassDriver folder. For implementing the project, demo project for Generic HID devices provided in the LUFA framework will be modified and complied. The demo project for Generic HID devices is in the LUFA-Source-FolderDemosDeviceClassDriverGenericHID folder. The folder contains GenericHID.c file which will be modified to implement the LED project.
How GenericHID.c identifies HID device being Generic HID device
The GenericHID.c uses Generic_HID_Interface interface in HID_Device_USBTask() function which is being imported from the HIDDeviceClass.c (from LUFA-Source-Folder LUFADriversUSBClassDevice) to configure the device as generic HID device. The interface abstracts the low-level descriptor codes and identifies the device as generic HID device through an InterfaceNumber variable.
Generic HID Device Specific Report Descriptors
Any HID device has to exchange data with the host which should be structured in the form of reports. The report descriptor defines the report structure. A report descriptor contains the information needed by host to determine the data format and how the data should be processed by the host. Therefore, a report descriptor basically structure the data that needs to be exchanged with the host according to the USB protocol.
For working like a generic USB HID device, the device needs to send usage report descriptor specific to Generic HID Class to the host. The Usage Report informs the Host about the features or functionality of the USB device. An HID device sends data output report to the host computer for sending any data to it while it reads data input report to fetch data from computer to itself. The usage report and data reports are application layer features of USB protocol. In this project, data will be sent from device to the host so data input report will be utilized.
From Where GenericHID.C gets the USAGE and Data Reports Descriptors
In the LUFA framework’s demo project for GenericHID, GenericHID.h is imported. The GenericHID.h imports descriptor.c file which defines the relevant usage and data reports descriptors for the host device. The descriptor.c defines a GenericReport[] structure to generate generic HID usage and data reports descriptors. Inside descriptor.c the GenericReport [] structure has the values returned by HID_DESCRIPTOR_VENDOR () function. The HID_DESCRIPTOR_VENDOR () is defined in HIDClassCommon.h (located in LUFA-Source-FolderLUFADriversUSBClassCommon folder).
The GenericHID.c imports GenericHID.h which imports usb.h. USB.h imports HIDCLass.h. In HIDClass.h is imported HIDClassDevice.h if the USB_CAN_BE_DEVICE is true for the controller chip to being a USB device not the host. The HIDClassDevice.h imports HIDClassCommon.h where the HID device specific descriptor fields have been defined.
USAGE REPORT
HID_DESCRIPTOR_VENDOR () returns the field values of the usage report descriptor, specific to generic HID device functioning. The fields are set to following values in HID_DESCRIPTOR_VENDOR ().
Fig. 5: Screenshot of HID_DESCRIPTOR_VENDOR Function of LUFA library
The Usage or Feature report contains information about the features of the device. In other words, this report informs Host about the features needed in the device. A generic HID device is a vender defined device and can simply send data on the USB interface.
DATA INPUT REPORT
The Data Input report for generic HID device simply contains data of a size restricted by the usage report. It is same as the data output report for the generic HID Class. It is defined in the following manner -:
Fig. 6: Screenshot of Data Input report for generic HID device in LUFA Library
In LUFA framework, both the data input and data output reports are restricted to contain data packet 8-byte long.
HOW THE DEVICE WORKS
The device has two LEDs and a tactile switch connected. Whenever, the switch will be pressed and released, the ON/OFF status of the LEDs will be changed. The microcontroller will detect pressing of switch and change logic at the GPIO pins where LEDs are connected. At the same time, it will generate and transmit a data input report which will be sent to the computer. Since, data is to be sent to the host device CALLBACK_HID_Device_CreateHIDReport() function of the GenericHID.c will be modified. The main() function of the GenericHID.c will also be modified to acknowledge the microcontroller about the circuit configuration. On PC side, a Python Application will be used to display data input report. The Application will be based on Python programming language and will run on Linux distribution like Ubuntu. It will use Pyusb and Libusb framework for receiving data on the USB protocol. The Application will issue a Get_Report request to transfer data from the Device (microcontroller). The data packet in data input report will be structured in the following manner -:
Fig. 7: Table listing structure of data packet in data input report
If the respective LED will be ON, 0x01 will be transmitted in the corresponding byte else if LED will be switched OFF, 0x00 will be transmitted in the corresponding byte.
Check out the program code to see the modifications implemented for the project.
PROGRAMMING GUIDE
For building the project download the LUFA framework from the github.com. The demo project provided with the LUFA framework is modified to make the project. In the extracted LUFA zip file, open Demos/Device/ClassDriver/GenericHID folder. The folder has the following files and folders.
Fig. 8: Screenshot of LUFA Library Folder on Windows
Of these, GenericHID.h, GenericHID.c and Makefile needs to be modified for this project. The modified files (provided at the bottom of the article in zip format) can also be downloaded from the engineersgarage and replaced with the original files. Either open the files in WinAVR Studio or Notepad++ and modify original files or replace files with the already modified one. The modified or replaced GenericHID.c needs to be compiled from within the LUFA’s Source folder to get the object code.
Modifying GenericHID.h
The GenericHID.h library file is imported in the GenericHID.c file and includes a set of additional libraries and defines the constants and functions for the Generic HID device. These include the additional libraries for the LED board which should be commented out as the project is not using that HID feature. So open GenericHID.h and make the following changes -:
• Comment the #include library statements for LEDs.h (This library is commented as typical LED board is not used in the project)
Save the file with changes.
Modifying GenericHID.C file
Again in the GenericHID.c, the code sections for LED board needs to be commented out. So open GenericHID.c and make the following changes -:
• In the main loop, comment the LEDs_SetAllLEDs()
• In SetupHardware() function, comment the LEDs_Init()
• In EVENT_USB_Device_Connect() function, comment the LEDs_SetAllLEDs()
• In EVENT_USB_Device_Disconnect() function, comment LEDs_SetAllLEDs()
• In EVENT_USB_Device_ConfigurationChanged() function, comment the LEDs_SetAllLEDs()
In the main() function of GenericHID.c the microcontroller needs to be made aware of the circuit configuration. Inside the main function Port B where the LEDs and switch have been connected needs to be defined as output and input respectively. The pins of port B has to be raised to LOW or HIGH logic by default accordingly as the LEDs should remain in OFF state by default while pin interfaced with switch must be detecting a HIGH logic by default. So add the following statements in the beginning of main() function -:
Inside the infinite for loop the HID_Device_USBTask() function is called where Generic_HID_Interface interface is passed as parameter. The interface identifies the device as Generic HID device and abstracts the low level program code specific to Generic HID class. The function is coming from the HIDClassDevice.c module (located in LUFA/Drivers/USB/Class/Device/HIDClassDevice.c) and is used for general management task for a given HID class interface, required for the correct operation of the interface. It should be called in the main program loop, before the master USB management task USB_USBTask(). The USB_USBTask() is the main USB management task. The USB driver requires this task to be executed continuously when the USB system is active (device attached in host mode, or attached to a host in device mode) in order to manage USB communications. The function is defined in USBTask.c (Located in LUFA-Source-FolderLUFADriversUSBCore folder).
For creating the Data Input report CALLBACK_HID_Device_CreateHIDReport() function needs to be modified. The default file has the function body to transmit LED board status back to the computer.
Fig. 9: Screenshot of CALLBACK_HID_Device_CreateHIDReport Function of LUFA Library
The controller chip sends 4-byte data to the host computer in data input report as configured in LUFA framework. A counter variable is declared which is initialized to zero. The counter increases wherever the switch is pressed. The counter value is used in a switch statement.When the switch is not pressed for a single time, the pins where LEDs are connected are set to LOW logic and 0x00 is sent in the data packet for both Byte0 and Byte1. When switch is pressed for first time, counter is increased to 1, and LED1 is set to ON by sending a HIGH logic at the respective pin. The microcontroller sends 0x01 in Byte0 and 0x00 in Byte1. When switch is pressed for second time, counter is increased to 2, and LED1 is set to OFF while LED2 is switched ON. The microcontroller sends 0x01 in Byte1 and 0x00 in Byte0. When switch is pressed for third time, counter is increased to 3, and both LEDs are switched ON. The microcontroller sends 0x01 in both Byte0 and Byte1. When switch is pressed for fourth time, , counter is increased to 4 which leads to running default case in switch statement resetting the counter to 0.
The Data Output Report (to receive data from host to the device) is handled by the CALLBACK_HID_Device_ProcessHIDReport() function. In the unedited LUFA file, this function has statements to control LED board -:
Fig. 10: Screenshot of CALLBACK_HID_Device_ProcessHIDReport Function of LUFA Library
All the statements in this function will be cleared as the device will not receive any data from the host computer. Therefore, the CALLBACK_HID_Device_ProcessHIDReport() function will be left with an empty body -:
Save the file and create Make file for the project.
Modifying Make File
In the GenericHID folder there is a make file that needs to be edited. The file can be edited using Notepad++. The following information needs to be edited -:
• MCU = atmega32u4
• ARCH = AVR8
• BOARD = LEONARDO
• F_CPU = 16000000
Save the file and exit. Now all the files are edited completely for the LED Status Project.
Compiling GenericHID.c
For compiling the source code, WinAVR Programmers Notepad or Arduino IDE can be used. Open the modified GeericHID.c file and compile the code.
BURNING HEX CODE
The hex file is generated on compiling the GenericHID.c file. For burning the object code to microcontroller open the Command Prompt, change the current directory to the directory containing the Hex file. This can be done using command: CD <address of the directory>. Now reset the Arduino and instantly run the command: avrdude -v -p atmega32u4 -c avr109 -P COM20 -b 57600 -D -Uflash:w:GenericHID.hex:i after replacing the COM Port with the recognized one. If using Linux, the COM port name will be like /dev/ttyACM0.
TESTING THE DEVICE
Project Source Code
###
/* LUFA Library Copyright (C) Dean Camera, 2015. dean [at] fourwalledcubicle [dot] com www.lufa-lib.org */ /* Copyright 2015 Dean Camera (dean [at] fourwalledcubicle [dot] com) Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that the copyright notice and this permission notice and warranty disclaimer appear in supporting documentation, and that the name of the author not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. The author disclaims all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall the author be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ /** file * * Main source file for the GenericHID demo. This file contains the main tasks of * the demo and is responsible for the initial application hardware configuration. */ #include "GenericHID.h" /** Buffer to hold the previously generated HID report, for comparison purposes inside the HID class driver. */ static uint8_t PrevHIDReportBuffer[GENERIC_REPORT_SIZE]; /** LUFA HID Class driver interface configuration and state information. This structure is * passed to all HID Class driver functions, so that multiple instances of the same class * within a device can be differentiated from one another. */ USB_ClassInfo_HID_Device_t Generic_HID_Interface = { .Config = { .InterfaceNumber = INTERFACE_ID_GenericHID, .ReportINEndpoint = { .Address = GENERIC_IN_EPADDR, .Size = GENERIC_EPSIZE, .Banks = 1, }, .PrevReportINBuffer = PrevHIDReportBuffer, .PrevReportINBufferSize = sizeof(PrevHIDReportBuffer), }, }; /** Main program entry point. This routine contains the overall program flow, including initial * setup of all components and the main program loop. */ int main(void) { SetupHardware(); DDRB |= 0b00110000; // make PB4 and PB5 as output DDRB &= 0b11111011; // make PB2 as input PORTB |= 0b00000100; // make PB2 high PORTB &= 0b11001111; // make PB4 and PB5 low //LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY); GlobalInterruptEnable(); for (;;) { HID_Device_USBTask(&Generic_HID_Interface); USB_USBTask(); } } /** Configures the board hardware and chip peripherals for the demo's functionality. */ void SetupHardware(void) { #if (ARCH == ARCH_AVR8) /* Disable watchdog if enabled by bootloader/fuses */ MCUSR &= ~(1 << WDRF); wdt_disable(); /* Disable clock division */ clock_prescale_set(clock_div_1); #elif (ARCH == ARCH_XMEGA) /* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */ XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU); XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL); /* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */ XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ); XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB); PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm; #endif /* Hardware Initialization */ //LEDs_Init(); USB_Init(); } /** Event handler for the library USB Connection event. */ void EVENT_USB_Device_Connect(void) { //LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING); } /** Event handler for the library USB Disconnection event. */ void EVENT_USB_Device_Disconnect(void) { //LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY); } /** Event handler for the library USB Configuration Changed event. */ void EVENT_USB_Device_ConfigurationChanged(void) { bool ConfigSuccess = true; ConfigSuccess &= HID_Device_ConfigureEndpoints(&Generic_HID_Interface); USB_Device_EnableSOFEvents(); //LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR); } /** Event handler for the library USB Control Request reception event. */ void EVENT_USB_Device_ControlRequest(void) { HID_Device_ProcessControlRequest(&Generic_HID_Interface); } /** Event handler for the USB device Start Of Frame event. */ void EVENT_USB_Device_StartOfFrame(void) { HID_Device_MillisecondElapsed(&Generic_HID_Interface); } /** HID class driver callback function for the creation of HID reports to the host. * * param[in] HIDInterfaceInfo Pointer to the HID class interface configuration structure being referenced * param[in,out] ReportID Report ID requested by the host if non-zero, otherwise callback should set to the generated report ID * param[in] ReportType Type of the report to create, either HID_REPORT_ITEM_In or HID_REPORT_ITEM_Feature * param[out] ReportData Pointer to a buffer where the created report should be stored * param[out] ReportSize Number of bytes written in the report (or zero if no report is to be sent) * * return Boolean c true to force the sending of the report, c false to let the library determine if it needs to be sent */ bool CALLBACK_HID_Device_CreateHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo, uint8_t* const ReportID, const uint8_t ReportType, void* ReportData, uint16_t* const ReportSize) { uint8_t* Data = (uint8_t*)ReportData; static uint8_t counter = 0; // counter to change the LED pattern if(!(PINB & _BV(PB2))) counter++; // update counter switch(counter) { case 0: PORTB &= 0b11001111; // Both LED OFF Data[0] = 0x00; Data[1] = 0x00; break; case 1: PORTB |= 0b00010000; // LED1 ON PORTB &= 0b11011111; // LED2 OFF Data[0] = 0x01; Data[1] = 0x00; break; case 2: PORTB |= 0b00100000; // LED2 ON PORTB &= 0b11101111; // LED1 OFF Data[0] = 0x00; Data[1] = 0x01; break; case 3: PORTB |= 0b00110000; // Both LED ON Data[0] = 0x01; Data[1] = 0x01; break; default: counter = 0; // reset counter break; } *ReportSize = GENERIC_REPORT_SIZE; return false; } /** HID class driver callback function for the processing of HID reports from the host. * * param[in] HIDInterfaceInfo Pointer to the HID class interface configuration structure being referenced * param[in] ReportID Report ID of the received report from the host * param[in] ReportType The type of report that the host has sent, either HID_REPORT_ITEM_Out or HID_REPORT_ITEM_Feature * param[in] ReportData Pointer to a buffer where the received report has been stored * param[in] ReportSize Size in bytes of the received HID report */ void CALLBACK_HID_Device_ProcessHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo, const uint8_t ReportID, const uint8_t ReportType, const void* ReportData, const uint16_t ReportSize) { }###
Circuit Diagrams
Project Video
Filed Under: Electronic Projects
Filed Under: Electronic Projects
Questions related to this article?
👉Ask and discuss on Electro-Tech-Online.com and EDAboard.com forums.
Tell Us What You Think!!
You must be logged in to post a comment.