Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe

Atmega 32u4 Based USB Controlled LED Series (Part 20/25)

By Amanpreet Singh February 15, 2017

Throughout this USB series, different types of USB devices have been designed and developed. These devices were enumerating with the host computer and then were using Class Specific transfers for further USB communication. Like the Keyboard, Mouse and joystick devices were using interrupt transfers for their operations after enumeration. Similarly, the audio class devices were using isochronous transfers for their operations after enumeration. The CDC Class devices were using bulk transfers for their operations after enumeration. Any of these transfers (Bulk, Isochronous or Interrupt) are enabled only after the control transfer which let the device get enumerated with the host. These transfers are required when data is also sent from the device to the host computer.

In this project, an USB device to control an LED series will be designed. The device will not send any data to the host computer but will only read data from the host computer and control LEDs accordingly. In such type of USB communication, only control transfer is sufficient to implement the device functioning and so only Endpoint 0 is involved in the USB communication.

The project will need a controller chip to handle USB data from the computer and to operate LED series accordingly. 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 sending data from computer to the device.

Prototype of Arduino based USB Controlled LED Series

Fig. 1: Prototype of Arduino based USB Controlled LED Series

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 four LEDs connected to it which will be switched ON or OFF from the computer.

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 receiving digital output at the Arduino pins.

COMPONENTS REQUIRED

1. Arduino Pro Micro

2. Breadboard

3. Connecting wires

4. LEDs

5. Micro USB cable

6. 10K resistors

SOFTWARE TOOLS REQUIRED

1. WinAVR Studio

2. AVR Dude

3. LUFA Firmware

4. Python 2.7.12

5. Pyserial 2.7

BLOCK DIAGRAM

Block Diagram of Arduino based USB Controlled LED Series

Fig. 2: Block Diagram of Arduino based USB Controlled LED Series

CIRCUIT CONNECTIONS

The project uses Arduino Pro Micro as the USB controller chip. A series of four LEDs is connected at the port B of the Arduino. The LEDs are connected at pins 2, 4, 5 and 6 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.

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 made in this project only handles to receive data from 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.

Image of Arduino based USB Controlled LED Series

Fig. 3: Image of Arduino based USB Controlled LED Series

In case of LED series, after configuring with the host device, it has to communicate with the host in the form of control transfers only for reading data from the host computer. The Control Transfer can also be used to exchange data between Device and PC like the other transfer types. The Class Specific Requests of Control Transfer will be used to send data from Host (PC) to the Device (Microcontroller).

In HID class, two types of Transfer Types are used: Control Transfer and Interrupt Transfer. Generally, the Interrupt Transfer is used to send Data Reports. But the Control Transfer can also be used when Interrupt Endpoints are not declared or available. The Default Control Endpoints (Endpoint 0) are always available so control transfer can also be used to send or receive data anytime. The data can be exchanged using Class-Specific Requests. These Requests are sent by Host to Device via Control Transfer. The Set_Report is the request by which Host can send data to Device.  The Set_Report request is structured in the following manner -:

Table listing data structure of Set_Report request

Fig. 4: Table listing data structure of Set_Report request

The data will be transferred using Data Packet or Data Report. The Data Report (Data Packet) will contain four bytes. These bytes will be used to indicate the device to switch ON/OFF the LEDs. Therefore the LEDs and data report received by control transfer from the host computer will be related in the following manner -:

Table listing Data Packet structure for LED Series Control

Fig. 5: Table listing Data Packet structure for LED Series Control

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 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.  The Generic HID Class can also send data to the host computer in the form of Data Input Report but that feature will not be used by the project.

Screenshot of Data Input Report from USB LED Series Controller

Fig. 6: Screenshot of Data Input Report from USB LED Series Controller

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 ().

Screenshot of HID_DESCRIPTOR_VENDOR Function in LUFA Library

Fig. 7: Screenshot of HID_DESCRIPTOR_VENDOR Function in 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 OUTPUT REPORT

The Data Output report for generic HID device simply contains data of a size restricted by the usage report. It is defined in the following manner -:

Screenshot of Data Output report for generic HID device in LUFA Library

Fig. 8: Screenshot of Data Output report for generic HID device in LUFA Library

HOW THE DEVICE WORKS

The device will receive data from the host computer on control transfer. Since, data is to be received from the host device CALLBACK_HID_Device_ProcessHIDReport() 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 control switching of LEDS. 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 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.

Screenshot of LUFA Library Folder on Windows

Fig. 9: 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.

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 #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 the microcontroller needs to be made aware of the circuit configuration. Inside the main function Port B where the LEds have been connected needs to be defined as output and all the pins of port B has to be raised to LOW logic by default as the LEDs should remain in OFF state by default. So add the following statements in the beginning of main() function.

