USB communication with CCS

From Mech
Jump to: navigation, search

A sample program using CCS's CDC library is shown below. The program waits for some input and then responds to it. When you first plug in the PIC to the computer, Windows will need to install a driver to talk to it. If you're running XP or earlier, point it to the directory C:\Program Files\PICC\Drivers, where it will find what it needs. If you're running Vista the driver may not be there; download File:Cdc NTXPVista.inf, save it somewhere, and point Windows to it. Once the driver is installed a virtual COM port will be created (it will be visible in the device manager) and you'll be able to talk to the PIC in Hyperterminal, Matlab, or anything else that communications over RS232.

#include <18f4550.h> //if your version of the compiler doesn't support the 4553, you can put the 4550 in your code, which is almost exactly the same.
#use delay(clock=48000000) //because of tricky fuses a 20Mhz oscillator will make the PIC run at 48Mhz
#fuses HS, NOWDT, NOLVP, NOPROTECT //standard fuses

//these fuses are critical. they assume a 20Mhz oscillator:
#fuses PLL5     //The USB module must run at 48Mhz. This tells the PIC to take the oscillator, divide the frequency by 5, then multiply by 12. The result must be 48Mhz. 
#fuses HSPLL    //I'm not exactly sure what this fuses does, but it's probably necessary.
#fuses VREGEN   //The USB module must run at 3.3V. This tells the PIC to accomplish this by using an internal voltage regulator.
#fuses CPUDIV1  //This tells the PIC to run at a frequency of 48Mhz / 1 = 48Mhz. It may or may not be necessary.

#include <usb_cdc.h> //Include the USB CDC library. If you want to see all the functions available look at usb_cdc.h and usb.h.

void main() {
   int c;

   //these lines do some initialization, obviously:

   while(true) {
       usb_task(); //handles connections to and disconnections from the computer, registering the PIC with the computer, etc. call this pretty often so that the PIC responds to being plugged in. 
       if(usb_cdc_kbhit()) { //did we get some incoming data? 
           c = usb_cdc_getc(); //get one character of input
           printf(usb_cdc_putc, "you typed: %c\r\n", c); //print out a response over usb
Personal tools