Go to the first, previous, next, last section, table of contents.


Example 6: A Differentiator

The program below inverts and differentiates the signals read by getvec and writes the results with putvec. The output is readable as record `dif'. A wide variety of simple digital filters can be modelled on this example; see section Example 7: A General-Purpose FIR Filter, for a more general approach.

 1  #include <stdio.h>
 2  #include <ecg/db.h>
 3
 4  main(argc, argv)
 5  int argc;
 6  char *argv[];
 7  {
 8      static DB_Siginfo s[DB_MAXSIG];
 9      int i, nsig, nsamp = 1000;
10      DB_Sample vin[DB_MAXSIG], vout[DB_MAXSIG];
11
12      if (argc < 2) {
13          fprintf(stderr, "usage: %s record\n", argv[0]); exit(1);
14      }
15      if ((nsig = isigopen(argv[1], s, DB_MAXSIG)) <= 0) exit(2);
16      if (osigopen("8l", s, nsig) <= 0) exit(3);
17      while (nsamp-- > 0 && getvec(vin) > 0) {
18          for (i = 0; i < nsig; i++)
19              vout[i] -= vin[i];
20          if (putvec(vout) < 0) break;
21          for (i = 0; i < nsig; i++)
22              vout[i] = vin[i];
23      }
24      (void)newheader("dif");
25      dbquit();
26      exit(0);
27  }

Notes:

Line 16:
Here we attempt to open as many output signals as there are input signals; if we cannot do so, the program exits after osigopen prints an error message.
Line 17:
The main loop of the program begins here. If 1000 samples can be read from each signal, the loop will end normally; if getvec fails before 1000 samples have been read, the loop ends prematurely.
Lines 18--19:
For each signal, we compute the negated first difference by subtracting the new sample from the previous sample.
Line 20:
One sample of each output signal is written here.
Lines 21--22:
The new input samples are copied into the output sample vector in preparation for the next iteration.
Line 24:
This step is optional. It creates a `header' file for a new record to be called `dif', which we can then open with another program if we want to read the signals that this program has written. Since the record argument for osigopen was `8l', we can also read these files using record `8l'; one reason for making a new `header' file here is that the `header' file for `8l' may not necessarily indicate the proper sampling frequency for these signals.
Line 25:
Since the program writes output signals, it must invoke dbquit to close the files properly.


Go to the first, previous, next, last section, table of contents.



George B. Moody (george@hstbme.mit.edu)