### Setup BrainFlow Matlab Binding Source: https://brainflow.readthedocs.io/en/stable/BuildBrainFlow Steps to set up the BrainFlow Matlab binding. This includes compiling the core module, adding BrainFlow directories to the Matlab path, and configuring the C++ compiler if necessary. ```matlab mex -setup cpp ``` -------------------------------- ### Start Streaming with Buffer and Parameters Source: https://brainflow.readthedocs.io/en/stable/UserAPI Starts a streaming thread that stores data in an internal ring buffer and streams it simultaneously. Supports file and multicast streaming. The buffer_size parameter defines the ring buffer's capacity. ```c++ inline void start_stream(int buffer_size, String streamer_params) ``` -------------------------------- ### Start Streaming Source: https://brainflow.readthedocs.io/en/stable/UserAPI Starts a streaming thread responsible for storing data within an internal ring buffer. ```c++ inline void start_stream() ``` -------------------------------- ### Get Data from Board (Java) Source: https://brainflow.readthedocs.io/en/stable/Examples This Java example shows how to get data from a BrainFlow-compatible board. It includes steps for initializing the BoardShim, preparing the session, starting data streaming to a file, sleeping for a duration, stopping the stream, and retrieving the board data. It also demonstrates how to parse command-line arguments for board configuration. ```java package brainflow.examples; import java.util.Arrays; import brainflow.BoardShim; import brainflow.BrainFlowInputParams; import brainflow.LogLevels; public class BrainFlowGetData { public static void main (String[] args) throws Exception { BoardShim.enable_board_logger (); BrainFlowInputParams params = new BrainFlowInputParams (); int board_id = parse_args (args, params); BoardShim board_shim = new BoardShim (board_id, params); board_shim.prepare_session (); // board_shim.start_stream (); // use this for default options board_shim.start_stream (450000, "file://file_stream.csv:w"); BoardShim.log_message (LogLevels.LEVEL_INFO.get_code (), "Start sleeping in the main thread"); Thread.sleep (5000); board_shim.stop_stream (); System.out.println (board_shim.get_board_data_count ()); double[][] data = board_shim.get_current_board_data (30); // doesnt flush it from ring buffer // double[][] data = board_shim.get_board_data (); // get all data and flush // from ring buffer for (int i = 0; i < data.length; i++) { System.out.println (Arrays.toString (data[i])); } board_shim.release_session (); } private static int parse_args (String[] args, BrainFlowInputParams params) { int board_id = -1; for (int i = 0; i < args.length; i++) { if (args[i].equals ("--ip-address")) { params.ip_address = args[i + 1]; } if (args[i].equals ("--ip-address-aux")) { params.ip_address_aux = args[i + 1]; } if (args[i].equals ("--ip-address-anc")) { params.ip_address_anc = args[i + 1]; } if (args[i].equals ("--serial-port")) { params.serial_port = args[i + 1]; } if (args[i].equals ("--ip-port")) { params.ip_port = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--ip-port-aux")) { params.ip_port_aux = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--ip-port-anc")) { params.ip_port_anc = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--ip-protocol")) { params.ip_protocol = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--other-info")) { params.other_info = args[i + 1]; } if (args[i].equals ("--board-id")) { board_id = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--timeout")) { params.timeout = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--serial-number")) { params.serial_number = args[i + 1]; } if (args[i].equals ("--file")) { params.file = args[i + 1]; } if (args[i].equals ("--file-aux")) { params.file_aux = args[i + 1]; } if (args[i].equals ("--file-anc")) { params.file_anc = args[i + 1]; } if (args[i].equals ("--master-board")) { params.master_board = Integer.parseInt (args[i + 1]); } } return board_id; } } ``` -------------------------------- ### Configure and Stream Data with Presets (C#) Source: https://brainflow.readthedocs.io/en/stable/DataFormatDesc This C# example shows how to configure a BrainFlow session for the Muse S board, add streamers for different presets (DEFAULT, AUXILIARY, ANCILLARY), start streaming, retrieve data for each preset, and save the data to files. It utilizes various BrainFlow methods for session management, configuration, streaming, and data retrieval. ```csharp using BrainFlow BrainFlow.enable_dev_logger(BrainFlow.BOARD_CONTROLLER) params = BrainFlowInputParams() board_shim = BrainFlow.BoardShim(BrainFlow.MUSE_S_BOARD, params) BrainFlow.prepare_session(board_shim) BrainFlow.config_board("p50", board_shim) # to enable ppg use p61, p50 enables aux(5th eeg) channel and smth else BrainFlow.add_streamer("file://default_from_streamer.csv:w", board_shim, BrainFlow.DEFAULT_PRESET) BrainFlow.add_streamer("file://aux_from_streamer.csv:w", board_shim, BrainFlow.AUXILIARY_PRESET) BrainFlow.add_streamer("file://anc_from_streamer.csv:w", board_shim, BrainFlow.ANCILLARY_PRESET) BrainFlow.start_stream(board_shim) sleep(10) BrainFlow.stop_stream(board_shim) data_default = BrainFlow.get_board_data(board_shim, BrainFlow.DEFAULT_PRESET) # contains eeg data data_aux = BrainFlow.get_board_data(board_shim, BrainFlow.AUXILIARY_PRESET) # contains accel and gyro data data_anc = BrainFlow.get_board_data(board_shim, BrainFlow.ANCILLARY_PRESET) # contains ppg data BrainFlow.release_session(board_shim) BrainFlow.write_file(data_default, "default.csv", "w") BrainFlow.write_file(data_aux, "aux.csv", "w") BrainFlow.write_file(data_anc, "anc.csv", "w") ``` -------------------------------- ### Unity C# Example: Stream and Get Board Data Source: https://brainflow.readthedocs.io/en/stable/GameEngines A C# script for Unity to initialize BrainFlow, start streaming data from a synthetic board, retrieve data, and properly release the session. Requires the BrainFlow NuGet package and C# bindings. ```csharp using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using brainflow; using brainflow.math; public class SimpleGetData : MonoBehaviour { private BoardShim board_shim = null; private int sampling_rate = 0; // Start is called before the first frame update void Start() { try { BoardShim.set_log_file("brainflow_log.txt"); BoardShim.enable_dev_board_logger(); BrainFlowInputParams input_params = new BrainFlowInputParams(); int board_id = (int)BoardIds.SYNTHETIC_BOARD; board_shim = new BoardShim(board_id, input_params); board_shim.prepare_session(); board_shim.start_stream(450000, "file://brainflow_data.csv:w"); sampling_rate = BoardShim.get_sampling_rate(board_id); Debug.Log("Brainflow streaming was started"); } catch (BrainFlowError e) { Debug.Log(e); } } // Update is called once per frame void Update() { if (board_shim == null) { return; } int number_of_data_points = sampling_rate * 4; double[,] data = board_shim.get_current_board_data(number_of_data_points); // check https://brainflow.readthedocs.io/en/stable/index.html for api ref and more code samples Debug.Log("Num elements: " + data.GetLength(1)); } // you need to call release_session and ensure that all resources correctly released private void OnDestroy() { if (board_shim != null) { try { board_shim.release_session(); } catch (BrainFlowError e) { Debug.Log(e); } Debug.Log("Brainflow streaming was stopped"); } } } ``` -------------------------------- ### config_board Source: https://brainflow.readthedocs.io/en/stable/UserAPI Configures a board with a given string. Use with caution, as it's not intended for starting or stopping streams. ```APIDOC ## POST /config_board ### Description Configures a board with a given string. Use with caution, as it's not intended for starting or stopping streams. ### Method POST ### Endpoint /config_board ### Parameters #### Query Parameters - **config** (str) - Required - String to send to a board. ### Response #### Success Response (200) - **response** (str) - Response string if any. #### Response Example ```json { "response": "Configuration successful" } ``` ``` -------------------------------- ### Initialize Cyton Board - Python Source: https://brainflow.readthedocs.io/en/stable/SupportedBoards Initializes the Cyton board using BrainFlow. Requires specifying the serial port for communication. This example demonstrates the basic setup for the Cyton board. ```python params = BrainFlowInputParams() params.serial_port = "COM3" board = BoardShim(BoardIds.CYTON_BOARD, params) ``` -------------------------------- ### Build BrainFlow C# Package on Unix (Mono) Source: https://brainflow.readthedocs.io/en/stable/BuildBrainFlow Instructions for building the BrainFlow C# package on Unix-like systems using Mono. This involves compiling the core module, installing dependencies, and building the solution with dotnet. ```bash # compile c++ code python tools/build.py # install dependencies sudo dnf install nuget sudo dnf install mono-devel sudo dnf install mono-complete sudo dnf install monodevelop sudo dnf install dotnet-sdk-6.0 sudo dnf install dotnet-runtime-6.0 sudo dnf install dotnet-sdk-3.1 sudo dnf install dotnet-runtime-3.1 # build solution dotnet build csharp_package/brainflow/brainflow.sln # run tests export LD_LIBRARY_PATH=/home/andreyparfenov/brainflow/installed/lib/ mono csharp_package/brainflow/examples/denoising/bin/Debug/denoising.exe ``` -------------------------------- ### Rust: Insert Markers During Streaming Source: https://brainflow.readthedocs.io/en/stable/Examples This Rust example shows how to set up BrainFlow, start streaming data to a CSV file, insert markers at specific times, stop streaming, retrieve the data, and release the session. It's useful for synchronizing external events with EEG data. ```rust use std::thread; use std::time::Duration; use brainflow::board_shim::BoardShim; use brainflow::brainflow_input_params::BrainFlowInputParamsBuilder; use brainflow::BoardIds; use brainflow::BrainFlowPresets; fn main() { brainflow::board_shim::enable_dev_board_logger().unwrap(); let params = BrainFlowInputParamsBuilder::default().build(); let board = BoardShim::new(BoardIds::SyntheticBoard, params).unwrap(); board.prepare_session().unwrap(); board.start_stream(45000, "file://data.csv:w").unwrap(); thread::sleep(Duration::from_secs(5)); board.insert_marker(1.0, BrainFlowPresets::DefaultPreset).unwrap(); thread::sleep(Duration::from_secs(5)); board.stop_stream().unwrap(); let data = board.get_board_data(Some(10), BrainFlowPresets::DefaultPreset).unwrap(); board.release_session().unwrap(); println!("{:?}", data); } ``` -------------------------------- ### Build and Install Brainflow for Android using CMake Source: https://brainflow.readthedocs.io/en/stable/BuildBrainFlow Builds and installs the Brainflow library for the currently configured Android ABI. This command should be run after the configuration step for each ABI. It specifies the build target, configuration, and parallel build options. ```bash cmake --build . --target install --config Release -j 2 --parallel 2 ``` -------------------------------- ### Get Board Presets Source: https://brainflow.readthedocs.io/en/stable/UserAPI Retrieves a list of available presets for a given board ID. ```APIDOC ## GET /get_board_presets ### Description Retrieves a list of available presets for a given board ID. ### Method GET ### Endpoint /get_board_presets ### Parameters #### Query Parameters - **board_id** (int) - Required - The ID of the board. ### Response #### Success Response (200) - **presets** (std::vector) - A vector of integers representing the available presets for the board. #### Response Example ```json { "presets": [0, 1, 2] } ``` ### Throws - **BrainFlowException** - ``` -------------------------------- ### Get EXG Channels Source: https://brainflow.readthedocs.io/en/stable/UserAPI Retrieves the list of EXG channels for a specified board ID and preset. ```APIDOC ## GET /api/channels/exg ### Description Retrieves the list of EXG channels available for a given BrainFlow board and preset. ### Method GET ### Endpoint /api/channels/exg ### Query Parameters - **board_id** (int) - Required - The ID of the BrainFlow board. - **preset** (int) - Optional - The preset configuration for the board (defaults to 0). ### Response #### Success Response (200) - **channels** (List[int]) - A list of integers representing the EXG channel indices. #### Response Example ```json { "channels": [ 4, 5, 6, 7 ] } ``` #### Error Response (400) - **error** (string) - Description of the error (e.g., UNSUPPORTED_BOARD_ERROR). #### Error Example ```json { "error": "UNSUPPORTED_BOARD_ERROR" } ``` ``` -------------------------------- ### Get Board Data Count Source: https://brainflow.readthedocs.io/en/stable/UserAPI Returns the total number of data packages available within the ring buffer. ```c++ inline int get_board_data_count() ``` -------------------------------- ### Prepare MLModel (Python) Source: https://brainflow.readthedocs.io/en/stable/UserAPI Prepares the MLModel for use, typically involving loading trained weights or setting up internal structures. This method should be called after initializing the model. ```python void prepare() ``` -------------------------------- ### TypeScript Get Board Data Source: https://brainflow.readthedocs.io/en/stable/Examples Retrieves data from a Brainflow board using TypeScript. This example demonstrates preparing the session, starting and stopping the data stream, fetching the board data, and releasing the session. It uses the 'brainflow' npm package. ```typescript import {BoardIds, BoardShim} from 'brainflow'; function sleep (ms: number) { return new Promise ((resolve) => { setTimeout (resolve, ms); }); } async function runExample (): Promise { const board = new BoardShim (BoardIds.SYNTHETIC_BOARD, {}); board.prepareSession(); board.startStream(); await sleep (3000); board.stopStream(); const data = board.getBoardData(); board.releaseSession(); console.info('Data'); console.info(data); } runExample (); ``` -------------------------------- ### Prepare Streaming Session (Python) Source: https://brainflow.readthedocs.io/en/stable/UserAPI Initializes resources and prepares a streaming session for a BrainFlow board. This method must be called before any other BoardShim object methods that interact with the board's data stream. It sets up the necessary environment for data acquisition. ```python from brainflow.board_shim import BoardShim, BrainFlowPresets # Example usage: # Assuming 'board' is an instance of a BoardShim subclass # board.prepare_session() # Or with a specific preset: # board.prepare_session(preset=BrainFlowPresets.ANALOG_FILTER_PRESET) ``` -------------------------------- ### Rust: Basic Signal Filtering with BrainFlow Source: https://brainflow.readthedocs.io/en/stable/Examples A simple Rust example demonstrating the setup for signal filtering using BrainFlow. It initializes a synthetic board, starts and stops data streaming, retrieves board data, and prints the data length and content. This snippet serves as a foundation for more complex filtering operations. Requires 'brainflow' and 'std'. ```rust use std::{thread, time::Duration}; use brainflow::{board_shim, brainflow_input_params::BrainFlowInputParamsBuilder, BoardIds, BrainFlowPresets,}; fn main() { brainflow::board_shim::enable_dev_board_logger().unwrap(); let params = BrainFlowInputParamsBuilder::default().build(); let board = board_shim::BoardShim::new(BoardIds::SyntheticBoard, params).unwrap(); board.prepare_session().unwrap(); board.start_stream(45000, "").unwrap(); thread::sleep(Duration::from_secs(5)); board.stop_stream().unwrap(); let data = board.get_board_data(Some(10), BrainFlowPresets::DefaultPreset).unwrap(); board.release_session().unwrap(); println!("{}", data.len()); println!("{:?}", data); } ``` -------------------------------- ### Get Band Power from PSD Source: https://brainflow.readthedocs.io/en/stable/UserAPI Calculates the band power within a specified frequency range using a provided PSD. The function takes the PSD data and the start and end frequencies of the band as input. ```C++ static inline double get_band_power(Pair psd, double freq_start, double freq_end) get band power Parameters * **psd** – PSD from get_psd or get_log_psd * **freq_start** – lowest frequency of band * **freq_end** – highest frequency of band Returns band power ``` -------------------------------- ### Configure Board with Bytes Source: https://brainflow.readthedocs.io/en/stable/UserAPI Sends a byte array to configure the board. This function is intended for internal use and should not be called directly by users. ```c++ inline void config_board_with_bytes (byte[] bytes) ``` -------------------------------- ### Initialize and Stream Data in Julia Source: https://brainflow.readthedocs.io/en/stable/UserAPI This Julia code snippet demonstrates how to initialize Brainflow, prepare a session, add a file streamer, start data streaming, and retrieve the data. It also shows how to write and read data to/from a file. ```julia using BrainFlow # specify logging library to use BrainFlow.enable_dev_logger(BrainFlow.BOARD_CONTROLLER) params = BrainFlowInputParams() board_shim = BrainFlow.BoardShim(BrainFlow.SYNTHETIC_BOARD, params) BrainFlow.prepare_session(board_shim) BrainFlow.add_streamer("file://data_default.csv:w", board_shim) BrainFlow.start_stream(board_shim) sleep(5) BrainFlow.stop_stream(board_shim) data = BrainFlow.get_current_board_data(32, board_shim) BrainFlow.release_session(board_shim) BrainFlow.write_file(data, "test.csv", "w") restored_data = BrainFlow.read_file("test.csv") println("Original Data") println(data) println("Restored Data") println(restored_data) ``` -------------------------------- ### Initialize MLModel (Python) Source: https://brainflow.readthedocs.io/en/stable/UserAPI Creates an instance of the MLModel class, which is used for machine learning tasks within BrainFlow. Initialization requires BrainFlowModelParams as input. ```python MLModel(BrainFlowModelParams input_params) ``` -------------------------------- ### Rust: Get Board Data Source: https://brainflow.readthedocs.io/en/stable/Examples This Rust code demonstrates how to initialize BrainFlow, prepare a session, start streaming data from a synthetic board, stop streaming, retrieve board data, and release the session. It includes basic logging and error handling. ```rust use std::{thread, time::Duration}; use brainflow::{board_shim, brainflow_input_params::BrainFlowInputParamsBuilder, BoardIds, BrainFlowPresets,}; fn main() { brainflow::board_shim::enable_dev_board_logger().unwrap(); let params = BrainFlowInputParamsBuilder::default().build(); let board = board_shim::BoardShim::new(BoardIds::SyntheticBoard, params).unwrap(); board.prepare_session().unwrap(); board.start_stream(45000, "").unwrap(); thread::sleep(Duration::from_secs(5)); board.stop_stream().unwrap(); let data = board.get_board_data(Some(10), BrainFlowPresets::DefaultPreset).unwrap(); board.release_session().unwrap(); println!("{}", data.len()); println!("{:?}", data); } ``` -------------------------------- ### Get Power Spectral Density (PSD) Source: https://brainflow.readthedocs.io/en/stable/UserAPI Calculates the Power Spectral Density (PSD) of the input data within specified start and end positions. It requires the sampling rate and supports different window functions (integer code or enum). The result is a pair of amplitude and frequency arrays. ```C++ static inline Pair< double[], double[]> get_psd (double[] data, int start_pos, int end_pos, int sampling_rate, int window) get PSD Parameters * **data** – data to process * **start_pos** – starting position to calc PSD * **end_pos** – end position to calc PSD, total_len must be even * **sampling_rate** – sampling rate * **window** – window function Returns pair of ampl and freq arrays with len N / 2 + 1 ``` ```C++ static inline Pair< double[], double[]> get_psd (double[] data, int start_pos, int end_pos, int sampling_rate, WindowOperations window) get PSD Parameters * **data** – data to process * **start_pos** – starting position to calc PSD * **end_pos** – end position to calc PSD, total_len must be even * **sampling_rate** – sampling rate * **window** – window function Returns pair of ampl and freq arrays with len N / 2 + 1 ``` -------------------------------- ### Get Current Board Data with Preset Source: https://brainflow.readthedocs.io/en/stable/UserAPI Retrieves the latest collected data from the board, up to a specified number of samples. It may return fewer samples than requested and does not clear the data from the ring buffer. ```c++ inline double[][] get_current_board_data (int num_samples, BrainFlowPresets preset) ``` -------------------------------- ### Matlab Get Data from a Board with BrainFlow Source: https://brainflow.readthedocs.io/en/stable/Examples This Matlab code demonstrates how to retrieve data from a BrainFlow-compatible board. It includes session preparation, starting a stream, recording data to a CSV file, and then retrieving the current board data. Requires the BrainFlow Matlab API. ```Matlab BoardShim.set_log_file('brainflow.log'); BoardShim.enable_dev_board_logger(); params = BrainFlowInputParams(); board_shim = BoardShim(int32(BoardIds.SYNTHETIC_BOARD), params); preset = int32(BrainFlowPresets.DEFAULT_PRESET); board_shim.prepare_session(); board_shim.add_streamer('file://data_default.csv:w', preset); board_shim.start_stream(45000, ''); pause(5); board_shim.stop_stream(); data = board_shim.get_current_board_data(10, preset); disp(data); board_shim.release_session(); ``` -------------------------------- ### R Get Data with Marker Insertion Source: https://brainflow.readthedocs.io/en/stable/Examples This R code snippet shows how to stream data from a BrainFlow board and insert a marker during the stream. It includes session preparation, starting the stream, inserting a marker, stopping the stream, retrieving data, and releasing the session. ```r library(brainflow) params <- brainflow_python$BrainFlowInputParams() board_shim <- brainflow_python$BoardShim(brainflow_python$BoardIds$SYNTHETIC_BOARD$value, params) board_shim$prepare_session() board_shim$start_stream() Sys.sleep(time = 5) board_shim$insert_marker(1) board_shim$stop_stream() data <- board_shim$get_current_board_data(as.integer(250)) board_shim$release_session() ``` -------------------------------- ### Configure Board with String Command - BrainFlow Source: https://brainflow.readthedocs.io/en/stable/UserAPI Configures a board by sending a string command. Use this method with caution, as it's not intended for starting or stopping data streams. It returns a string response from the board if one is provided. ```python config_board(_config_: str) -> str Use this method carefully and only if you understand what you are doing, do NOT use it to start or stop streaming Parameters **config** (_str_) – string to send to a board Returns response string if any Return type str ``` -------------------------------- ### Prepare ML Classifier Source: https://brainflow.readthedocs.io/en/stable/UserAPI Prepares the machine learning classifier for use. This typically involves loading models or performing necessary initializations. It can throw a BrainFlowError if preparation fails. ```c++ inline void prepare() ``` -------------------------------- ### R Data Transforms Source: https://brainflow.readthedocs.io/en/stable/Examples This R code snippet shows the basic setup for applying data transforms using BrainFlow. It includes preparing the session, starting the stream, waiting, stopping the stream, and releasing the session, which are prerequisites for applying transforms to the acquired data. ```r library(brainflow) params <- brainflow_python$BrainFlowInputParams() board_shim <- brainflow_python$BoardShim(brainflow_python$BoardIds$SYNTHETIC_BOARD$value, params) board_shim$prepare_session() board_shim$start_stream() Sys.sleep(time = 5) board_shim$stop_stream() data <- board_shim$get_current_board_data(as.integer(250)) board_shim$release_session() ``` -------------------------------- ### Java: Insert Markers into Data Stream Source: https://brainflow.readthedocs.io/en/stable/Examples This Java code snippet demonstrates how to prepare a BrainFlow session, start streaming data to a CSV file, and insert numerical markers at specific intervals. It requires the BrainFlow library and handles session setup and teardown. ```java package brainflow.examples; import brainflow.BoardShim; import brainflow.BrainFlowInputParams; public class Markers { public static void main (String[] args) throws Exception { BoardShim.enable_board_logger (); BrainFlowInputParams params = new BrainFlowInputParams (); int board_id = parse_args (args, params); BoardShim board_shim = new BoardShim (board_id, params); board_shim.prepare_session (); board_shim.start_stream (450000, "file://file_stream.csv:w"); for (int i = 1; i < 5; i++) { Thread.sleep (1000); board_shim.insert_marker (i); } board_shim.stop_stream (); board_shim.release_session (); } private static int parse_args (String[] args, BrainFlowInputParams params) { int board_id = -1; for (int i = 0; i < args.length; i++) { if (args[i].equals ("--ip-address")) { params.ip_address = args[i + 1]; } if (args[i].equals ("--serial-port")) { params.serial_port = args[i + 1]; } if (args[i].equals ("--ip-port")) { params.ip_port = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--ip-protocol")) { params.ip_protocol = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--other-info")) { params.other_info = args[i + 1]; } if (args[i].equals ("--board-id")) { board_id = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--timeout")) { params.timeout = Integer.parseInt (args[i + 1]); } if (args[i].equals ("--serial-number")) { params.serial_number = args[i + 1]; } if (args[i].equals ("--file")) { params.file = args[i + 1]; } } return board_id; } } ``` -------------------------------- ### Build Project with CMake and Make Source: https://brainflow.readthedocs.io/en/stable/Examples This command initiates the build process for a project configured with CMake. It assumes CMake has already generated the build system files. The `make` command then compiles the source code and links the executables. ```bash cmake -DCMAKE_PREFIX_PATH=/home/andrey/brainflow/installed .. make ``` -------------------------------- ### Julia Get Board Data Source: https://brainflow.readthedocs.io/en/stable/Examples Retrieves data from a BrainFlow board using the Julia library. It enables logging, initializes the BoardShim, prepares the session, starts streaming, pauses for a duration, stops streaming, and then fetches the current board data. Finally, it releases the session. ```julia using BrainFlow # specify logging library to use BrainFlow.enable_dev_logger(BrainFlow.BOARD_CONTROLLER) params = BrainFlowInputParams() board_shim = BrainFlow.BoardShim(BrainFlow.SYNTHETIC_BOARD, params) BrainFlow.prepare_session(board_shim) BrainFlow.start_stream(board_shim) sleep(5) BrainFlow.stop_stream(board_shim) data = BrainFlow.get_current_board_data(256, board_shim) BrainFlow.release_session(board_shim) ``` -------------------------------- ### Get Board Data (C#) Source: https://brainflow.readthedocs.io/en/stable/UserAPI Retrieves collected board data from the ring buffer. Overloads allow fetching all data, a specific number of data points, or data with a specified preset. Data can be optionally stored in a provided array to avoid memory allocation. ```csharp double[,] get_current_board_data (double[,] result, int preset=(int) BrainFlowPresets.DEFAULT_PRESET) get latest collected data, doesnt remove it from ringbuffer Parameters * **preset** – preset for device * **result** – array to store results, if provided BrainFlow does not allocate new memory Returns latest collected data, can be less than “num_samples” double[,] get_board_data () get all collected data and remove it from ringbuffer Returns collected data double[,] get_board_data (int num_datapoints) get collected data and remove it from ringbuffer Returns collected data double[,] get_board_data (int num_datapoints, int preset) get collected data and remove it from ringbuffer Parameters * **num_datapoints** – number of datapoints to get * **preset** – preset for device Returns all collected data double[,] get_board_data (double[,] data_arr, int preset) get collected data and remove it from ringbuffer Parameters * **data_arr** – array to store results, if provided BrainFlow will not allocate memory * **preset** – preset for device Returns all collected data ``` -------------------------------- ### Python: Get Data from Board Source: https://brainflow.readthedocs.io/en/stable/Examples This Python script demonstrates how to initialize a BrainFlow board, start streaming data, retrieve the data, and then stop the stream and release the session. It utilizes argparse to handle various board connection parameters. Dependencies include the BrainFlow package. ```python import argparse import time from brainflow.board_shim import BoardShim, BrainFlowInputParams, BoardIds def main(): BoardShim.enable_dev_board_logger() parser = argparse.ArgumentParser() # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port parser.add_argument('--timeout', type=int, help='timeout for device discovery or connection', required=False, default=0) parser.add_argument('--ip-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--serial-number', type=str, help='serial number', required=False, default='') parser.add_argument('--board-id', type=int, help='board id, check docs to get a list of supported boards', required=True) parser.add_argument('--file', type=str, help='file', required=False, default='') parser.add_argument('--master-board', type=int, help='master board id for streaming and playback boards', required=False, default=BoardIds.NO_BOARD) args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.serial_number = args.serial_number params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol params.timeout = args.timeout params.file = args.file params.master_board = args.master_board board = BoardShim(args.board_id, params) board.prepare_session() board.start_stream () time.sleep(10) # data = board.get_current_board_data (256) # get latest 256 packages or less, doesnt remove them from internal buffer data = board.get_board_data() # get all data and remove it from internal buffer board.stop_stream() board.release_session() print(data) if __name__ == "__main__": main() ``` -------------------------------- ### R Get Data from a Board Source: https://brainflow.readthedocs.io/en/stable/Examples This R code snippet demonstrates how to acquire data from a BrainFlow board. It initializes the BrainFlow library, prepares a session, starts streaming data, waits for a specified duration, stops the stream, retrieves the current board data, and releases the session. ```r library(brainflow) params <- brainflow_python$BrainFlowInputParams() board_shim <- brainflow_python$BoardShim(brainflow_python$BoardIds$SYNTHETIC_BOARD$value, params) board_shim$prepare_session() board_shim$start_stream() Sys.sleep(time = 5) board_shim$stop_stream() data <- board_shim$get_current_board_data(as.integer(250)) board_shim$release_session() ``` -------------------------------- ### Perform Bandstop Filter In-Place Source: https://brainflow.readthedocs.io/en/stable/UserAPI Applies a bandstop filter to the input data in-place. Requires data, sampling rate, start and stop frequencies, filter order, filter type, and ripple as parameters. ```c++ static inline void perform_bandstop (double[] data, int sampling_rate, double start_freq, double stop_freq, int order, int filter_type, double ripple) ``` ```c++ static inline void perform_bandstop (double[] data, int sampling_rate, double start_freq, double stop_freq, int order, FilterTypes filter_type, double ripple) ``` -------------------------------- ### Initialize Galea Board and Stream Data - Python Source: https://brainflow.readthedocs.io/en/stable/SupportedBoards Initializes the Galea board, prepares the session, starts data streaming for default (EEG, EMG, EOG) and auxiliary (Gyroscope, Accelerometer, etc.) presets, and saves the data to CSV files. It also demonstrates how to retrieve and print preset descriptions for the Galea board. ```python import time from pprint import pprint from brainflow.board_shim import BoardShim, BrainFlowInputParams, BrainFlowPresets, BoardIds from brainflow.data_filter import DataFilter def main(): BoardShim.enable_dev_board_logger() params = BrainFlowInputParams() board = BoardShim(BoardIds.GALEA_BOARD, params) board.prepare_session() board.start_stream() time.sleep(10) data_default = board.get_board_data(preset=BrainFlowPresets.DEFAULT_PRESET) data_aux = board.get_board_data(preset=BrainFlowPresets.AUXILIARY_PRESET) board.stop_stream() board.release_session() DataFilter.write_file(data_default, 'data_default.csv', 'w') DataFilter.write_file(data_aux, 'data_aux.csv', 'w') # To get info about channels and presets for preset in BoardShim.get_board_presets(BoardIds.GALEA_BOARD): preset_description = BoardShim.get_board_descr(BoardIds.GALEA_BOARD, preset) pprint(preset_description) if __name__ == "__main__": main() ``` -------------------------------- ### Insert Markers in C# Source: https://brainflow.readthedocs.io/en/stable/Examples Demonstrates how to insert markers into a data stream using the BrainFlow library in C#. It initializes a board, starts streaming, adds a file streamer, inserts markers at intervals, and then stops streaming and releases the session. This example requires BrainFlow NuGet package. ```csharp using System; using brainflow; using brainflow.math; namespace examples { class Markers { static void Main (string[] args) { BoardShim.enable_dev_board_logger (); BrainFlowInputParams input_params = new BrainFlowInputParams (); int board_id = parse_args (args, input_params); BoardShim board_shim = new BoardShim (board_id, input_params); board_shim.prepare_session (); board_shim.start_stream (); board_shim.add_streamer ("file://data.csv:w"); for (int i = 1; i < 5; i++) { System.Threading.Thread.Sleep (1000); board_shim.insert_marker (i); } board_shim.stop_stream (); board_shim.release_session (); } static int parse_args (string[] args, BrainFlowInputParams input_params) { int board_id = (int)BoardIds.SYNTHETIC_BOARD; //assume synthetic board by default // use docs to get params for your specific board, e.g. set serial_port for Cyton for (int i = 0; i < args.Length; i++) { if (args[i].Equals ("--ip-address")) { input_params.ip_address = args[i + 1]; } if (args[i].Equals ("--mac-address")) { input_params.mac_address = args[i + 1]; } if (args[i].Equals ("--serial-port")) { input_params.serial_port = args[i + 1]; } if (args[i].Equals ("--other-info")) { input_params.other_info = args[i + 1]; } if (args[i].Equals ("--ip-port")) { input_params.ip_port = Convert.ToInt32 (args[i + 1]); } if (args[i].Equals ("--ip-protocol")) { input_params.ip_protocol = Convert.ToInt32 (args[i + 1]); } if (args[i].Equals ("--board-id")) { board_id = Convert.ToInt32 (args[i + 1]); } if (args[i].Equals ("--timeout")) { input_params.timeout = Convert.ToInt32 (args[i + 1]); } if (args[i].Equals ("--serial-number")) { input_params.serial_number = args[i + 1]; } if (args[i].Equals ("--file")) { input_params.file = args[i + 1]; } } return board_id; } } } ``` -------------------------------- ### config_board_with_bytes Source: https://brainflow.readthedocs.io/en/stable/UserAPI Sends raw bytes to the board. Use with caution. ```APIDOC ## POST /config_board_with_bytes ### Description Sends raw bytes to the board. Use with caution. ### Method POST ### Endpoint /config_board_with_bytes ### Parameters #### Request Body - **bytes_to_send** (bytes) - Required - Bytes to send to the board. ### Response #### Success Response (200) - **message** (str) - Indicates success or failure of the operation. #### Response Example ```json { "message": "Bytes sent successfully" } ``` ``` -------------------------------- ### C++ Read Write File Example Source: https://brainflow.readthedocs.io/en/stable/Examples Demonstrates reading and writing data to a CSV file using BrainFlow's DataFilter class. It prepares a session, starts a stream, collects data, writes it to 'test.csv', then reads it back and prints both original and restored data. Error handling for BrainFlow exceptions is included. ```cpp #include #include #include #ifdef _WIN32 #include #else #include #endif #include "board_shim.h" #include "data_filter.h" using namespace std; int main (int argc, char *argv[]) { BoardShim::enable_dev_board_logger (); struct BrainFlowInputParams params; int res = 0; int board_id = (int)BoardIds::SYNTHETIC_BOARD; // use synthetic board for demo BoardShim *board = new BoardShim (board_id, params); try { board->prepare_session (); board->start_stream (); #ifdef _WIN32 Sleep (5000); #else sleep (5); #endif board->stop_stream (); BrainFlowArray data = board->get_current_board_data (10); board->release_session (); std::cout << "Original data:" << std::endl << data << std::endl; DataFilter::write_file (data, "test.csv", "w"); BrainFlowArray restored_data = DataFilter::read_file ("test.csv"); std::cout << "Restored data:" << std::endl << restored_data << std::endl; } catch (const BrainFlowException &err) { BoardShim::log_message ((int)LogLevels::LEVEL_ERROR, err.what ()); res = err.exit_code; if (board->is_prepared ()) { board->release_session (); } } delete board; return res; } ``` -------------------------------- ### Install BrainFlow Python Package Source: https://brainflow.readthedocs.io/en/stable/BuildBrainFlow Installs the latest BrainFlow release from PyPI using pip. For development versions, compile the core module first, then install from the local source. ```bash python -m pip install brainflow ``` ```bash cd python_package python -m pip install -U . ``` -------------------------------- ### Muse S Initialization Source: https://brainflow.readthedocs.io/en/stable/SupportedBoards Instructions for initializing the Muse S board. On Linux, libdbus installation and potentially compiling BrainFlow from source are recommended. Connection can be made via MAC address or serial number. ```APIDOC ## Muse S Initialization ### Description Initializes the Muse S board using BrainFlow. On Linux, libdbus installation and compiling BrainFlow from source may be required. Connection can be established using the device's MAC address or serial number. ### Method Initialization (Conceptual - involves creating a BoardShim instance) ### Endpoint N/A (Local library initialization) ### Parameters #### Board ID - **BoardIds.MUSE_S_BOARD** (enum) - Required - The identifier for the Muse S board. #### BrainFlowInputParams - **mac_address** (string) - Optional - The MAC address of the Muse S device. - **serial_number** (string) - Optional - The serial number or device name of the Muse S device. ### Initialization Example ```python params = BrainFlowInputParams() board = BoardShim(BoardIds.MUSE_S_BOARD, params) ``` ### Supported Platforms - Windows 10.0.19041.0+ - MacOS 10.15+ (Note: 12.0 to 12.2 have known issues; update to 12.3+. Bluetooth permissions may be needed on MacOS 12+). - Linux (compilation from source code probably will be needed). - Devices like Raspberry Pi ### Available BrainFlow Presets - `BrainFlowPresets.DEFAULT_PRESET`: Contains EEG data. To enable the 5th EEG channel, use `board.config_board("p50")`. - `BrainFlowPresets.AUXILIARY_PRESET`: Contains Gyro and Accel data (enabled by default). - `BrainFlowPresets.ANCILLARY_PRESET`: Contains PPG data. To enable it, use `board.config_board("p61")`. ``` -------------------------------- ### Install BrainFlow Typescript Package Source: https://brainflow.readthedocs.io/en/stable/BuildBrainFlow Installs the BrainFlow package for Node.js using npm. For development versions, compile the core module first, then run 'npm install' in the 'nodejs_package' directory. ```bash npm install brainflow ``` ```bash cd nodejs_package npm install ``` -------------------------------- ### Start Streaming with Buffer Size Source: https://brainflow.readthedocs.io/en/stable/UserAPI Initiates a streaming thread that stores data in an internal ring buffer. The buffer_size parameter specifies the capacity of this ring buffer. ```c++ inline void start_stream(int buffer_size) ``` -------------------------------- ### Start Data Streaming (Python) Source: https://brainflow.readthedocs.io/en/stable/UserAPI Initiates the streaming of data from the BrainFlow board. This method stores incoming data in a ring buffer with a specified size. Optionally, streamer parameters can be provided to direct the data stream simultaneously. ```python from brainflow.board_shim import BoardShim # Example usage: # Assuming 'board' is an initialized BoardShim object # board.start_stream(num_samples=10000) # With streamer parameters: # file_streamer_params = "file://my_data.csv:w" # board.start_stream(num_samples=10000, streamer_params=file_streamer_params) ``` -------------------------------- ### Install BrainFlow Julia Package Source: https://brainflow.readthedocs.io/en/stable/BuildBrainFlow Installs the BrainFlow package in Julia using the Pkg manager. The compiled BrainFlow libraries will be automatically downloaded on first use. ```julia import Pkg Pkg.add("BrainFlow") ``` -------------------------------- ### Get Other Channels for Board (Python) Source: https://brainflow.readthedocs.io/en/stable/UserAPI Retrieves a list of 'other' channels for a specified board ID and preset. This is useful for understanding the full data structure returned by a board. It raises a BrainFlowError if the board does not support this data. ```python from brainflow.board_shim import BrainFlowPresets # Example usage: board_id = 0 # Replace with actual board ID preset = BrainFlowPresets.DEFAULT_PRESET # Assuming 'board' is an initialized BoardShim object # other_channels = board._get_other_channels(board_id, preset) ``` -------------------------------- ### Initialize and Stream Data from Synthetic Board Source: https://brainflow.readthedocs.io/en/stable/notebooks/denoising Sets up a synthetic board for demonstration purposes, prepares the session, starts data streaming, collects a sample of data, and then stops and releases the session. This simulates real-time data acquisition. ```python # use synthetic board for demo params = BrainFlowInputParams() board_id = BoardIds.SYNTHETIC_BOARD.value board = BoardShim(board_id, params) board.prepare_session() board.start_stream() time.sleep(10) data = board.get_current_board_data(500) board.stop_stream() board.release_session() ``` -------------------------------- ### Get Current Board Data (Python) Source: https://brainflow.readthedocs.io/en/stable/UserAPI Retrieves a specified amount of the latest data from the board's ring buffer without removing it. If insufficient data is available, it returns all available data. This is useful for real-time monitoring or analysis where data is not immediately consumed. ```python import numpy as np from brainflow.board_shim import BoardShim, BrainFlowPresets # Example usage: # Assuming 'board' is an initialized BoardShim object and streaming is active # num_samples_to_get = 100 # data = board.get_current_board_data(num_samples_to_get) # print(f"Retrieved {data.shape[1]} samples.\n") ```