Ttelmah
Joined: 11 Mar 2010 Posts: 19361
|
|
Posted: Wed May 29, 2013 2:41 am |
|
|
At heart, USB, _is_ complex. There has to be replies and messages going on all the time. Fortunately, you don't have to worry about this at all.
ex_usb_serial.c, is just a slight expansion on a 'hello world' type application using the RS232, and USB, sending just a 'CCS CDC (Virtual RS232) Example" message to the RS232, , followed by the version number. Then sitting and echoing stuff back to the USB and the RS232.
As an example, This is a basic 'hello world' using CDC.
Code: |
#include <18F2550.h>
#device adc=10
#fuses HSPLL, NOWDT, PLL2, CPUDIV1, USBDIV, VREGEN, NOPROTECT, BORV42, NOPBADEN
#FUSES BROWNOUT, PUT, STVREN, NODEBUG, NOLVP, NOWRT, NOWRTD, NOWRTB, NOWRTC, NOCPD, NOCPB, NOEBTR, NOEBTRB, NOXINST, NOMCLR
#use delay(clock=48000000)
//This assumes a 8MHz crystal. Chance 'PLLx' to suit your crystal.
//Can be 4,8, 12, 16, 20 or 24Mhz.
//Beyond this other changes are needed.....
#define USB_CON_SENSE_PIN PIN_B2
#define PIN_USB_SENSE USB_CON_SENSE_PIN
#define USB_CABLE_IS_ATTACHED() input(PIN_USB_SENSE)
int1 usb_cdc_oldconnected=FALSE;
//Now a thing that is commonly 'missed', is that if your unit has it's own
//5v power, the connection sense pin is _required_ by the USB specs.
//Disconnection/reconnection will not be handled properly without it.
#include <stdlib.h>
#define __USB_PIC_PERIF__ 1
// Includes all USB code and interrupts, as well as the CDC API
#include <usb_cdc.h>
void main(void)
{
setup_adc_ports(NO_ANALOGS);
setup_comparator(NC_NC_NC_NC);
usb_init_cs();
usb_cdc_init();
while (true)
{
if (usb_attached())
{
usb_task();
if (usb_enumerated())
{
if (usb_cdc_carrier.dte_present)
{
if (usb_cdc_oldconnected==FALSE)
{
printf(usb_cdc_putc,"Hello World\n\r");
usb_cdc_oldconnected=TRUE;
}
if (usb_cdc_kbhit())
{
//use usb_cdc_getc here to read the character and do what
//you want
usb_cdc_putc(toupper(usb_cdc_getc()));
//as a demo, return the character converted to upper case
}
if (your_button_is_pressed())
{
//Obviously you need to work out how this function is done...
printf(usb_cdc_putc,"Button is pressed\n\r");
}
}
}
}
else
{
usb_cdc_oldconnected=FALSE;
usb_cdc_init(); //clear buffers if disconnected
}
}
}
|
Now, this if connected to a terminal program, will return 'Hello World', when this connects. It'll then echo text typed back, converted to upper case.
The actual output and input, is really the same as using RS232. usb_cdc_getc, instead of getc, etc.. 80% of the extra complexity is the much larger string of fuses to setup the PIC, and the extra code needed to handle if the application disconnects, or the cable is disconnected etc..
Then if you have a function 'your_button_is_pressed', which returns 'true' when the button is pressed, I show how to send a message.
Best Wishes |
|