int main(void)
{
SetupHardware();
 
DDRB = 0xff;  // make PORTB as output port
PORTB = 0x00; // make all pins low
 
//LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
GlobalInterruptEnable();
 
for (;;)
{
HID_Device_USBTask(&Generic_HID_Interface);
USB_USBTask();
}
}

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.

Screenshot of CALLBACK_HID_Device_ProcessHIDReport Function of LUFA Library

Fig. 10: Screenshot of CALLBACK_HID_Device_ProcessHIDReport Function of LUFA Library

The controller chip receives 4-byte data from the host computer and according to that data, it changes the status of LEDs. If 0x00 is received in a byte, a LOW logic is sent to the respective pin switching the respective LED OFF.  If 0x01 is received in a byte, a HIGH logic is sent to the respective pin switching the respective LED ON. So replace the body of the function with the following code -:

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;
 
if (Data[0] == 0x01)
 PORTB |= 0b00010000;   // switch on led1
else
PORTB &= 0b11101111; // switch off led1
 
if (Data[1] == 0x01)
 PORTB |= 0b00100000;   // switch on led2
else
PORTB &= 0b11011111; // switch off led2
 
if (Data[2] == 0x01)
 PORTB |= 0b01000000;   // switch on led3
else
PORTB &= 0b10111111; // switch off led3
 
if (Data[3] == 0x01)
 PORTB |= 0b00000100;   // switch on led4
else
PORTB &= 0b11111011; // switch off led4
}

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.

Screenshot of CALLBACK_HID_Device_CreateHIDReport Function of LUFA Library

Fig. 11: Screenshot of CALLBACK_HID_Device_CreateHIDReport Function of LUFA Library

All the statements in this function will be cleared as the device will not send any data to the host computer. Therefore, the CALLBACK_HID_Device_CreateHIDReport() function will be left with an empty body.

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)
{
}

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 Series 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

For running the Host Application, Python and Pyusb need to be installed. If using Ubuntu, then the python is already installed. The external package that needs to be installed is Pyusb. To test the device with desktop computer, a python script will be written and run on command line. Open Notepad++ or use a python specific IDE (like PythonWin for Windows, IDLE for Linux and Macintosh) to write the following script. 
 
First two libraries – core and util from the pyusb package are imported. 
 
import usb.core  # import usb core library from pyusb
import usb.util
 
Two variables to hold Vendor ID and Product ID are declared. The values passed in the variables are same as of the values assigned in the modified Make file. 
 
vid = 0x03EB
pid = 0x204F
 
An object of the USB type is declared and identified by the vendor ID and product ID variables. The object identifies the USB device with the desktop. 
device = usb.core.find(idVendor=vid,idProduct=pid)
 
A message is printed on the terminal to inform about the application. 
print(‘LED Blinking Test application based on Control Transfern’)
 
The USB device is detected in an exception handling trial using the functions from the core library. 
if device is None:
sys.exit(“Could not find USB device.”)
 
if device.is_kernel_driver_active(0):
        try:
            device.detach_kernel_driver(0)
        except usb.core.USBError as exception:
            sys.exit(“Could not detatch kernel driver: %s” % str(exception))
 
Once the device is detected, it is configured using the set_configuration() method on the “device” object. The device is again configured in an exception handling statement. 
try:
device.set_configuration()
except usb.core.USBError as exception:
sys.exit(“Could not set configuration: %s” % str(exception))
 
An array “data_report” containing the default data bytes to be sent to the microcontroller is defined. The bytes respective to all the four LEDs are defined 0x00 in the array which corresponds to OFF state of the LEDs. 
data_report = [0x00, 0x00, 0x00, 0x00]
 
An infinite while loop is called in which the user is prompted to select switching LEDs ON or OFF by entering number 1 or 0. After selecting one of the two operations, the user is prompted to select an LED to perform switching by entering a number between 0 and 5. Based on the selection of the LED, respective byte in the data_report array is changed to 0x01 for ON operation or 0x00 for OFF operation. The data_report array is passed to the microcontroller using control transfer. For implementing control transfer, ctrl_transfer() method on “device” object is used and assigned to number_of_bytes_written variable. The control transfer statement is tested for error handing using assert statement on the  number_of_bytes_written object. The assert statement verifies if the data report sent to the microcontroller equals to the length of the data_report array ensuring all the bytes are transferred to the microcontroller. 
 
