MATLAB Examples

Count Pulses on a Digital Signal Using NI Devices

This example shows how to determine the rate of rotation of an Anaheim Automation motor controller by counting the number of rising edges in the signal. The controller returns hall effect pulses (square waves) that serve as frequency feedback for motor rotation speeds.


Create a Counter Input Channel

Create a DAQ Session, and add a counter input channel with EdgeCount measurement type. For this example, use CompactDAQ chassis NI c9178 and module NI 9402 with ID cDAQ1Mod5.

s = daq.createSession('ni');
addCounterInputChannel(s,'cDAQ1Mod5', 'ctr0', 'EdgeCount');
s = 

Data acquisition session using National Instruments hardware:
   Will run for 1 second (1000 scans) at 1000 scans/second.
   Number of channels: 1
      index Type  Device   Channel MeasurementType Range Name
      ----- ---- --------- ------- --------------- ----- ----
      1     ci   cDAQ1Mod5 ctr0    EdgeCount       n/a

Determine the Terminal of the Counter Input Channel

To connect the input signal to the correct terminal, examine the Terminal property of the channel. The terminal is determined by the hardware.

ans =

  1×4 char array


Read the Counter Channel

To determine if the counter is operational, input a single scan, pause while the motor rotates, then read the counter again.

ans =


ans =


ans =


Measure Revolutions per Second

Count the number of pulses by resetting the counter to zero, pause for one second, and read the counter. The hall effects are oriented every 120 degrees and generate three square wave pulses for every rotation.

s.inputSingleScan() / 3
ans =


Use Hardware Clock for Higher Accuracy

The hardware clock is highly accurate. Use the hardware clock to acquire multiple counter measurements. NI counter devices require an external clock. By adding an analog input channel for a module on the same chassis, the session shares an internal clock with both modules.

s = daq.createSession('ni');
addAnalogInputChannel(s,'cDAQ1Mod1', 0, 'Voltage');
addCounterInputChannel(s,'cDAQ1Mod5', 0, 'EdgeCount');
s.DurationInSeconds = 0.25;
[data, time] = s.startForeground();
plot(time, data);