More Serial Port Samples

Purpose: Show how to startup with serial ports. -- RoS


You should also visit another Serial Port page.


 ############################################
 # A first quick test if you have a modem

 # open com2: for reading and writing
 # For UNIX'es use the appropriate devices /dev/xxx
 set serial [open com2: r+]

 # setup the baud rate, check it for your configuration
 fconfigure $serial -mode "9600,n,8,1"

 # don't block on read, don't buffer output
 fconfigure $serial -blocking 0 -buffering none

 # Send some AT-command to your modem
 puts -nonewline $serial "AT\r"

 # Give your modem some time, then read the answer
 after 100
 puts "Modem echo: [read $serial]"


 ############################################
 # Example (1): Poll the comport periodically
 set serial [open com2: r+]
 fconfigure $serial -mode "9600,n,8,1"
 fconfigure $serial -blocking 0 -buffering none

 while {1} {
     set data [read $serial]             ;# read ALL incoming bytes
     set size [string length $data]      ;# number of received byte, may be 0
     if { $size } {
         puts "received $size bytes: $data"
     } else {
         puts "<no data>"
     update      ;# Display output, allow to close wish-window
 }

 ############################################
 # Example (2): Fileevents
 set serial [open com2: r+]
 fconfigure $serial -mode "9600,n,8,1" -blocking 0 -buffering none -translation binary
 fileevent $serial readable [list serial_receiver $serial]

 proc serial_receiver { chan } {
     if { [eof $chan] } {
         puts stderr "Closing $chan"
         catch {close $chan}
         return
     }
     set data [read $chan]
     set size [string length $data]
     puts "received $size bytes: $data"
 }

mailto:[email protected] (Rolf Schroedter)


In above examples, don't forget to use " close $serial " command when finished with serial port, or else the port will be locked from further use (the only way I know of rectifying this in Windows is to reboot the PC). - Jeff Wright ([email protected])


modemtcl


Category Device Control