New User - Help needed please with USB code

Coding and general discussion relating to the compiler

Moderators: David Barker, Jerry Messina

Post Reply
M0DJH
Posts: 4
Joined: Wed Sep 12, 2018 9:06 am

New User - Help needed please with USB code

Post by M0DJH » Thu Sep 13, 2018 8:18 am

Hi everyone,
I am new to Swordfish but it looks like it can do exactly what I want. I found the bit of code below and I would like your opinion on whether it would work and any changes that would be necessary to establish USB/232 comms with a PC running WIN10.

]// device and clock...
Device = 18F2550
Clock = 48

// 20Mhz crystal, 48Mhz internal (FS USB)
Config
PLLDIV = 5,
CPUDIV = OSC1_PLL2,
USBDIV = 2,
FOSC = HSPLL_HS,
VREGEN = ON

// import modules...
Include "usbcdc.bas"
Include "convert.bas"

// local variables...
Dim Value As Byte
Dim ValueAsString As String

Sub ClearUSART()
'Dim tmpByte As Byte
While CDC.DataAvailable = True
cdc.read(valueasstring) 'tmpByte = RCRegister
Wend
CDC.ClearOverrun
End Sub


// main program...

cdc.ReadTerminator = #13
clearusart
// wait for a CR to be received...
Repeat
Until ReadByte = 13

// main program loop - ask for a number between 1 and 10, then
// check range - if number is OK, display value multiplied by two...
While true
cdc.Read(ValueAsString)
clearusart
Write("Enter a number between 1 and 10",13,10)

cdc.Read(ValueAsString)
Value = StrToDec(ValueAsString)
If (Value < 1) Or (Value > 10) Then
cdc.Write("Number out of range!",13,10)
Else
cdc.Write("Value ",DecToStr(Value)," multiplied by 2 is ",DecToStr(Value * 2),13,10)
EndIf
clearusart
Wend

Thanks for taking the time to look at this code and all comments, suggestions or better ideas and example code are welcome...........

Jerry Messina
Swordfish Developer
Posts: 1469
Joined: Fri Jan 30, 2009 6:27 pm
Location: US

Re: New User - Help needed please with USB code

Post by Jerry Messina » Thu Sep 13, 2018 2:02 pm

You might want to start off with a simple echo program...

Code: Select all

// import modules...
include "usbcdc.bas"

// wait for connection...
repeat
until Attached

// main program loop - this just simply reads a byte from a
// terminal window (for example, SerialCommunicator) and then
// echos it back...

while true
   if DataAvailable then
      WriteByte(ReadByte)
   endif
wend

M0DJH
Posts: 4
Joined: Wed Sep 12, 2018 9:06 am

Re: New User - Help needed please with USB code

Post by M0DJH » Thu Sep 13, 2018 3:52 pm

Thanks for the code, I will start with that and build on it......

Post Reply