Impedance Measurement Example#
This is the full MATLAB example file that measures electrode impedance and prints it once per second.
Download the source:
example_impedance_measurement.m
example_impedance_measurement.m#
function result = example_impedance_measurement(device_name, duration_seconds)
%EXAMPLE_IMPEDANCE_MEASUREMENT Print each electrode's impedance once per second.
%
% Usage:
% example_impedance_measurement()
% example_impedance_measurement('BA MINI 001')
% result = example_impedance_measurement('BA MINI 001', 20)
%
% Measures every electrode of the device with the 31.2 Hz test wave, using
% electrode 0 for bias feedback, and prints the newest impedance of each
% electrode in kOhm once per second.
project_root = fileparts(fileparts(mfilename('fullpath')));
addpath(fullfile(project_root, 'matlab'));
if nargin < 1
device_name = '';
end
if nargin < 2 || isempty(duration_seconds)
duration_seconds = 20;
end
ba_setup();
ba_init();
cleanup_obj = onCleanup(@() safe_shutdown());
device_name = resolve_device_name(device_name);
fprintf('Connecting to %s\n', device_name);
ba_connect(device_name);
device_features = ba_get_device_features();
% Electrode i is channel ID 1 + i; electrode 0 (channel 1) is the bias electrode.
channel_ids = 1:double(device_features.electrode_count);
ba_configure_eeg(channel_ids, 250, 8, 1);
ba_set_impedance_mode('31.2hz');
start_result = ba_start_stream();
fprintf('Measuring impedance at %d Hz.\n', start_result.sample_frequency_hz);
pause(2.0); % wait for the first impedance values
impedance_kohm = [];
started_at = tic;
while toc(started_at) < duration_seconds
pause(1.0);
[chunk, meta] = ba_read_chunk(0, true);
if ~meta.available || isempty(chunk)
continue;
end
impedance_kohm = chunk(:, end);
fprintf('Electrode impedance (kOhm):');
fprintf(' %.0f', impedance_kohm);
fprintf('\n');
end
ba_stop_stream();
ba_disconnect();
ba_close();
clear cleanup_obj
result = struct( ...
'channel_ids', channel_ids, ...
'device_name', device_name, ...
'impedance_kohm', impedance_kohm, ...
'sample_frequency_hz', start_result.sample_frequency_hz);
end
function device_name = resolve_device_name(device_name)
if ~isempty(device_name)
return;
end
device_name = getenv('BA_DEVICE_NAME');
if ~isempty(device_name)
return;
end
devices = ba_scan();
if isempty(devices)
error('brainaccess:api', ...
'No devices found. Set BA_DEVICE_NAME or pass a device name explicitly.');
end
device_name = devices(1).name;
end
function safe_shutdown()
status = ba_status();
if status.streaming
ba_stop_stream();
end
if status.connected
ba_disconnect();
end
if status.core_initialized || status.manager_present
ba_close();
end
end