QB64.com

QB64 is a modern extended BASIC programming language that retains QBasic/QuickBASIC 4.5 compatibility and compiles native binaries for Windows, Linux, and macOS.

The OPEN COM statement is used to access a computer’s serial port COM.

Syntax

OPEN “COMn: Speed, Parity, Bits, Stopbit, [Options]” [FOR {RANDOM BINARY OUTPUT INPUT (file mode)}] AS #P [LEN = byteSize]

Parameter(s)

Description

Example(s)

Checking to see if a COM port exists. If the port does not exist QBasic will cause a Windows access error.


ON ERROR GOTO Handler 
FF = FREEFILE
comPort$ = "COM1:"                         'try a COM port number that does not exist
CONST comMode$ = "9600,N,8,1,CS0,DS0"      'Use 0 to avoid timeouts 
OPEN comPort$ + comMode$ FOR RANDOM AS FF 
IF errnum = 0 THEN PRINT "COM exists!

K$ = INPUT$(1) 
END 

Handler: 
errnum = ERR 
PRINT "Error:"; errnum
RESUME NEXT 

Explanation: QB64 may create error 68 if COM is not found. Use a zero CD, CS, DS or OP timeout value to avoid COM timeouts.

Opening a COM port with the BIN, CS0 and DS0 options in QB64.


DIM bytestr AS STRING * 1  'one byte transfers
INPUT "COM port number #", port$  'any COM port number available

OPEN "COM" + port$ + ":9600,N,8,1,BIN,CS0,DS0" FOR RANDOM AS #1
DO 'main loop
    'receive data in buffer when LOC > 0
    IF LOC(1) THEN 
       GET #1, , bytestr
       PRINT "[" + bytestr + "]";
    END IF
    'transmit (send)
    k$ = INKEY$  
    IF LEN(k$) = 1 THEN
       k = ASC(k$)
       IF k >= 32 THEN     'ignore control key codes
           PRINT ">" + k$ + "<";
           bytestr = k$: PUT #1, , bytestr
       END IF
    END IF
LOOP UNTIL k$ = CHR$(27)
CLOSE #1: PRINT "Finished!" 

Sending string data from one COM port to another requires predefined length strings:


DIM SHARED ByteIn AS STRING * 1 'One byte transfers
DIM SHARED Byte4 AS STRING * 4 'Four byte transfers

Byte4 = CHR$(254) + CHR$(175) + CHR$(0) + CHR$(3) 'Command code to query all 4 banks of switch input board.

OPEN "COM1:115200,N,8,1,BIN,CS0,DS0" FOR RANDOM AS #1 'Open port used to send commands.
OPEN "COM2:115200,N,8,1,BIN,CS0,DS0" FOR RANDOM AS #2 'Open port used to receive commands.

PUT #1, , Byte4 'Send the 4 byte command.

Start# = TIMER
DO UNTIL LOC(2) <> 0 'Check if there is data received at com2
    IF TIMER - Start# > .5 THEN EXIT DO 'Exit loop if no data arrives within .5 seconds.
LOOP

IF LOC(2) = 0 THEN 'If no data was received.....
    PRINT "No data received from COM port."
    END
END IF

PRINT "Received from COM2:";

DO UNTIL LOC(2) = 0 'Read data from COM2 until there is no more data.
    GET #2, , ByteIn
    PRINT ASC(ByteIn);
LOOP
END 

See Also