The first example is the classic blink code. You can see the creation of a digital output on D13, setting its value and sleeping. Note the use of tail-call recursion to implement the repetition.

    ;;; Blink the onboard LED

(define (blink)
  (let ((led (digital-pin (board "D13") **OUTPUT**)))
    (define (loop val)
      (pin-value! led val)
      (sleep 0.5)
      (loop (not val)))
    (loop #t)))

Next we'll add digital input. With a pushbutton between D12 and ground, this code turns the led on when the switch is pushed, off when released.

;;; echo a switch on pin D12 onto the onboard LED

(define (echo)
  (let ((switch (digital-pin (board "D12") **INPUT** **PULLUP**))
        (led (digital-pin (board "D13") **OUTPUT**)))
    (define (loop)
      (pin-value! led (not (pin-value? switch)))

Switching to analog, a potentiometer can be connected to A0 and set it up as an analog input. Then it can be read and the value displayed every half second.

;;; Read an analog input every second and print result

(define (analog)
  (let ((input (analog-pin (board "A0") **INPUT**)))
    (define (loop)
      (display (pin-value input))
      (sleep 0.5)

Flipping it around an LED can be connected to A1. The code below sets it up as an analog output and ramps the value up and down between minimum and maximum values. The LED gets brighter and dimmer. The value is also written to the console.

This code also uses the cond special form. It's similar to a switch statement in many languages. The cond contains a series of (condition code) clauses. The code associated with the first condition that evaluates to true is evaluated. FYI, true in CircuitScheme is #t and false is #f.

;;; Ramp an analog output up and down

(define (analog)
  (let ((output (analog-pin (board "A1") **OUTPUT**)))
    (define (loop val delta)
      (let ((new-val (+ val delta)))
        (display new-val)
        (sleep 0.1)
        (cond ((<= new-val 0)
               (loop new-val (* -1 delta)))
              ((>= new-val 65535)
               (loop new-val (* -1 delta)))
              (#t (pin-value! output new-val)
                  (loop new-val delta)))))
    (loop 0 1000)))

This guide was first published on Feb 14, 2019. It was last updated on Feb 14, 2019.

This page (Examples) was last updated on Feb 07, 2021.

Text editor powered by tinymce.