Touchdraw

Touchdraw is a simple drawing program that demonstrates the use of the touchscreen on boards that provide one. You can draw with a finger on the touchscreen, choose a colour by touching on a coloured square to the right of the screen, or clear the screen by touching the cross:

PyPortalTouchdraw.jpg

Here's the program:

; Touchdraw

(defun index-colour (i)
  (+ (* (ash i -2) #x1f) (* (ash (logand i 2) -1) #x7e0) (* (logand i 1) #xf800)))

(defun colour-index (c)
  (+ (logand (ash c -2) 4) (logand (ash c -9) 2) (logand (ash c -15) 1)))

(defun touchdraw ()
  (bind (xsize ysize) (display-size)
    (let* ((bsize (truncate ysize 8))
           (width (- xsize bsize))
           (index 7))
      (loop
       (fill-screen)
       (dotimes (b 8)
         (fill-rect width (* b bsize) bsize bsize (index-colour b)))
       (draw-rect width 0 bsize bsize)
       (draw-line width 0 (1- xsize) (1- bsize))
       (draw-line (1- xsize) 0 width (1- bsize))
       (loop
        (bind (&optional x y) (touchscreen)
          (cond
           ((null x) nil)
           ((< x width)
            (fill-circle x y 4 (index-colour index)))
           ((< y bsize) (return))
           (t
            (setq index (colour-index (read-pixel x y)))))))))))

It uses the read-pixel function to read the colour at the touched position when you touch a colour in the palette.

The function index-colour converts a number from 0 to 7 to one of the primary colours, and colour-index converts a 16-bit colour back to a colour index from 0 to 7.

Boards currently supported are the Adafruit PyPortal (shown above) and M5Stack Tab5.


Previous: Barnsley Fern

Next: Langton's Ant