Here is a bit of code I am using at the moment that seems to work well.
Wait for 255 to be sent from PC then samples and sends reply back.
Code:
'************************************
'Define ADCIN parameters
' Set number of bits in result
DEFINE ADC_BITS 10
' Set clock source (3=rc)
DEFINE ADC_CLOCK 3
' Set sampling time in microseconds
DEFINE ADC_SAMPLEUS 10
' Set PORTA to all input
TRISA = %11111111
' Set up ADCON1 to tell it to right justify and enable A/D channel 0
ADCON1 = %10000010
' Maximum buffer size
USBBufferSizeMax con 8
' Input buffer size
USBBufferSizeTX con 8
' Output buffer size
USBBufferSizeRX con 8
' The USB buffer variables...
USBBuffer Var ByteUSBBufferSizeMax
USBBufferCount Var Byte
' Other variables
datawait var byte
' Create variable to store result
adcVar VAR WORD
'Wait Half a second let ADC settle
pause 500
' Initialise USB...
usbinit
***' ***************************************************************
***' * Start of Main Routine ** **
***' ***************************************************************
usbstart:
'Clear main wait variable
datawait=0
'Go check for a USB packet
gosub DoUSBIn
' Check data Received in and load variables
datawait=usbbuffer(0)
'Check if PC wants ADC sent back
if datawait=255 then
'Gosub main ADC routine
gosub main
endif
'Go back to the start and wait for the next command
goto usbstart
*' *************************************************************
*' * Main Sample Routine **
*' *************************************************************
main:
' Read channel 0
ADCIN 0, adcVar
' Wait.01 second
Pause 10
'Shift the result down to 10 bits
ADcvar = adcvar >> 6
'Set the Result
usbbuffer(0)=adcvar.highbyte
usbbuffer(1)=adcvar.Lowbyte
'Send it out to PC
gosub dousbout
return
*' *************************************************************
*' * Receive data from the USB bus **
*' *************************************************************
DoUSBIn:
' RX buffer size
USBBufferCount = USBBufferSizeRX
' Keep connection alive
USBService
' Read data, if available
USBIn 1, USBBuffer, USBBufferCount, DoUSBIn
return
*' *************************************************************
*' * Send Data out **
*' *************************************************************
DoUSBOut:
' TX buffer size
USBBufferCount = USBBufferSizeTX
' Keep connection alive
USBService
' If bus available, transmit data
USBOut 1, USBBuffer, USBBufferCount, DoUSBOut
return
Cheers
Sean.
Bookmarks