[racket] Racket / Scheme access to serial port, rs232, uart

From: Richard Cleis (rcleis at mac.com)
Date: Mon Dec 26 11:29:18 EST 2011

About five years ago, I wrote simple C extensions that our group has used on OS X, Linux, and Windows. Today, I'd probably use the Foreign Function Interface. Sometimes we used the KeySpan USB-Serial hardware with the same extension. It might be possible to do what you show below entirely in Racket, but the serial interfaces are sometimes quirky enough that a small, non comprehensive C library is easier to maintain.


On Dec 23, 2011, at 9:05 AM, Andrej Mošať wrote:

> I was wondering how can one access serial port from scheme / racket?
> To justify this ancient technology, more and more embedded devices,
> microcontrollers and development boards are being used. UART, rs232,
> serial over USB are being used to communicate with the devices.
> There is some support in several OS by a few programming languages.
> Question: how can one reliably read / write to serial port from racket
> under windows and linux ?
> Here are just some experiences.
> Sofar, Python has pyserial - works as a charm within minutes,
> PERL claims to support rs232,
> C++ and C have libraries, which vary by OS and are not standardized,
> POSIX C++ seems to require the least amount of time to setup among
> those.
> Linux can access serial port from command line by coreutils "stty"
> program, as found in
> http://planet.plt-scheme.org/package-source/xtofs/firmata.plt/1/0/
> i.e.
> (define port-name "/dev/ttyS0")
> (system (string-append  "stty -f " port-name " 57600 cs8 cread clocal")
> Windows can directly read and write to serial ports  by using mode and
> reading / writing by copy,
> here is a basic code example to do it from racket:
> #lang racket
> ;c:\Program Files (x86)\GnuWin32\bin>mode com3: baud=115200 parity=N
> data=8 stop=1
> ;copy com3 con
> (define port-name "com3") ;;serial port
> (define baudrate 115200) ;;baud rate for port-name
> ;;; 1. set device parameters
> ;; windows
> (when (eq? (system-type 'os) 'windows)
>  (if (system (string-append "mode " port-name ":")) ;; detect if
> device connected
>      (if (not (system (string-append  "mode " port-name ": baud="
> (number->string baudrate) "parity=N data=8 stop=1")) ;; set the baud
> rate and other params
>               )
>          (error "Failed to open the connection with " port-name "
> verify if your device is plugged in correctly") ;;error if device not
> connected
>          'OK_Baudrate_Set)
>      (error "Failed to open the connection with " port-name " verify
> if your device is plugged in correctly") ;;error if device not
> connected
>      )
>  )
> Thank you very much for your thoughts and comments.
> mosi
> _________________________________________________
>  For list-related administrative tasks:
>  http://lists.racket-lang.org/listinfo/users

Posted on the users mailing list.