Skip to content

Control measurements

Use NMRController to connect, send settings, and acquire data. Combine its state and error notifications with your own UI.

These are excerpts for the HTML in Build your first Web UI, not standalone programs. They share the same controller and parameters.

On this page

Connect and disconnect

js
const controller = new NMRController();
const connect = document.getElementById("connect");
const disconnect = document.getElementById("disconnect");
const status = document.getElementById("status");

connect.onclick = async () => {
  const result = await controller.connect();
  if (result.ok) status.textContent = "Connected";
};
disconnect.onclick = async () => {
  const result = await controller.disconnect();
  if (result.ok) status.textContent = "Disconnected";
};

Port selection requires a user gesture. Call connect() directly from the button click, without awaiting unrelated work first.

Disconnect any other app or tab using the same port first. disconnect() is not a measurement-stop command and is rejected while measuring.

Set measurement parameters

js
const parameters = {
  frequencyHz: 402000,
  pulse1Cycles: 21, phase1Degrees: 0,
  pulse2Cycles: 42, phase2Degrees: 90,
  pulseIntervalMs: 5,
  measurementIntervalMs: 200,
  scans: 128,
};
FieldMeaningAccepted values
frequencyHzFrequency [Hz]Integer from 1 to 2147483647
pulse1Cycles / pulse2CyclesFirst and second pulse lengths in RF cyclesInteger from 0 to 32767
phase1Degrees / phase2DegreesPhase [degrees]0 / 90 / 180 / 270
pulseIntervalMsInter-pulse delay [ms]Integer from 0 to 32767
measurementIntervalMsDevice interval setting [ms]Integer from 1 to 32767
scansAcquisition countInteger from 1 to 32767

All fields are required. Pulse lengths are RF cycle counts, not microseconds. Include the second-pulse fields even for Single. These limits come from the wire format; they do not guarantee suitable operating conditions for your device and sample.

Convert form input values to numbers. Use validateParameters to check input before sending it. This call does not communicate with hardware.

js
import { validateParameters } from "./nmrlink/index.js";

try {
  validateParameters(parameters);
  status.textContent = "Input format is valid";
} catch (error) {
  status.textContent = error.message;
}

Run Single or Double

js
const measure = document.getElementById("measure");

measure.onclick = () => controller.measure(parameters, { mode: "single" });

// For Double, replace the handler above with:
// measure.onclick = () => controller.measure(parameters, { mode: "double" });

measure() sends settings and acquires the result. The device performs the acquisition count specified by scans. Requests made during another operation are rejected rather than queued.

Measurements are not retried automatically. Immediate stop and precise progress notifications are not available; wait for the operation to finish.

Update buttons from state

js
controller.onStateChange(state => {
  connect.disabled = !state.canConnect;
  measure.disabled = !state.canMeasure;
  disconnect.disabled = !state.canDisconnect;
  if (state.busy) status.textContent = "Working…";
});
  • canConnect / canMeasure / canDisconnect: whether each operation is available.
  • busy: whether an operation is running. You can also use it to disable a settings form.
  • operation: connect / disconnect / measure / sweep, or null when idle.
  • hasResult: whether a result is available for saving or reanalysis.

Receive results and errors

js
controller.onResult(record => {
  status.textContent = "Measurement complete: " + record.points + " points";
  // record.raw contains uncorrected [Data 1, Data 2] pairs.
});
controller.onError(error => {
  status.textContent = error.message;
});

onResult runs only after success. Each record contains 2048 points × 2 channels with sampleIntervalMs equal to 0.02 ms. Acquisition time, settings, and mode are also recorded.

The last successful record remains in controller.result if a later communication or analysis step fails. Make sure your UI does not present a previous result as a new measurement.

When awaiting an operation, check { ok: true, value } for success or { ok: false, error } for failure. Failed NMRController operations also notify onError.

Show an estimated duration

js
import { measurementDurationMs } from "./nmrlink/index.js";

const seconds = measurementDurationMs(parameters, { mode: "single" }) / 1000;
status.textContent = "Estimated measurement time: " + seconds.toFixed(1) + " s";

The estimate excludes serial transfer and command overhead. It does not guarantee an exact completion time or report progress.

Clean up the UI

Before removing a component, wait for the current operation to finish, disconnect as needed, and release the UI resources.

js
async function closeUI() {
  if (controller.state.busy) return;
  if (controller.state.canDisconnect) {
    const result = await controller.disconnect();
    if (!result.ok) return;
  }
  controller.dispose();
  graphs.dispose();
}

dispose() releases state monitoring. It does not implicitly stop or disconnect the device. graphs is the graph view created in Build your first Web UI.

For connection issues, see Supported browsers and connection troubleshooting.

Connect from Node.js

The npm nmrlink package can run analysis in Node.js. Serial hardware access additionally requires NodeSerialTransport from nmrlink-server, which is not published to npm. Use the repository with Node.js 22 or later. Node.js hardware connection remains unverified.

sh
git clone https://github.com/masabando/nmrlink.git
cd nmrlink
npm install

Save the following as measure.mjs at the repository root. Check the port and parameters, then run node measure.mjs. This code performs a physical measurement; it is not a simulated-data example.

js
import { NMRDevice, analyzeMeasurement } from "nmrlink";
import { NodeSerialTransport } from "nmrlink-server";

console.log(await NodeSerialTransport.listPorts());
const device = new NMRDevice({
  transport: new NodeSerialTransport({ path: "/dev/cu.YOUR_DEVICE" }),
});
try {
  await device.connect();
  const record = await device.measure({
    frequencyHz: 402000,
    pulse1Cycles: 21, phase1Degrees: 0,
    pulse2Cycles: 42, phase2Degrees: 90,
    pulseIntervalMs: 5, measurementIntervalMs: 200, scans: 128,
  }, { mode: "single" });
  console.log(analyzeMeasurement(record).peak);
} finally {
  await device.disconnect();
}

Listing ports does not open them. Specify path explicitly; there is no automatic reconnection or resend. NMRGraphs and the download helper saveMeasurement are browser-only. For Firebase-based operation, see Remote access (unverified).

Next: Analyze signals →