Serial port functions enable communication with devices connected to the computer via an RS-232 interface. Such devices include modems, printers, and many scientific instruments. The operating system may also emulate RS-232 connection with other devices, such as built-in modems or USB (Universal Serial Bus) devices.
Functions described in this section include only those required for opening, configuring and closing the connection. They correspond to fopen and fclose for files. For receiving and sending data, use the same functions as for reading from and writing to files, such as fread and fwrite.
Close a serial port opened with opendevice.
closedevice(fd)
closedevice(fd) closes the connection established with opendevice. Its argument is the file descriptor obtained with opendevice. Once it is closed, a serial port can be opened again by opendevice or by another application. All ports are closed anyway when the application quits.
Serial device name.
name = devicename(n)
devicename(n) returns the name of the n:th serial device which can be opened by opendevice. Argument n must be 1 or higher; with other values, such as those larger than the number of serial devices available on your computer, devicename returns the empty string.
On a Macintosh with internal modem:
devicename(1) Internal Modem
Under Windows:
devicename(1) COM1
Flush the input buffer of a serial port opened with opendevice.
flushdevice(fd)
flushdevice(fd) discards all the data in the input buffer of a serial port opened with opendevice. The input buffer is always flushed when the connection is opened. flushdevice is useful to recover from errors.
Open a serial port.
fd = opendevice(portname, options) fd = opendevice(portname)
opendevice(portname) opens a connection to the port whose name is portname and returns a file descriptor fd. Names depend on the operating system and can be obtained with devicename.
The second argument of opendevice(portname,options) is a string of comma-separated options from the following list (n is a place holder for a positive decimal number):
Option | Default | Meaning |
---|---|---|
bn | 19200 | bits per second |
Tn | 1000 | timeout in milliseconds |
t | off | text mode (input CR and CRLF are converted to LF) |
h | off | hardware handshake control |
sn | 2 | number of stop bits (1, 1.5 or 2) |
Once a connection has been opened, the file descriptor fd can be used with functions such as fread, fwrite, fscanf, and fprintf.
fd = opendevice(devicename(1), 'b19200,t,T2000'); fprintf(fd, 'L,%d,2\n', 1); reply = fgetl(fd) closedevice(fd);
closedevice, devicename, fread, fwrite, fscanf, fgetl, fgets, fprintf