Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
Universal Serial Bus (USB) is a widely used interface for communication between computers and peripheral devices. In the context of microchip environments, USB connectivity can be crucial for applications such as data logging, firmware updates, and communication with sensors or other microcontrollers. This article will guide you through the process of interfacing USB with Microchip microcontrollers, specifically focusing on the PIC18F4550, which has built-in USB support.
Examples:
Setting Up the Hardware:
Configuring the Microcontroller:
#include <xc.h>
#include <usb.h>
#include <usb_device_hid.h>
#pragma config FOSC = HSPLL_HS
#pragma config PLLDIV = 5
#pragma config CPUDIV = OSC1_PLL2
#pragma config USBDIV = 2
#pragma config FCMEN = OFF
#pragma config IESO = OFF
#pragma config PWRT = ON
#pragma config BOR = ON
#pragma config BORV = 3
#pragma config VREGEN = ON
#pragma config WDT = OFF
#pragma config MCLRE = ON
#pragma config LPT1OSC = OFF
#pragma config PBADEN = OFF
#pragma config CCP2MX = ON
#pragma config STVREN = ON
#pragma config LVP = OFF
#pragma config XINST = OFF
Initializing the USB Module:
void main(void) {
USBDeviceInit(); // Initialize USB
USBDeviceAttach(); // Attach USB
while(1) {
USBDeviceTasks(); // Handle USB tasks
// Your application code here
}
}
Creating a Simple HID Device:
const struct { uint8_t report[HID_RPT01_SIZE]; } hid_rpt01 = {
{
0x06, 0x00, 0xFF, // Usage Page (Vendor Defined Page 1)
0x09, 0x01, // Usage (Vendor Usage 1)
0xA1, 0x01, // Collection (Application)
0x19, 0x01, // Usage Minimum (1)
0x29, 0x40, // Usage Maximum (64)
0x15, 0x00, // Logical Minimum (0)
0x26, 0xFF, 0x00, // Logical Maximum (255)
0x75, 0x08, // Report Size (8)
0x95, 0x40, // Report Count (64)
0x81, 0x02, // Input (Data,Var,Abs)
0x19, 0x01, // Usage Minimum (1)
0x29, 0x40, // Usage Maximum (64)
0x91, 0x02, // Output (Data,Var,Abs)
0xC0 // End Collection
}
};
void ProcessIO(void) {
if((USBDeviceState < CONFIGURED_STATE)||(USBSuspendControl==1)) return;
if(HIDRxHandleBusy(USBOutHandle) == false) {
// Process received data
USBOutHandle = HIDRxPacket(HID_EP, (uint8_t*)&ReceivedDataBuffer, 64);
}
if(HIDTxHandleBusy(USBInHandle) == false) {
// Prepare data to send
USBInHandle = HIDTxPacket(HID_EP, (uint8_t*)&ToSendDataBuffer, 64);
}
}