The current on-line documentation for Tcl (i.e. the Tcl reference  
manual) still reads "Opening a serial port is not currently  
implemented under Macintosh".  Hence, last week, when I inquired as to  
whether or not it was possible to acquire data from a usb serial  
device from within R, I was pointed to Rpy, which is somewhat indirect  
in that communication is unidirectional from Python to R. While it  
allows R functions to be called from within Python, it is not a very  
familiar environment from an R-user perspective.

As it turns out, the Tcl documentation is not up to date, since the  
open/ puts/ gets/ read commands all allow access to the Macintosh  
serial (USB) port from within the Tcl interpreter. Consequently, it is  
in fact very easy to access the serial port using the tcltk package  
from within R. On the off chance that someone else may need to acquire  
data directly from an external device, I thought I should document how  
this can be done using a few Tcl calls, so that data can be read into  
R in real time, where it can be parsed, processed, and displayed using  
a familiar R environment.


require("tcltk")

# Under Unix, hardware ports are mapped to file descriptors. So we  
open the serial port by specifying its file descriptor (typically /dev/ 
tty.* or /dev/cu.*. Under Windows, this would be COM1, COM2 etc).  
Here, the resulting channelID (e.g.file10) is assigned to the Tcl  
string 'serial' and the port (file) is opened for read/write access.  
Other options are covered in the Tcl reference manual - see [open].
.Tcl("set serial [open /dev/cu.usbserial r+]" )

# display the channelID for later references
.Tcl("puts $serial")

#configure the port setting, here for a non-blocking stream. If  
blocked, make sure the -timeout option is set or it will hang
.Tcl("fconfigure $serial -mode \"19200,n,8,1\"  -blocking 0")

# read and display individual lines (to the newline character if  
that's how your device is configured)
.Tcl("puts [gets $serial]")

# or read all the data in the buffer
.Tcl("puts [read $serial]")

# remember to close the port or you will have to reboot
.Tcl("close $serial" )

To write to the port, just send "puts $serial <output>" to the Tcl  
interpreter.  In the absence of an R serial library, I think this is  
the simplest approach in that it is platform independent and minimizes  
reliance on external programs other than Tcl, which is supported by R- 
Core.

Atul

-----
Atul Sharma MD, FRCP(C)
Department of Pediatrics,
McGill University



        [[alternative HTML version deleted]]

_______________________________________________
R-SIG-Mac mailing list
[email protected]
https://stat.ethz.ch/mailman/listinfo/r-sig-mac

Reply via email to