while(1):
# Send the generated report to the device
value = raw_input(“Enter 1 to ON a LED, 0 to OFF a LEDn”)
if value is ‘1’:
led_no = raw_input(“Enter LED number, 1-4n”)
if int(led_no) > 0 and int(led_no) < 5:
data_report[int(led_no) – 1] = 0x01
print(led_no + ‘ ONn’)
else:
print(‘Not a valid numbern’)
elif value is ‘0’:
led_no = raw_input(“Enter LED number, 1-4n”)
if int(led_no) > 0 and int(led_no) < 5:
data_report[int(led_no) – 1] = 0x00
print(led_no + ‘ OFFn’)
else:
print(‘Not a valid numbern’)
else:
print(‘Not a valid optionn’)
 
number_of_bytes_written = device.ctrl_transfer(  # Set Report control request
        0b00100001,  # bmRequestType (Host to Device Control Request)
        0x09,        # bmRequest (Set_Report Request)
        0,           # wValue (MSB is report type, LSB is report number)
        0,           # wIndex (interface number)
        data_report  # report data to be sent
    );
assert number_of_bytes_written == len(data_report)
 
Write the python code using an IDE or Notepad++ and save it as a file. The application can be run by the terminal on Linux. First, change the current directory of the terminal window to the directory where the application is present, then run the command sudo python <application name>.py. After pin connections and uploading the firmware, plug the device using a USB micro cable and open the command prompt or command-line interpreter to run the python script from saved file.  

In the next project – Atmega 32u4 Based USB LED Status, learn how to use interrupt transfer for sending data from microcontroller to the host computer.

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 = 0xff;  // make PORTB as output port

PORTB = 0x00; // make all pins 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)

{

}


/** 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;


if (Data[0] == 0x01)

 PORTB |= 0b00010000;   // switch on led1

else

PORTB &= 0b11101111; // switch off led1


if (Data[1] == 0x01)

 PORTB |= 0b00100000;   // switch on led2

else

PORTB &= 0b11011111; // switch off led2


if (Data[2] == 0x01)

 PORTB |= 0b01000000;   // switch on led3

else

PORTB &= 0b10111111; // switch off led3


if (Data[3] == 0x01)

 PORTB |= 0b00000100;   // switch on led4

else

PORTB &= 0b11111011; // switch off led4

}

###

 


Circuit Diagrams

Circuit-Diagram-Arduino-Based-USB-Controlled-LED-Series

Project Video


Filed Under: Electronic Projects

 

Next Article

← Previous Article
Next Article →

Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.



Tell Us What You Think!! Cancel reply

You must be logged in to post a comment.

EE TECH TOOLBOX

“ee
Tech Toolbox: 5G Technology
This Tech Toolbox covers the basics of 5G technology plus a story about how engineers designed and built a prototype DSL router mostly from old cellphone parts. Download this first 5G/wired/wireless communications Tech Toolbox to learn more!

EE Learning Center

EE Learning Center
“engineers
EXPAND YOUR KNOWLEDGE AND STAY CONNECTED
Get the latest info on technologies, tools and strategies for EE professionals.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


RSS EDABOARD.com Discussions

  • Thermal modelling of repetitive power pulse
  • Redundant XORs
  • No Output Voltage from Voltage Doubler Circuit in Ansys Nexxim (Harmonic Balance Simulation)
  • Discrete IrDA receiver circuit
  • ISL8117 buck converter blowing up

RSS Electro-Tech-Online.com Discussions

  • Is AI making embedded software developers more productive?
  • Simple LED Analog Clock Idea
  • Can I make two inputs from one??
  • Behlke swich
  • using a RTC in SF basic

Featured – LoRa/LoRaWan Series

  • What is the LoRaWAN network and how does it work?
  • Understanding LoRa architecture: nodes, gateways, and servers
  • Revolutionizing RF: LoRa applications and advantages
  • How to build a LoRa gateway using Raspberry Pi
  • How LoRa enables long-range communication
  • How communication works between two LoRa end-node devices

Recent Articles

  • RPi Python Programming 21: The SIM900A AT commands
  • RPi Python Programming 22: Calls & SMS using a SIM900A GSM-GPRS modem
  • RPi Python Programming 23: Interfacing a NEO-6MV2 GPS module with Raspberry Pi
  • RPi Python Programming 24: I2C explained
  • RPi Python Programming 25 – Synchronous serial communication in Raspberry Pi using I2C protocol

EE ENGINEERING TRAINING DAYS

engineering

Submit a Guest Post

submit a guest post
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • Battery Power Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • EV Engineering
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • Subscribe to our newsletter
  • About Us
  • Contact Us
  • Advertise

Copyright © 2025 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy

Search Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe