usbHostGetSerialPort (Function)

Top  Previous  Next

Architecture:

NX32L

Device support:

NX-200, NX-400

Firmware version:

1.00.00


This returns the serial port number which can be use with serOpen to open a serial connection using an USB serial device.

 

 

Input:

device : STRING

The system device name of the USB serial port device retrieved using the usbHostEnumerate function.

 

 

Returns: SINT

>0

- The serial port number used to open a connection with.

0

- The function is not supported.

-1

- The device is not a serial port or not found

 

Declaration:

FUNCTION usbHostGetSerialPort : SINT;
VAR_INPUT
  device : STRING;
END_VAR;

 

Example:

INCLUDE rtcu.inc
VAR_INPUT
  doOpen   : BOOL;           | open first found USB serial port
END_VAR;
VAR_OUTPUT
  isOpen   : BOOL := FALSE; | is serial port open
  failed   : BOOL;           | failed to open port
END_VAR;
 
FUNCTION GetPortNum : SINT;
VAR
  device   : STRING;         // System name of USB device
  type     : INT := -1;     // Type of USB device
  index    : INT;
  port     : SINT;
  rc       : INT;
END_VAR;
GetPortNum := -1; // Not found
FOR index := 1 TO 32 DO
  rc := usbHostEnumerate(index := index, device := device, type := type);
  IF ((rc <= 0) OR (type = 2)) THEN
    EXIT;
  END_IF;
END_FOR;
IF type <> 2 THEN
  DebugMsg(message := "Failed to find any USB serial devices.");
  RETURN;
END_IF;
DebugFmt(message := "Found '" + device + "' at index \1", v1 := index);
port := usbHostGetSerialPort(device := device);
IF port <= 0 THEN
  DebugFmt(message := "Failed to get serial port number (code \1)", v1 := rc);
END_IF;
GetPortNum := port;
END_FUNCTION;
 
PROGRAM example;
VAR
  portNum  : SINT := -1;     // Select which port to use for the communication
  timer    : TON;
  rc       : INT;
END_VAR;
// Enable USB host port
usbHostEnable(port:=1,enable:=TRUE);
 
BEGIN
  IF doOpen XOR isOpen THEN
    IF portNum >= 0 THEN
        serClose(port:=portNum);
        DebugFmt(message := "Serial port \1 was closed", v1 := portNum);
        portNum := -1;
    END_IF;
    IF doOpen THEN
        portNum := GetPortNum();
        IF portNum >= 0 THEN
          rc := serOpen(port := portNum);
          IF rc = 0 THEN
              DebugFmt(message := "Serial port \1 is open", v1 := portNum);
          ELSE
              DebugFmt(message := "Failed to open serial port \1 (\2)", v1 := portNum, v2 := rc);
              portNum := -1;
          END_IF;
        END_IF;
        failed := (portNum < 0);
        timer.pt := 0;
    END_IF;
    isOpen := doOpen;
  END_IF;
  timer(trig := (isOpen AND NOT failed));
  IF timer.q THEN
    serSendString(port := portNum, str := "Hello$N");
    timer(trig := FALSE, pt := 5000); // reset timer
  END_IF;
END;
END_PROGRAM;