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

From: Andrej Mošať (amosat+lisp at gmail.com)
Date: Fri Dec 23 11:05:36 EST 2011

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


Posted on the users mailing list.