Author Topic: Detecting COM ports??  (Read 2591 times)

0 Members and 1 Guest are viewing this topic.

Offline Mad Axeman

  • Newbie
  • Posts: 74
    • View Profile
    • My web site - Harrythetrout
Detecting COM ports??
« on: November 08, 2020, 07:24:52 am »
I've written a program that reads data from the RS-232 port on an instrument via a USB - RS-232 adapter. At the moment I have a prompt for the user to input the COM port that the adapter is using. Is there a (simple) way to detect what COM ports are in use so that I can put them in a pull down menu for the user to pick?
Oh look - a sig file :-)

Offline Mad Axeman

  • Newbie
  • Posts: 74
    • View Profile
    • My web site - Harrythetrout
Re: Detecting COM ports??
« Reply #1 on: November 08, 2020, 08:41:43 am »
My current workaround is to use an array for the ports. I then use a 'for x to y' loop to open each COM port in turn. If it brings up an error '68' then  stick a '0' in the array corresponding to that port number. If it doesn't return error '68' then that port is answering and stick a '1' in the array for that port. My pull down list will just include array entries that are '1'.

Must be a simpler way?
Oh look - a sig file :-)

Offline Mad Axeman

  • Newbie
  • Posts: 74
    • View Profile
    • My web site - Harrythetrout
Re: Detecting COM ports??
« Reply #2 on: November 08, 2020, 10:16:09 am »
My current way of doing things. Any suggestions for an easier way? Not the neatest code but that's the way I do things :-)
Code: QB64: [Select]
  1. DIM ps(255) AS INTEGER
  2. ON ERROR GOTO fault
  3.  
  4. 'create a loop that opens comm 1 to comm 255 in turn
  5. FOR i = 1 TO 255
  6.     port$ = LTRIM$(STR$(i))
  7.     re = 1 ' This sets up the return from the error trap
  8.     o = 1 ' Set this to 1. If it's not open then it sets this to 0
  9.     CLOSE 1 ' Make sure port is closed before we try to open it
  10.  
  11.     OPEN "COM" + port$ + ":9600,N,8,1,BIN,CS0,DS0" FOR RANDOM AS #1 ' try and open the port
  12.     ps%(i) = o ' Set ps%(i) to 1 for openable or 0 if not
  13.  
  14.  
  15. ' Display which ones are openable
  16. PRINT "The following ports are openable"
  17. FOR i = 1 TO 255
  18.     IF ps%(i) = 1 THEN PRINT i
  19.  
  20.  
  21.  
  22. ' Catch the error
  23. fault:
  24. errnum = ERR
  25.  
  26.  
  27. ' why re = 1
  28. ' Well, at a point later in the main program I open the comm port again.
  29. ' That time re will be 0 so it won't go to the RESUME NEXT,
  30. ' it will go to a second IF (errnum = 68) THEN error call
  31. IF (errnum = 68 AND re = 1) THEN
  32.     o = 0
  33.     CLOSE 1
  34.     RESUME NEXT
  35.  
  36.  
  37. PRINT " FATAL PROGRAMME ERROR!!"
  38.  
  39. PRINT " Error:"; errnum
  40.  
  41.  
Oh look - a sig file :-)