In this project, a device will be designed that will read analog data from any analog sensor and will send the digitized form of that data to a personal computer on USB interface. On PC, a desktop application will store the data in an excel spreadsheet therefore performing the data logging. 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. The control transfer will be used for enumeration of the device. After enumeration, the analog readings will be digitized and sent to the host computer on a real-time basis using Interrupt Transfer. In this project, Accelerometer Sensor – ADXL335 will be used as analog sensor. Any other analog sensor can also be used and tested with minor modifications in this project.
The device will need a controller chip to handle send digitized data on USB interface to the host computer. 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 responsible for implementation of the USB Protocol. The device is tested on a Linux system using Python based Pyusb and Libusb frameworks for receiving data from peripheral device to the host computer. Another Python based desktop application – openpyxl is used for data logging to an XML file. . For using the project device with windows operating system, similar desktop software for reading or writing data to USB and data logging has to be used.
Fig. 1: Prototype of AVR based USB Data Logger
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.
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 and using ADC channels for analog to digital conversion. 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. ADXL335 Accelerometer Sensor
5. Micro USB cable
SOFTWARE TOOLS REQUIRED
1. WinAVR Studio
2. AVR Dude
5. Pyserial 2.7
6. Openpyxl
BLOCK DIAGRAM
Fig. 2: Block Diagram of Arduino based DIY USB Analog Data Logger
CIRCUIT CONNECTIONS
The analog sensor used in the device is ADXL335. The ADXL335 is a three axis Accelerometer that outputs analog data for axis X, Y, and Z direction at analog out pins. The analog out pins of the sensor will be connected to analog input pins of the microcontroller. The Analog pins are a hardware functionality of the microcontroller through which analog voltage can be measured. Since, three analog values will be read in real-time, the analog out pins of the sensor will be connected to three analog in pins of the controller.
The microcontroller will then convert the measured Analog voltage to Digital data. For analog to digital conversion, it will use the 10-bit resolution ADC (Analog to Digital Converter). Therefore, it will represent the analog signal in a range of 0-1023. Each Analog input pin will have its own ADC. Generally, the term channel is used to number the ADCs. For example, the Atmega 32u4 has twelve Analog pins and hence twelve ADC channels, 0-11. For three analog output signals (X, Y and Z), three ADC channels numbering from Channel4 to Channel6 will be used. These channels are specifically used because they are available on the Arduino Pro Micro board. However, if Atmega 32u4 is used externally any three out of the twelve channels can be used. The VCC and ground pins of the accelerometer sensor are connected to the common VCC and ground respectively. The Analog Out pins of the sensor are connected to the following Analog In pins of the Arduino
Fig. 3: Table listing circuit connections between Arduuino Pro Micro and ADXL335 Accelerometer Sensor
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.
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. The device designed in this project uses control transfer to enumerate with the host computer and then uses interrupt transfer to send real-time sensor data to the host computer for logging. The data will 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. Check out the Atmega 32u4 Based LED Status Project for learning about the Get_Report Class specific request.
Fig. 4: Image showing data log from AVR based USB Data Logger
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. The Data Output Report is used to receive data from the host while Data Input report is used to send data to 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. 5: Screenshot of HID_DESCRIPTOR_VENDOR Function in LUFA
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 -:
In LUFA framework, both the data input and data output reports are restricted to contain data packet 8-byte long. In this project, only six bytes of the data packet will be utilized.
HOW THE DEVICE WORKS
The device (microcontroller) will take readings from the analog sensor for X, Y and Z direction. After this it will convert analog data into digital data. Once the digital data is ready, it will transmit that data in a data packet to PC.
To transmit the data, the Device will create a 6 byte Data Report (data packet). The contents of Data Report will be -:
Fig. 6: Table listing data report of ADXL335 Accelerometer Sensor
The accelerometer sensor has a 16-bit long resolution for reading of each axis. That is why, a 6-byte long data report needs to be sent. 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 make aware the microcontroller of the circuit connections.
Fig. 7: Image showing data logged from ADXL335 Accelerometer Sensor in an Excel Sheet
The Data Report will be then collected by Application running on Host (PC). The Application will then calculate the acceleration in X, Y and Z axis in terms of g (gravitational acceleration). After calculation, it will store the output in an excel sheet. 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 collection and logging process will repeat every 500 Milliseconds.
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 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.
A python script has been written to run on the desktop side. The script can be written and saved as a file during testing this USB device or it can be downloaded along with the other project files from engineersgarage and run using command prompt or a command line interpreter during testing of the device.
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 #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 order to use the in-built ADC channels, ADC.h library must be imported in the GenericHID.c file. Save the ADC.h in the same folder and add the following include statements -:
In the main() function of GenericHID.c the microcontroller needs to be made aware of the circuit configuration. Inside the main function Port F where the Analog Out pins are interfaced should be defined as input. The ADC should be initialized using InitADC() function. So add the following statements in the 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
Inside this function, the microcontroller will read analog data for each axis and will convert them to digital data. This digital data for each axis will be transmitted to Host using Data Report. The function will have the following statements -:
In the function body, a variable adc_data is declared to hold the 16-bit value of analog reading for any axis. The readings for each axis are converted to digital data using ReadADC() function where the function takes the ADC channel number as the parameter. The data is then transmitted to the host computer by assigning it to different bytes of the data packet.
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 removed 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 USB Data Logger 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 Controlled Servo Motor, learn how to control a servo motor from a personal computer on USB interface.
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" // include ADC library #include "adc.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(); DDRF = 0x00;// PORTF as input port InitADC(); // initialize analog to digital converter //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; // variable to store Analog to Digital Converted data uint16_t adc_data; //read channel 4 adc_data = ReadADC(0x04); //get LSB Data[0] = adc_data & 0xff; //get MSB Data[1] = (adc_data >> 8) & 0xff; //read channel 5 adc_data = ReadADC(0x05); //get LSB Data[2] = adc_data & 0xff; //get MSB Data[3] = (adc_data >> 8) & 0xff; //read channel 6 adc_data = ReadADC(0x06); //get LSB Data[4] = adc_data & 0xff; //get MSB Data[5] = (adc_data >> 8) & 0xff; *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 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.