Tcl Tk Serial Port Communication

Tcl8.6.10/Tk8.6.10 Documentation>Tcl Commands> open

  1. Tcl Tk Serial Port Communications

Import serial import threading from time import sleep from Tkinter import. import sys wind=Tk global var var=StringVar(wind) var.set('value 1') entryCOM=Entry(wind,textvariable=var) entryCOM.place(x=0,y=0,width=100,height=50) ser = serial.Serial(port='COM1',baudrate=115200,parity=serial.PARITYNONE,stopbits=serial.STOPBITSONE,bytesize.

Tcl/Tk Applications Tcl Commands Tk Commands [incr Tcl] Package Commands SQLite3 Package Commands TDBC Package Commands tdbc::mysql Package Commands tdbc::odbc Package Commands tdbc::postgres Package Commands tdbc::sqlite3 Package Commands Thread Package Commands Tcl C API Tk C API [incr Tcl] Package C API TDBC Package C API

NAME
open — Open a file-based or command pipeline channel
SYNOPSIS
DESCRIPTION
r
r+
w
w+
a
a+
RDONLY
WRONLY
RDWR
APPEND
BINARY
CREAT
EXCL
NOCTTY
NONBLOCK
TRUNC
COMMAND PIPELINES
SERIAL COMMUNICATIONS
-modebaud,parity,data,stop
-handshaketype
-queue
-timeoutmsec
-ttycontrol{signal boolean signal boolean ...}
-ttystatus
-xchar{xonChar xoffChar}
-pollintervalmsec
-sysbufferinSize
-sysbuffer{inSize outSize}
-lasterror
SERIAL PORT SIGNALS
TXD(output)
RXD(input)
RTS(output)
CTS(input)
DTR(output)
DSR(input)
DCD(input)
RI(input)
BREAK
ERROR CODES (Windows only)
RXOVER
TXFULL
OVERRUN
RXPARITY
FRAME
BREAK
PORTABILITY ISSUES
Windows
Unix
EXAMPLE
SEE ALSO
KEYWORDS

NAME

open — Open a file-based or command pipeline channel

SYNOPSIS

open fileName
open fileName access
open fileName access permissions

DESCRIPTION

This command opens a file, serial port, or command pipeline and returns achannel identifier that may be used in future invocations of commands likeread, puts, and close.If the first character of fileName is not thenthe command opens a file:fileName gives the name of the file to open, and it must conform to theconventions described in the filename manual entry.

The access argument, if present, indicates the way in which the file(or command pipeline) is to be accessed.In the first form access may have any of the following values:

r
Open the file for reading only; the file must already exist. This is thedefault value if access is not specified.
r+
Open the file for both reading and writing; the file mustalready exist.
w
Open the file for writing only. Truncate it if it exists. If it does notexist, create a new file.
w+
Open the file for reading and writing. Truncate it if it exists.If it does not exist, create a new file.
a
Open the file for writing only. If the file does not exist,create a new empty file.Set the file pointer to the end of the file prior to each write.
a+
Open the file for reading and writing. If the file does not exist,create a new empty file.Set the initial access position to the end of the file.

All of the legal access values above may have the characterb added as the second or third character in the value toindicate that the opened channel should be configured as if with thefconfigure-translation binary option, making the channel suitable forreading or writing of binary data.

In the second form, access consists of a list of any of thefollowing flags, all of which have the standard POSIX meanings.One of the flags must be either RDONLY, WRONLY or RDWR.

RDONLY
Open the file for reading only.
WRONLY
Open the file for writing only.
RDWR
Open the file for both reading and writing.
APPEND
Set the file pointer to the end of the file prior to each write.
BINARY
Configure the opened channel with the -translation binary option.
CREAT
Create the file if it does not already exist (without this flag itis an error for the file not to exist).
EXCL
If CREAT is also specified, an error is returned if thefile already exists.
NOCTTY
If the file is a terminal device, this flag prevents the file frombecoming the controlling terminal of the process.
NONBLOCK
Prevents the process from blocking while opening the file, andpossibly in subsequent I/O operations. The exact behavior ofthis flag is system- and device-dependent; its use is discouraged(it is better to use the fconfigure command to put a filein nonblocking mode).For details refer to your system documentation on the open systemcall's O_NONBLOCK flag.
TRUNC
If the file exists it is truncated to zero length.

If a new file is created as part of opening it, permissions(an integer) is used to set the permissions for the new file inconjunction with the process's file mode creation mask.Permissions defaults to 0666.

COMMAND PIPELINES

If the first character of fileName is“”then theremaining characters of fileName are treated as a list of argumentsthat describe a command pipeline to invoke, in the same style as thearguments for exec.In this case, the channel identifier returned by open may be usedto write to the command's input pipe or read from its output pipe,depending on the value of access.If write-only access is used (e.g. access is“w”),then standard output for the pipeline is directed to the current standardoutput unless overridden by the command.If read-only access is used (e.g. access is“r”),standard input for the pipeline is taken from the current standardinput unless overridden by the command.The id of the spawned process is accessible through the pidcommand, using the channel id returned by open as argument.

If the command (or one of the commands) executed in the commandpipeline returns an error (according to the definition in exec),a Tcl error is generated when close is called on the channelunless the pipeline is in non-blocking mode then no exit status isreturned (a silent close with -blocking 0).

It is often useful to use the fileevent command with pipelinesso other processing may happen at the same time as running the commandin the background.

SERIAL COMMUNICATIONS

If fileName refers to a serial port, then the specified serial portis opened and initialized in a platform-dependent manner. Acceptablevalues for the fileName to use to open a serial port are described inthe PORTABILITY ISSUES section.

The fconfigure command can be used to query and set additionalconfiguration options specific to serial ports (where supported):

-modebaud,parity,data,stop
This option is a set of 4 comma-separated values: the baud rate, parity,number of data bits, and number of stop bits for this serial port. Thebaud rate is a simple integer that specifies the connection speed.Parity is one of the following letters: n, o, e,m, s; respectively signifying the parity options of“none”,“odd”,“even”,“mark”,or“space”.Data is the number ofdata bits and should be an integer from 5 to 8, while stop is thenumber of stop bits and should be the integer 1 or 2.
-handshaketype
(Windows and Unix). This option is used to setup automatic handshakecontrol. Note that not all handshake types maybe supported by your operatingsystem. The type parameter is case-independent.

If type is none then any handshake is switched off.rtscts activates hardware handshake. Hardware handshake signalsare described below.For software handshake xonxoff the handshake characters can be redefinedwith -xchar.An additional hardware handshake dtrdsr is available only under Windows.There is no default handshake configuration, the initial value dependson your operating system settings.The -handshake option cannot be queried.

-queue
(Windows and Unix). The -queue option can only be queried.It returns a list of two integers representing the current numberof bytes in the input and output queue respectively.
-timeoutmsec
(Windows and Unix). This option is used to set the timeout for blockingread operations. It specifies the maximum interval between thereception of two bytes in milliseconds.For Unix systems the granularity is 100 milliseconds.The -timeout option does not affect write operations ornonblocking reads.This option cannot be queried.
-ttycontrol{signal boolean signal boolean ...}
(Windows and Unix). This option is used to setup the handshakeoutput lines (see below) permanently or to send a BREAK over the serial line.The signal names are case-independent.{RTS 1 DTR 0} sets the RTS output to high and the DTR output to low.The BREAK condition (see below) is enabled and disabled with {BREAK 1} and{BREAK 0} respectively.It is not a good idea to change the RTS (or DTR) signalwith active hardware handshake rtscts (or dtrdsr).The result is unpredictable.The -ttycontrol option cannot be queried.
-ttystatus
(Windows and Unix). The -ttystatus option can only bequeried. It returns the current modem status and handshake input signals(see below).The result is a list of signal,value pairs with a fixed order,e.g. {CTS 1 DSR 0 RING 1 DCD 0}.The signal names are returned upper case.
-xchar{xonChar xoffChar}
(Windows and Unix). This option is used to query or change the softwarehandshake characters. Normally the operating system default should beDC1 (0x11) and DC3 (0x13) representing the ASCII standardXON and XOFF characters.
-pollintervalmsec
(Windows only). This option is used to set the maximum time betweenpolling for fileevents.This affects the time interval between checking for events throughout the Tclinterpreter (the smallest value always wins). Use this option only ifyou want to poll the serial port more or less often than 10 msec(the default).
-sysbufferinSize
-sysbuffer{inSize outSize}
(Windows only). This option is used to change the size of Windowssystem buffers for a serial channel. Especially at higher communicationrates the default input buffer size of 4096 bytes can overrunfor latent systems. The first form specifies the input buffer size,in the second form both input and output buffers are defined.
-lasterror
(Windows only). This option is query only.In case of a serial communication error, read or putsreturns a general Tcl file I/O error.fconfigure-lasterror can be called to get a list of error details.See below for an explanation of the various error codes.

SERIAL PORT SIGNALS

RS-232 is the most commonly used standard electrical interface for serialcommunications. A negative voltage (-3V..-12V) define a mark (on=1) bit anda positive voltage (+3..+12V) define a space (off=0) bit (RS-232C). Thefollowing signals are specified for incoming and outgoing data, statuslines and handshaking. Here we are using the terms workstation foryour computer and modem for the external device, because some signalnames (DCD, RI) come from modems. Of course your external device may usethese signal lines for other purposes.
TXD(output)
Transmitted Data: Outgoing serial data.
RXD(input)
Received Data:Incoming serial data.
RTS(output)
Request To Send: This hardware handshake line informs the modem thatyour workstation is ready to receive data. Your workstation mayautomatically reset this signal to indicate that the input buffer is full.
CTS(input)
Clear To Send: The complement to RTS. Indicates that the modem isready to receive data.
DTR(output)
Data Terminal Ready: This signal tells the modem that the workstationis ready to establish a link. DTR is often enabled automatically whenever aserial port is opened.
DSR(input)
Data Set Ready: The complement to DTR. Tells the workstation that themodem is ready to establish a link.
DCD(input)
Data Carrier Detect: This line becomes active when a modem detects a“Carrier”signal.
RI(input)
Ring Indicator: Goes active when the modem detects an incoming call.
BREAK
A BREAK condition is not a hardware signal line, but a logical zero on theTXD or RXD lines for a long period of time, usually 250 to 500milliseconds. Normally a receive or transmit data signal stays at the mark(on=1) voltage until the next character is transferred. A BREAK is sometimesused to reset the communications line or change the operating mode ofcommunications hardware.

ERROR CODES (Windows only)

A lot of different errors may occur during serial read operations or duringevent polling in background. The external device may have been switchedoff, the data lines may be noisy, system buffers may overrun or your modesettings may be wrong. That is why a reliable software should alwayscatch serial read operations. In cases of an error Tcl returns ageneral file I/O error. Then fconfigure

Tcl Tk Serial Port Communications

Tcl tk serial port communications-lasterror may help tolocate the problem. The following error codes may be returned.
RXOVER
Windows input buffer overrun. The data comes faster than your scripts readsit or your system is overloaded. Use fconfigure-sysbuffer to avoid atemporary bottleneck and/or make your script faster.
TXFULL
Windows output buffer overrun. Complement to RXOVER. This error shouldpractically not happen, because Tcl cares about the output buffer status.
OVERRUN
UART buffer overrun (hardware) with data lost.The data comes faster than the system driver receives it.Check your advanced serial port settings to enable the FIFO (16550) bufferand/or setup a lower(1) interrupt threshold value.
RXPARITY
A parity error has been detected by your UART.Wrong parity settings with fconfigure-mode or a noisy data line (RXD)may cause this error.
FRAME
A stop-bit error has been detected by your UART.Wrong mode settings with fconfigure-mode or a noisy data line (RXD)may cause this error.
BREAK
A BREAK condition has been detected by your UART (see above).

PORTABILITY ISSUES

Windows
Valid values for fileName to open a serial port are of the formcomX, where X is a number, generally from 1 to 9.A legacy form accepted as well is comX:. This notation onlyworks for serial ports from 1 to 9. An attempt to open a serial port thatdoes not exist or has a number greater than 9 will fail. An alternateform of opening serial ports is to use the filename //./comX,where X is any number that corresponds to a serial port.
When running Tcl interactively, there may be some strange interactionsbetween the real console, if one is present, and a command pipeline that usesstandard input or output. If a command pipeline is opened for reading, someof the lines entered at the console will be sent to the command pipeline andsome will be sent to the Tcl evaluator. If a command pipeline is opened forwriting, keystrokes entered into the console are not visible until thepipe is closed. These problems only occur because both Tcl and the childapplication are competing for the console at the same time. If the commandpipeline is started from a script, so that Tcl is not accessing the console,or if the command pipeline does not use standard input or output, but isredirected from or to a file, then the above problems do not occur.
Unix
Valid values for fileName to open a serial port are generally of theform /dev/ttyX, where X is a or b, but the nameof any pseudo-file that maps to a serial port may be used.Advanced configuration options are only supported for serial portswhen Tcl is built to use the POSIX serial interface.

When running Tcl interactively, there may be some strange interactionsbetween the console, if one is present, and a command pipeline that usesstandard input. If a command pipeline is opened for reading, someof the lines entered at the console will be sent to the command pipeline andsome will be sent to the Tcl evaluator. This problem only occurs becauseboth Tcl and the child application are competing for the console at thesame time. If the command pipeline is started from a script, so that Tcl isnot accessing the console, or if the command pipeline does not use standardinput, but is redirected from a file, then the above problem does not occur.

See the PORTABILITY ISSUES section of the exec command foradditional information not specific to command pipelines about executingapplications on the various platforms

EXAMPLE

Open a command pipeline and catch any errors:

SEE ALSO

file, closeTcl tk serial port communications, filename, fconfigure, gets, read, puts, exec, pid, fopen

KEYWORDS

access mode, append, create, file, non-blocking, open, permissions, pipeline, process, serial
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Comments are closed.