Hi, these days I did some testing for the management, through the USB protocol, of a stream of data to a PIC18F2550, using an HID class device firmware and VisualC # as a language for the application on Windows, and i wanted to publish my work (more than a week working on).
We start from the hardware configuration that i made on breadboard, it is standard pattern for this type of applications, which can be expanded at will of the designer (the pattern is a classic pattern taken from the web, nothing innovative):

I have attached a series of 8 LEDs with 220 Ohm resistors on PORTB and LEDs on the port that flashes when the USB is recognized by Windows. The firmware that i did, as HID class, can be modified at will to determine how big the buffer must be read and write via USB, and to give a unique identification code so that it is not confused with other USB devices connected to the PC, this code is given by the pair VID and PID (Vendor ID and Product ID), which in my case i chose 1234 and 0001 (in hex). Written and compiled the HID descriptor, coupled to the main(), or what determines what to do when they get data from USB, you have to program the PIC18F2550. Hex is available in the source that i provides.
The first time you connect the hardware inside the FW just mentioned, Windows will install automatically HID (Human Interface Device) which can be seen between devices (resource management), assigned with your own VID and PID.
We now have the hardware connected and recognized, not just open the door of communication via the USB HID class with a programming language of your choice, i typically use the C or Basic, essentially, but because i want a nice view interface i use VisualC # (via the programming of Windows Forms).
The program i wrote is very simply: you connect the device with VID and PID 1234 and 0001, and once connected you can send a byte to the PIC via USB typing data in a box, in decimal, and pressing SEND.
This is the first step to communicate from one application to win out on a device interfaced to the USB, everything has been written by hand, FW and SW, and so we have full control (or almost) of everything happens and what can not work.
Here is an issue on which i spend some time, but not much yet.
To properly write the firmware (written in C) on the PIC, through any programmer, you must properly configure the configuration bits of the microcontroller. The PIC that i have chosen have this internal structure block (as you note is a page of datasheet from Microchip ®, please read it for more detail):

We need to set the behavior of the multiplexer according to our oscillator, i chosen a crystal of 4 MHz, then the correct settings (found after several trials) are these:
- 96 MHz PLL prescaler : No Divide (4 MHz input)
- CPU System Clock Postscaler: [OSC1/OSC2 Src: /1][96MHz PLL Src: /2]
- Full-Speed USB Clock Source Selection: Clock src from OSC1/OSC2
- Oscillator: XT: USB-XT
It ‘s very important to use XT oscillator and NOT HS if we use a crystal, and also that the USB works at 48 MHz, as we are doing now, in fact signed by the multiplexer with selection USBDIV is coming out exactly a frequency of 48 MHz, half of that generated by the internal PLL.
If these paths are not set up correctly with the internal configuration bit, windows does not recognize anything, placing doubts over the entire system, will the FW I’ve written correct? HW will be wrong some connection? … probably not been set correctly these configuration bits.
Last thing very important and quite critical, due to many failures, is the capacitor on VUSB of 220nF, the value is not critical, but criticism is its lack.
Now let’s see some pictures of HW and then a video of the operation:




I’ll give you the source of the firmware, also you will find the . hex ready for those wishing to try
FW Sources
Here are the sources in VisualC # application that communicates with the device, will find the sources and also the little program already compiled in executable format:
HID Sources (Visual C)
Executable (.exe)
If you want you can try to read some source, modify it, recompile it for other PICs, for example, 18F4550, and if you try even if the exe will run properly with your HW / FW, use other ports of the PIC, have them do other things (instead to view the status with the 8 LEDs), everything is editable and customizable.
As you may have noticed i have not made a pcb as this trial is not definitive but is a pattern seen more as a “testbench” for various uses, attempts to work at an hardware and software interfaced to the USB device under the operating system Microsoft Windows.
All the real work was to understand how the bytes are sent via USB from a Windows application to a digital port of a MCU, so most of the time was used to fully understand how to write the HID firmware and run it with all the real problems encountered as settings, frequency, fuses … etc. ..
I hope it was to your liking.
Salve a tutti, in questi giorni ho fatto dei test per quanto riguarda la gestione, tramite protocollo USB, di un flusso di dati verso un PIC18F2550, usando un HID class device come firmware e VisualC# come linguaggio per l’applicazione su Windows, e volevo rendere pubblico il mio lavoro (durato più di una settimana).
Partiamo dalla configurazione hardware che ho realizzato su breadboard, schema che è standard per questo tipo di applicazioni, che può essere ampliato a piacimento del progettista (lo schema è uno schema classico preso dalla rete, nulla di innovativo):

