Notice: MediaWiki has been updated. Report any rough edges to marcan@marcan.st

Getting Started With Common Lisp

From OpenKinect
Jump to: navigation, search

Dependencies

libfreenect

Install libfreenect as described on the Installation page.

cffi, verrazano

The next step is to create CFFI bindings for libfreenect. We can use Verrazano to generate these bindings for us. Installing these is simple via quicklisp:

(ql:quickload :cffi)
(ql:quickload :verrazano)

Verrazano depends on an external program, gccxml, to generate CFFI bindings, so you would need to install it too. On Ubuntu, it is available via apt-get:

sudo apt-get install gccxml

Generate CFFI bindings

Generate the CFFI bindings -- running verrazano:generate-binding will create the file libfreenect.lisp -- and load them.

(verrazano:generate-binding (list :cffi :package-name :libfreenect :input-files (list "libfreenect/libfreenect.h")))
(load (compile-file #p"libfreenect.lisp"))
(use-package :libfreenect)

Load libfreenect in your Lisp image

On Linux, you would load libfreenect.so. Change the name accordingly for Mac and Windows. On the mac, You'll need to do (mapc #'cffi:load-foreign-library '((:framework "CoreFoundation") (:framework "IOKit"))) first.

(cffi:load-foreign-library #p"libfreenect.so")

Example Usage

Define a couple of globals which you would need to pass around for most calls to libfreenect:

(defvar *ctx*) ; freenect_context *ctx;
(defvar *dev*) ; freenect_device *dev;

Initialize the library with a call to freenect_init:

(let ((ctx-ptr (cffi:foreign-alloc :pointer)))
  (freenect-init ctx-ptr (cffi:null-pointer))
  (setf *ctx* (cffi:mem-ref ctx-ptr :pointer)))

The second arg to freenect_init is a libusb context, which we set to NULL since we are using only one context here (NULL refers to the default context).

If a Kinect is connected, you can confirm it with a call to freenect_num_devices (which should return 1):

(freenect-num-devices *ctx*) ; this should return 1

Now "open" the device with a call to freenect_open_device:

(let ((dev-ptr (cffi:foreign-alloc :pointer)))
  (freenect-open-device *ctx* dev-ptr 0)
  (setf *dev* (cffi:mem-ref dev-ptr :pointer)))

The last arg to freenect_open_device refers to the device number index, which is 0 in case a single device is connected.

Now you can confirm that you are able to work with the device with a call to freenect_set_led (see the LED colour change accordingly):

(freenect-set-led *dev* (cffi:foreign-enum-value 'freenect-led-options :led-blink-red-yellow))

When you are done with Kinect hacking, you should wrap things up cleanly:

(freenect-close-device *dev*)
(freenect-shutdown *ctx*)