Examples
Hello, world!
Firstly, the canonical ‘Hello World’ example: (If you would like to see the output, it might be a good idea to have a 16×2 LCD shield such as this is connected.)
(include "libraries/list.ms")
(include "libraries/io.ms")
(include "libraries/lcd.ms")
(lcd_init)
(for-each-vector print "Hello, World!")
Interacting with the world
Using the general purpose digital input/output pins on the arduino is simple. Assuming you are using an Arduino MEGA, and have an LED connected to digital pin 20, you can make it blink like so:
(include "libraries/io.ms")
(set-ddr 20 #t) ; Set direction register for pin 20 to 'output'
(define (blink_forever)
(set-pin 20 #t) ; Set pin 20 high
(pause 500) ; Wait half a second
(set-pin 20 #f) ; Set pin 20 low
(pause 500) ; Wait half a second
(blink_forever)) ; Repeat...
(blink_forever)
Fibonacci Sequence
In the next example, we build a list of numbers from the Fibnacci sequence. This time, rather than producing output on an LCD screen, we send each of the values to some external device via the serial interface.
(include "libraries/list.ms")
(define (fibstep i acc n2 n1)
(if (= 0 i)
acc
(fibstep (- i 1) (cons (+ n2 n1) acc) n1 (+ n2 n1))))
(define (fib n)
(reverse (fibstep n () 0 1)))
(for-each serial-send (fib 10))
Factorial
Here we see two approaches to writing a factorial function; the second of which is tail-recursive. In each function, the value of (stacksize)
, which returns the number of bytes occupied at the moment of evaluation, is reported at the deepest part of the recursion. This demonstrates the importance of the tail-recursive style in environments such as microcontrollers.
(include "libraries/list.ms")
(define (factorial n)
(if (zero? n)
(begin (serial-send (stacksize)) 1)
(* (factorial (- n 1)) n)))
(serial-send (factorial 7))
(define (tail-factorial n acc)
(if (zero? n)
(begin (serial-send (stacksize)) acc)
(tail-factorial (- n 1) (* acc n))))
(serial-send (tail-factorial 7 1))