Applicable file: python_ctypes_example.py Download file
Runtime environment: 64-bit Windows, 64-bit Python 3
Example purpose: read device information and perform one spectrum measurement over a specified wavelength range

1. Example Functions

python_ctypes_example.py is a runnable interactive Python example. Following the prompts, the program completes the following operations:

  1. Search for and open the PynectDirect spectrometer.
  2. Read the device serial number.
  3. Read and display the device's full wavelength range.
  4. Read the current integration time and average count.
  5. Ask the user to enter the integration time and average count for this measurement.
  6. Ask the user to enter the start and end wavelengths to be read.
  7. Display the wavelength range actually selected by the device.
  8. Read all wavelength values and corresponding intensity values within the selected range.
  9. Report the total number of points actually read, and print up to 10 representative data points at even intervals.
  10. Restore the integration time and average count to their pre-run values, and close the device.

This example sets only temporary measurement parameters for the current run and does not write to the device's default stored configuration.

2. Runtime Environment and File Layout

2.1 Python Requirements

64-bit Python is required. You can run the following command to check:

python -c "import struct; print(struct.calcsize('P') * 8)"

The correct output is:

64

This example uses only the Python standard library, so no pip install is needed.

In the complete SDK delivery package, the file layout is as follows:

PynectDirect_SDK/
|-- bin/
|   |-- PynectDirect.dll
|   `-- ftd2xx.dll
`-- examples/
    |-- python_ctypes_example.py
    `-- python_ctypes_example_guide.md

PynectDirect.dll and ftd2xx.dll must be placed in the same directory. The program can find them automatically from the bin directory of the delivery package.

2.3 Layout When Copying the Example Separately

If you only copy the Python example, a sibling dll directory is recommended:

my_spectrum_demo/
|-- python_ctypes_example.py
|-- python_ctypes_example_guide.md
`-- dll/
    |-- PynectDirect.dll
    `-- ftd2xx.dll

The program also supports placing the two DLLs directly in the same directory as python_ctypes_example.py.

3. Running the Example

Open PowerShell, enter the SDK delivery package directory and run:

python .\examples\python_ctypes_example.py

If you have already entered the examples directory, you can also run:

python .\python_ctypes_example.py

The program scans for devices. When only one device is connected, device index 0 is used automatically; when multiple devices are connected, you are first prompted to select a device index.

4. Item-by-Item Input Guide

The program first reads the device's current state, then prompts for the measurement parameters for this run. Values in square brackets are defaults; press Enter to accept them.

Prompt item Input type Unit or range Pressing Enter directly Purpose
Device index Integer 0 to the maximum index in the scan results Use 0 Select the device to open; appears only with multiple devices
Integration time Positive integer Microseconds (us), within the device's allowed range Keep the current integration time Set the temporary integration time for this measurement
Average count Integer 1-255 times Keep the current average count Set the temporary average count for this measurement
Start wavelength Number nm, within the full wavelength range Use the start of the full range Select the start of the range to be read
End wavelength Number nm, within the full wavelength range Use the end of the full range Select the end of the range to be read

The start wavelength must be less than the end wavelength. If you enter text, an out-of-range value or an invalid combination, the program explains the problem and re-prompts without needing a restart.

4.1 Example Input Prompt

Assuming the device's current integration time is 50000 us, the average count is 1, and the full wavelength range is 350-850 nm:

Device serial number: PYN-TEST-001
Full wavelength range: 350.000-850.000 nm
Current integration time: 50000 us
Current average count: 1
Integration time in us [50000]: 100000
Average count [1]: 3
Start wavelength in nm [350.000]: 400
End wavelength in nm [850.000]: 600

The above input means:

  • This measurement uses an integration time of 100000 us.
  • Each output spectrum point uses 3 averages.
  • Only the spectral data within the requested 400-600 nm range is read.

4.2 Using All Defaults

To keep the current integration time and average count and read the full wavelength range, simply press Enter at all four parameter prompts.

5. Output Content

5.1 Measurement Summary

After acquisition completes, the program first outputs:

Output item Meaning
Device serial number Device serial number
Full wavelength range Full wavelength range supported by the device
Integration time Integration time actually used for this measurement, in us
Average count Average count actually used for this measurement
Requested wavelength range Start and end wavelengths entered by the user
Actual wavelength range Range after the device matches the actual pixel positions
Actual wavelength points read Total number of data points actually read within the selected range

The requested range and the actual range may differ slightly. This is because the device can only select pixels and calibrated wavelength points that actually exist. When processing data, use the Actual wavelength range and the actually returned arrays as the reference.

5.2 Wavelength Values and Intensity Values

The example reads all spectrum points within the selected range, but to keep the console output readable it prints at most 10 representative data points. When the actual point count is at least 10, the program selects 10 points at even intervals over the original indices and keeps the first and last points; when the actual point count is less than 10, the program prints all the data.

For example, when a measurement actually reads 810 points, the output begins as follows:

Actual wavelength points read: 810
Showing 10 evenly spaced points:
Index   Wavelength (nm)   Intensity
0       800.090000        1200
90      811.197000        1380
...
809     899.911000        1760

The three columns mean:

  • Index: the data sequence number within the selected range, starting from 0.
  • Wavelength (nm): the wavelength value at that point, in nm.
  • Intensity: the raw spectrum intensity value at the same index position, in the range 0-65535.

Wavelength values and intensity values correspond one-to-one by index. For example, index 1 with 500.000000 nm corresponds to intensity value 2300. Do not sort the two arrays separately, or this correspondence will be broken.

The console only omits the display; it does not discard the measurement data. The result.wavelengths and result.intensities returned by run_interactive_measurement() still contain all the data actually read in this run; in the example above, both lists contain 810 elements.

6. Reusing in Your Own Program

6.1 Reading the Full Spectrum

The original read_full_spectrum(device_index=0) function is retained. It performs no interactive input and returns two ordinary Python lists:

from python_ctypes_example import read_full_spectrum

wavelengths, intensities = read_full_spectrum(device_index=0)
print("Point count:", len(wavelengths))
print("First pair:", wavelengths[0], intensities[0])

6.2 Running an Interactive Band-Select Measurement

run_interactive_measurement() shows the item-by-item prompts and returns a SelectedSpectrumResult:

from python_ctypes_example import run_interactive_measurement

result = run_interactive_measurement()
for wavelength, intensity in zip(
    result.wavelengths, result.intensities
):
    print(wavelength, intensity)

The main fields of the result object are:

Field Type Meaning
serial_number str Device serial number
full_start_nm, full_end_nm float Full wavelength range
integration_us int Integration time for this measurement, in us
average_count int Average count for this measurement
request_start_nm, request_end_nm float Range requested by the user
actual_start_nm, actual_end_nm float Range actually matched by the device
start_pixel, end_pixel int Actual start and end pixels
wavelengths list Wavelength list of the selected range
intensities list Intensity list corresponding to the wavelength list

On normal return, len(result.wavelengths) always equals len(result.intensities).

7. Parameter Restoration and Device Close

The program saves the original integration time and average count before modifying them. Whether acquisition completes or an acquisition error occurs, the program attempts to:

  1. Restore the original average count.
  2. Restore the original integration time.
  3. Close the device.

If restoration fails, the program outputs a message starting with WARNING:. In that case, do not continue measuring; close other software that may be using the device, reopen the device and check the parameters.

After the program ends normally, the selected wavelength range is not written to the device's long-term configuration. The next run reads the full range again and prompts for input.

8. Common Errors

8.1 PynectDirect.dll Not Found

You may see:

ERROR: PynectDirect.dll not found

Check:

  • That the file name is exactly PynectDirect.dll.
  • That PynectDirect.dll and ftd2xx.dll are in the same directory.
  • That the DLL is in the script's directory, a sibling dll directory, or the delivery package's bin directory.

8.2 Incorrect Python Bitness

If you use 32-bit Python, you will see a message saying 64-bit Python is required. Install and use 64-bit Python, then run again.

8.3 No Device Found

You may see:

ERROR: No PynectDirect device found

Check the USB connection and device power, and close other software that is currently occupying the spectrometer.

8.4 Invalid Input Value

  • The integration time must be a positive integer, in microseconds.
  • The average count must be between 1-255.
  • The start and end wavelengths must lie within the displayed full range.
  • The start wavelength must be less than the end wavelength.

The program re-prompts; enter the values as required.

8.5 API Returns a Negative Error Code

The error message includes the operation name and return code, for example:

ERROR: Get selected spectrum data failed, return code=-9

Common return codes include:

Return code Meaning
-3 Device not opened
-4 Device communication or returned data abnormal
-5 Invalid parameter or array capacity
-7/-8 Data checksum or data packet abnormal
-9 Device response timeout
-11 The current device does not support this function

For the complete error codes and API parameter descriptions, see docs/PynectDirect_API_Guide.md.

9. Safety Notes

  • This example only modifies the temporary integration time and average count used for the current measurement.
  • This example does not call Flash, stored configuration, xenon lamp, DAC or device reset functions.
  • Do not unplug the USB cable while the device is acquiring.
  • Longer integration times and larger average counts increase the waiting time and do not mean the program is unresponsive.
  • When calling from your own program, also ensure that the device is closed on the exception path.