此內容不適用於您所偏好的語言。

此內容已顯示為其他適用語言。 您的瀏覽器可能含有可協助翻譯的套件。

Generating a PWM Using NI-DAQmx for Python

Updated Oct 19, 2026

Environment

Driver

  • NI-DAQ™mx

Programming Language

  • Python

A Pulse Width Modulation (PWM) signal is a technique for generating digital pulses to control an analog circuit. This article will go through the steps to create a counter output and set or change the duty cycle of the square wave using the Python NI-DAQmx API. You will need to have the NI-DAQmx driver and support for Python API installed.

This example demonstrates how to use NI-DAQmx for Python to generate an independent Pulse Width Modulation (PWM) signal using the hardware counters available on an NI device.
 

  • Import the following classes:
    import nidaqmx
    from nidaqmx.constants import AcquisitionType, Level

  • Create your task, add a counter output channel to it, set the frequency and duty cycle and specify on which terminal to generate pulses. 
    with nidaqmx.Task() as task: 
         channel1 = task.co_channels.add_co_pulse_chan_freq("Dev1/ctr0", idle_state=Level.LOW, initial_delay=0.0, freq=50, duty_cycle=0.065) #PWM with period of 20ms and 1.3ms in high
         channel1.co_pulse_term = "/Dev1/PFI12" #terminal to generate pulses
      The parameters for this method are the following:
counter (str) – Specifies the names of the counters to use to create the virtual channels.
idle_state (nidaqmx.constants.Level) – Specifies the resting state of the output terminal.
initial_delay (float) – Is the amount of time in seconds to wait before generating the first pulse.
freq (float) – Specifies at what frequency to generate pulses.
duty_cycle (float) – Is the width of the pulse divided by the pulse period.
             
  • Set the acquisition mode and start the task:
    task.timing.cfg_implicit_timing(sample_mode=AcquisitionType.CONTINUOUS)
    task.timing.samp_clk_src = "/Dev1/Ctr0InternalOutput" #Counter to use
    task.start() 

    
    

      The resulting code should be similar to this:

      
      
      import nidaqmx
      from nidaqmx.constants import AcquisitionType, Level
      
      with nidaqmx.Task() as task:
          channel1 = task.co_channels.add_co_pulse_chan_freq("Dev1/ctr0", idle_state=Level.LOW, initial_delay=0.0 freq=50, duty_cycle=0.065) #PWM with period of 20ms and 1.3ms in high
          channel1.co_pulse_term = "/Dev1/PFI12"    
      
          task.timing.cfg_implicit_timing(sample_mode=AcquisitionType.CONTINUOUS)
          task.timing.samp_clk_src = "/Dev1/Ctr0InternalOutput"
          task.start()
      
          # This part is just to stop the task
          input("Generating PWM. Press Enter to stop.\n")
      
          task.stop()