In Atmega 32u4 Based USB Controlled LED Series Project, how data is communicated from computer to a generic HID device was seen. Then, in Atmega 32u4 Based LED Status Project, how microcontroller configured as generic HID device can communicate data to the computer was studied. For data transmission from computer to device, control transfer was used while for data transmission from device to computer, interrupt transfer was used. In this project, a generic HID device will be designed that will exchange data with a computer both ways.
Primarily, it will receive data packets from the host computer and will use those data packets to control input/output ports of the microcontroller. A python based application will run on the personal computer which will send these data packets and will be able to select a microcontroller port and set it as digital input or output, read data from the selected port or write data to the selected port. The python based application will be sending these packets on USB interface. The application itself will run on a Linux operating system like Ubuntu.
The project will be built on Arduino Pro Micro as it will need a controller chip to handle USB data exchanged from the computer. The onboard 8-bit USB AVR – Atmega 32u4 will work 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 sending data from computer to the device.
Fig. 1: Prototype of USB Controlled AVR GPIO Pins
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 Input/output operations can be tested by interfacing LEDs or tactile switches with the microcontroller ports. All the input/output ports – B, C, D, E and F could be controlled in the project.
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 to receive or transmit digital data with the host computer.
COMPONENTS REQUIRED
1. Arduino Pro Micro
2. Breadboard
3. Connecting wires
4. LEDs
5. Switches
6. Micro USB cable
7. 10K resistors
8. 220 Ω Resistors
SOFTWARE TOOLS REQUIRED
1. WinAVR Studio
2. AVR Dude
5. Pyserial 2.7
BLOCK DIAGRAM
Fig. 2: Block Diagram of Arduino based DIY USB Controlled Digital Input and Output
CIRCUIT CONNECTIONS
The project uses Arduino Pro Micro as the USB controller chip. If LEDs are connected at any port of the Arduino to check digital output, 220 Ω pull up resistors should be used to interface the LEDs. The LEDs must be 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. If tactile switches are connected at any Port of the Arduino to test digital input, they should be connected between ground and the pin. The port by default should be connected to VCC through a 10 K Ω resistor. On pressing a switch, the respective pin will be short circuited to the ground and a LOW logic must be detected at the respective bit. 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
Enumeration of the Device
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.
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.
In HID class, two types of Transfer Types are used: Control Transfer and Interrupt Transfer. An HID device uses control transfer to receive data from the computer while it uses interrupt transfer to send data to the computer. The data can be exchanged using Class-Specific Requests. These Requests are sent by Host to Device via Control Transfer. Check out the Atmega 32u4 Based USB Controlled LED Series Project and Atmega 32u4 Based LED Status Project for learning about the Get_Report and Set_Report Class specific requests.
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 and data input report descriptors specific to Generic HID Class to the host while it itself needs to interpret data output report specific to Generic HID Class received from the host device. The Usage Report informs the Host about the features or functionality of the USB device whereas the Data Output Report is used to receive data from the host.
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. 3: 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 or data on the USB interface.
DATA INPUT AND OUTPUT REPORT
The Data Input and Output report for generic HID device simply contains data of a size restricted by the usage report. It is defined in the following manner -:
Fig. 4: Screenshot of Data Input and Output 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. In this project, only three bytes of the data packet will be utilized.
HOW THE DEVICE WORKS
When device will be attached with the computer, it will get enumerated and ready for receiving data packets from the computer. On the host computer, a python based desktop application will be used for the following port operations -:
• Selecting the port and the pin which needs to be accessed
• Setting the Data direction of the selected port or pin in the microcontroller
• To read or write the port or pin with a value
The desktop application will be used to send three bytes long data packet structured in the following manner -:
Fig. 5: Table listing data packet structure for USB Controlled Digital IO
The Byte0 of the data packet will be used to select the operation on the port. It will indicate the microcontroller that user wants to either Set Data Direction for a Port, or Read a Port, or Write a Port. This byte is custom named ModeFlag and is denoted by mode_flag variable in the program code. If the byte will read 0x44, the controller will select setting data direction as the desired operation. If the byte will read 0x52, the controller will select Reading port data as the desired operation. In case, the byte will read 0x57, the controller will select writing data to a port as the desired operation. These codes are pre-defined in the program code and should be sent as Byte0 in the data packet sent from the desktop application.
The Byte1 will indicate the Port Name that needs to be accessed. For example, if Port A needs to be controlled, then this byte will contain ASCII value of A (0x41).
The Byte2 will contain the appropriate data associated with the desired operation. Like if data direction is selected as the desired operation, it will contain the byte defining digital input and output. If data read or write operation is selected, it will contain data that will have to be read or write respectively to the selected port.
When data will be read, it will be sent to the computer using data input report over an interrupt transfer.
The data direction and write operation involves only receiving data from the host computer for which CALLBACK_HID_Device_ProcessHIDReport() function of the GenericHID.c will be modified. The data read operation involves data communication in both directions and involve modifying CALLBACK_HID_Device_ProcessHIDReport() as well as CALLBACK_HID_Device_CreateHIDReport() functions of the GenericHID.c. Rest, few code lines in the original file written for the LED board needs to be removed. The desktop Application will be based on Python programming language and will run on Linux distribution like Ubuntu. It will use Pyusb and Libusb framework for sending data on the USB protocol. The Application will issue a Set_Report request to transfer the data to Device (microcontroller).
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. 6: Screenshot of LUFA Library 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 (We are commenting this library as we are not using LED board)
• Comment the #define statements for LEDMASK_USB_NOTREADY, LEDMASK_USB_ENUMERATING, LEDMASK_USB_READY, LEDMASK_USB_ERROR
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 only statement for LED board needs to be removed or commented out. The generic HID driver is also implemented from within the main() function. So the main function will have following statements -:
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 Output report CALLBACK_HID_Device_ProcessHIDReport() function needs to be modified. The default file has the function body to transmit data to an LED board.
Fig. 7: Screenshot of CALLBACK_HID_Device_ProcessHIDReport Function of LUFA
The controller chip receives 3-byte data from the host computer and according to that data, it performs the desired operations on selected port. So replace the body of the function with the following code -:
In the body of the CALLBACK_HID_Device_ProcessHIDReport() function, the variables mode_flag, port_name and hex_value are declared to hold values of Byte0, Byte1 and Byte2 of the data packet. If data direction operation is selected, the received Byte2 value is assigned to the DDR<Port_Name> statements with the port selected based on a switch statement. If data write operation is selected, the received Byte2 value is assigned to the selected port therefore writing off the received value to the selected parallel port.
The Data Input Report (to send data from device to the host) is handled by the CALLBACK_HID_Device_CreateHIDReport() function. In the unedited LUFA file, this function has statements to report back the status of LED board and has the following body -:
Fig. 8: Screenshot of CALLBACK_HID_Device_CreateHIDReport Function of LUFA
The device send back 2-byte data packet to the host computer if read operation is selected. The CALLBACK_HID_Device_CreateHIDReport() function is modified to implement functioning of the read function -:
The first byte sent by the device in response to read operation contain “R” string to indicate that the packet is sent in response to read request. The second byte contains the actual data read from the selected port.
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 USB Controlled GPIO 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
In the next project – Atmega 32u4 Based USB Data Logger, learn how to read analog data from a microcontroller and send it to PC on USB port for saving to a Log File.
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]; // flag to indicate read, write or direction update mode volatile char mode_flag; // character to indicate port name received from host char port_name; /** 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(); //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; /* *If Read flag is received from Host * Send status of pins for the specifed port */ if(mode_flag == 'R') { Data[0] = 'R'; // send Read flag as echo // read pins according to port switch(port_name) { case 'B': Data[1] = PINB; break; case 'C': Data[1] = PINC; break; case 'D': Data[1] = PIND; break; case 'E': Data[1] = PINE; break; case 'F': Data[1] = PINF; 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) { uint8_t* Data = (uint8_t*)ReportData; mode_flag = Data[0]; //read flag port_name = Data[1]; //read port name char hex_value = Data[2]; // read hex value /* * if Set Data Direction flag is received * set data direction for the received port * else, if Write flag is received * set port value */ if(mode_flag == 'D') { switch(port_name) { case 'B': DDRB = hex_value; break; case 'C': DDRC = hex_value; break; case 'D': DDRD = hex_value; break; case 'E': DDRE = hex_value; break; case 'F': DDRF = hex_value; break; } } else if(mode_flag == 'W') { switch(port_name) { case 'B': PORTB = hex_value; break; case 'C': PORTC = hex_value; break; case 'D': PORTD = hex_value; break; case 'E': PORTE = hex_value; break; case 'F': PORTF = hex_value; break; } } }###
Circuit Diagrams
Project Datasheet
Project Video
Filed Under: Electronic Projects
Filed Under: Electronic Projects
Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.
Tell Us What You Think!!
You must be logged in to post a comment.