Io ho collegato una serie di 8 led con relative resistenze da 220 Ohm sulla PORTB e un led sulla PORTA che lampeggia quando la USB è riconosciuta da Windows. Il firmware che ho fatto, come HID class, è modificabile a piacimento per poter stabilire quanto dev’essere grande il buffer in lettura e in scrittura tramite USB, e per dare un codice di identificazione univoco di modo che non venga confuso con altri dispositivi USB collegati al PC, questo codice è dato dalla coppia VID e PID (Vendor ID e Product ID), che nel mio caso ho scelto 1234 e 0001 (in hex). Scritto e compilato il descrittore HID, accoppiato al main vero e proprio, ovvero quello che stabilisce cosa fare quando arrivano dati dalla USB, si programma il PIC18F2550 con il .hex che è disponibile nei sorgenti che vi metto a disposizione.
La prima volta che si collega l’HW con il FW appena citato all’interno, win installerà in automatico un HID (Human Interface Device) che potrete vedere tra le periferiche (gestione risorse), con assegnati proprio il vostro VID e PID.
Ora abbiamo l’HW collegato e riconosciuto, non resta che aprire la porta di comunicazione USB tramite l’HID class con un vostro linguaggio di programmazione a scelta, in genere si usa il C o il Basic, di base, ma siccome voglio una interfaccia visuale piacevole io uso VisualC# (tramite la programmazione delle Windows Form).
Il programma che ho scritto fa molto semplicemente due cose: si connette al dispositivo con VID e PID 1234 e 0001, e una volta connesso si può inviare un byte al PIC tramite USB digitandolo in una casella, in decimale, e premendo INVIA.
Questo è il primo passo per comunicare da un applicazione win verso l’esterno su un dispositivo interfacciato alla USB, tutto è stato scritto “a mano”, FW e SW, e per questo abbiamo il pieno controllo (o quasi) di tutto quello che succede e di quello che può non funzionare.
Vediamo ora un punto sul quale ho perso un po, ma non molto, tempo.
Per scrivere correttamente il firmware (scritto in C) sul PIC, tramite qualsiasi programmatore, è necessario configurare correttamente i configuration bit del microcontrollore. Il PIC da me scelto ha questa struttura interna a blocchi (come si nota è una pagina del datasheet della Microchip®, che vi invito a leggere):

Dobbiamo settare il comportamento dei multiplexer in base al nostro oscillatore, io ho scelto un quarzo da 4 MHz, quindi i settaggi corretti (trovati dopo varie prove) sono questi:
- 96 MHz PLL prescaler : No Divide (4 MHz input)
- CPU System Clock Postscaler: [OSC1/OSC2 Src: /1][96MHz PLL Src: /2]
- Full-Speed USB Clock Source Selection: Clock src from OSC1/OSC2
- Oscillator: XT: USB-XT
E’ molto importante usare XT oscillator e NON HS se usiamo un quarzo, ed inoltre che la USB lavori a 48 MHz, come stiamo facendo ora, infatti dal multiplexer con selezione siglata USBDIV sta uscendo esattamente una frequenza di 48 MHz, metà di quella generata dal PLL interno.
Se non si settano correttamente questi percorsi interni con i configuration bit, win non riconoscerà proprio niente, ponendo dubbi su tutto l’intero sistema, sarà il FW che ho scritto? Sarà sbagliata qualche connessione nell’HW? …molto probabilmente non sono stati settati correttamente questi bit di configurazione.
Ultima cosa molto importante e abbastanza critica, causa di molti mancati funzionamenti, è il condensatore sulla VUSB da 220nF, il valore non è critico ma è critica la sua mancanza
Vediamo ora alcune immagini dell’HW e poi un video del funzionamento:




Vi fornisco i sorgenti del Firmware, all’interno trovate anche l’.hex già pronto per chi volesse provare
FW Sources
Ecco i sorgenti in VisualC# dell’applicazione che dialoga con il dispositivo, trovate i sorgenti ed anche il programmino già compilato in formato eseguibile:
HID Sources (Visual C)
Executable (.exe)
Se potete provate a leggervi qualche sorgente, modificare, ricompilare per altri PIC, ad esempio 18F4550, e se potete provate anche se l’exe vi gira correttamente con il vostro HW/FW, usate altre porte del PIC, fategli fare altre cose (invece di visualizzare lo stato con gli 8 LED), insomma sbizzarritevi potete fare di questi materiali ciò che volete, è tutto liberamente modificabile e personalizzabile.
Come avrete notato non ho fatto un pcb in quanto questa è sperimentazione, non è uno schema definitivo ma più che altro un “banco di prova” per vari utilizzi, tentativi di far collaborare a livello HW e SW un dispositivo interfacciato alla USB sotto sistema operativo Microsoft Windows.
Tutto il lavoro vero e proprio è stato capire come mandare via USB dei byte da una applicazione Windows ad una porta digitale di una MCU, quindi la maggior parte del tempo è stato impiegato a capire a fondo come scrivere il firmware HID e farlo funzionare, con tutti i problemi reali che si incontrano come settaggi, frequenza, fuses… ecc..
Spero sia stato di vostro gradimento