3.  Writing Comedi programs

3.1. Your first Comedi program
3.2. Converting between integer data and physical units
3.3. Your second Comedi program
3.4. Asynchronous acquisition
3.5. Further examples

This section describes how Comedi can be used in an application, to communicate data with a set of Comedi devices. Section 4 gives more details about the various acquisition functions with which the application programmer can perform data acquisition in Comedi.

Also don't forget to take a good look at the demo directory of the Comedilib source code. It contains lots of examples for the basic functionalities of Comedi.

3.1.  Your first Comedi program

This example requires a card that has analog or digital input. This progam opens the device, gets the data, and prints it out:

 * Tutorial example #1
 * Part of Comedilib
 * Copyright (c) 1999,2000 David A. Schleef <ds@schleef.org>
 * This file may be freely modified, distributed, and combined with
 * other software, as long as proper attribution is given in the
 * source code.

#include <stdio.h>	/* for printf() */
#include <comedilib.h>

int subdev = 0;		/* change this to your input subdevice */
int chan = 0;		/* change this to your channel */
int range = 0;		/* more on this later */
int aref = AREF_GROUND;	/* more on this later */

int main(int argc,char *argv[])
	comedi_t *it;
	int chan = 0;
	lsampl_t data;
	int retval;

	it = comedi_open("/dev/comedi0");
	if(it == NULL) {
		return 1;

	retval = comedi_data_read(it, subdev, chan, range, aref, &data);
	if(retval < 0) {
		return 1;

	printf("%d\n", data);

	return 0;


The source code file for the above program can be found in Comedilib, at demo/tut1.c. You can compile the program using

      cc tut1.c -lcomedi -lm -o tut1

The comedi_open call can only be successful if the comedi0 device file is configured with a valid Comedi driver. Section 2.1 explains how this driver is linked to the device file.

The range variable tells Comedi which gain to use when measuring an analog voltage. Since we don't know (yet) which numbers are valid, or what each means, we'll use 0, because it won't cause errors. Likewise with aref, which determines the analog reference used.