Skip to content

H9Chae/OBzip

Repository files navigation

OBzip

A low-cost, modular MATLAB–Teensy platform for real-time control and data acquisition in olfactory behavioral neuroscience experiments

OBzip coordinates a custom-built olfactometer, reward delivery, lick detection, sniff acquisition, trial logic, live monitoring, and structured data logging through a single MATLAB interface. A Teensy 4.1 performs time-sensitive hardware control and analog acquisition, while MATLAB manages experimental configuration, trial scheduling, visualization, and session-level data organization.

The current implementation was developed for odor-guided mouse behavior, but its modular design allows the stimulus-control layer to be adapted for auditory, visual, optogenetic, or other multimodal neuroscience experiments.

Scope: OBzip is a research-grade reference implementation for a custom laboratory setup. It is not a commercial olfactometer, and hardware-specific pin assignments, drivers, signal-conditioning circuits, and safety checks must be adapted to each rig.


Why OBzip?

Behavioral neuroscience systems require both precise hardware control and synchronized acquisition of physiological or behavioral signals. Commercial control and data-acquisition systems can be expensive, while simple microcontroller scripts often become difficult to maintain as experiments grow.

OBzip addresses this gap by combining:

  • a Teensy 4.1 board costing roughly US$40 as the core real-time controller;
  • MATLAB-based graphical experiment control;
  • digital control of odor and reward valves;
  • configurable analog acquisition for sniff and lick-related signals;
  • real-time event and analog-data transfer over USB;
  • automated trial-level and session-level data storage; and
  • an object-oriented software architecture in which hardware control, stimulation, data management, plotting, camera preview, and experiment logic are separated into independent modules.

The Teensy board is only the controller. Valves, valve drivers, sensors, signal-conditioning electronics, wiring, the olfactometer, and MATLAB are separate components of the complete system.


System overview

flowchart LR
    A[MATLAB GUI] --> B[MouseBehaviorController]
    B --> C[StimulationManager]
    B --> D[DataManager]
    B --> E[PlotManager]
    B --> F[CameraManager]
    B <--> G[TeensyInterface<br/>USB serial]

    G <--> H[Teensy 4.1 firmware]
    H --> I[Odor valve drivers]
    H --> J[Reward valve drivers]
    K[Lick sensors] --> H
    L[Sniff sensor<br/>conditioned analog input] --> H
    H --> M[Optional digital triggers<br/>or additional stimuli]
Loading

Division of responsibilities

MATLAB

  • graphical configuration of the experiment;
  • stimulus-group and trial-list generation;
  • standard and early-training workflows;
  • experiment start, pause, resume, and stop control;
  • real-time behavioral and sniff visualization;
  • camera preview;
  • metadata capture; and
  • trial-level and session-level data saving.

Teensy 4.1

  • real-time trial-state execution;
  • odor-valve and reward-valve control;
  • lick-event detection;
  • timer-driven analog acquisition;
  • manual reward commands;
  • event and analog packet generation; and
  • USB communication with MATLAB.

This separation keeps time-sensitive operations on the microcontroller while leaving experiment configuration, visualization, and data organization on the computer.


Current experimental capabilities

Odor-guided behavior

  • Go/No-Go odor-discrimination workflows
  • Up to four independently configured experimental groups in the MATLAB GUI
  • User-defined trial counts
  • Selection of Go and multiple No-Go odors
  • Adjustable Go-odor probability
  • Randomized stimulus-list generation
  • Partial regeneration of future stimulus trials when Go probability changes
  • Standard training and early-training modes
  • Reward-with-odor and reward-without-odor workflows
  • Always-reward and conditional-reward options

Behavioral control and monitoring

  • Single- or dual-lick-port operation
  • Independent reward ports A and B
  • Manual reward delivery
  • Configurable odor duration
  • Configurable lick latency and reward window
  • Start, stop, pause, and resume controls
  • Live indicators for odor, lick, and reward events
  • USB-camera preview

Analog and event acquisition

The included implementation acquires:

  • sniff analog signals;
  • lick-port A analog signals;
  • lick-port B analog signals; and
  • discrete trial, odor, lick, reward, and trial-outcome events.

The GUI currently provides the following selectable sampling settings:

Signal Selectable rates
Sniff 1, 5, or 10 kHz
Lick-related analog channels 1 or 5 kHz

Sampling is driven by Teensy IntervalTimer callbacks. Analog samples are transferred to MATLAB in binary packets, and the data manager reconstructs trial-aligned sample timestamps from the packet timestamp and configured sampling interval.


Low-cost analog acquisition

Teensy 4.1 provides a practical low-cost option for basic behavioral control and moderate-rate analog acquisition. In this implementation, the same microcontroller that controls the behavioral task also samples sniff and lick-related analog channels and streams them to MATLAB.

Important analog-input limitation

Teensy 4.1 analog inputs accept only unipolar signals from 0 to 3.3 V. Negative voltages and voltages above 3.3 V must not be connected directly.

Bipolar sensor signals therefore require an external analog front end, for example:

  • voltage offset or level shifting;
  • signal inversion;
  • scaling or attenuation;
  • buffering and filtering;
  • a bipolar-to-unipolar conversion circuit; or
  • acquisition of appropriately conditioned original and inverted signal paths.

The exact conditioning circuit depends on the sensor and is not included in this repository. All conditioned outputs must remain within the Teensy ADC input range.

Do not connect solenoid valves directly to Teensy output pins. Use appropriate MOSFET or driver circuits, external power supplies, flyback protection, and a shared-ground strategy suitable for the hardware.


Extensibility beyond olfaction

OBzip is currently configured around an olfactometer, but most of the framework is not intrinsically odor-specific.

The modular structure separates:

  • stimulus-list generation;
  • task and trial logic;
  • microcontroller communication;
  • event parsing;
  • analog acquisition;
  • data storage;
  • plotting; and
  • camera preview.

To adapt the platform to another sensory modality, the main changes would generally be concentrated in:

  1. the stimulus-specific GUI controls;
  2. stimulus definitions in StimulationManager;
  3. output-pin or communication logic in the Teensy firmware;
  4. event opcodes or packet fields, when new events are needed; and
  5. modality-specific plotting or metadata.

Possible extensions include:

  • auditory cues triggered by TTL or serial commands;
  • visual stimuli controlled by LEDs, displays, or external presentation software;
  • optogenetic stimulation triggers;
  • additional analog sensors;
  • locomotor or force sensors; and
  • multimodal cue combinations.

The framework should be treated as a starting architecture rather than a plug-and-play solution for every modality.


MATLAB software architecture

File Responsibility
MouseBehaviorController.m Coordinates the overall experiment, manager objects, trial progression, session state, and incoming Teensy events.
GUIManager.m Builds the MATLAB GUI for stimulation/acquisition settings, task control, early training, indicators, and manual reward.
TeensyInterface.m Opens the serial connection, encodes trial parameters, sends binary command packets, buffers incoming bytes, and parses event and analog packets.
StimulationManager.m Generates and updates randomized Go/No-Go stimulus lists for enabled groups.
DataManager.m Creates session folders, saves metadata, records trial events and analog streams, saves individual trials, and merges them into a session file.
PlotManager.m Displays behavioral performance and sniff-related data in real time.
CameraManager.m Provides USB-camera preview.
ExperimentParams.m Stores configurable task, acquisition, reward, timing, subject, and session parameters.
GroupData.m Shares mutable group-specific state across components.
Teensy/Teensy_OBzip.ino Implements real-time trial control, digital outputs, lick detection, analog sampling, reward logic, and packet transmission.

Communication protocol

MATLAB and Teensy communicate through a custom binary protocol.

MATLAB to Teensy

TeensyInterface.sendTrialParameters() packs the current trial configuration into a command packet containing parameters such as:

  • task mode;
  • lick-detection mode;
  • reward method;
  • reward duration;
  • odor duration;
  • lick latency;
  • reward window;
  • current stimulus;
  • lick-port mode;
  • analog-acquisition enable flags and sampling rates;
  • reward port; and
  • manual reward commands.

The packet includes start and end markers and a checksum.

Teensy to MATLAB

The firmware returns two broad packet classes:

  • event packets, carrying an opcode and timestamps; and
  • analog packets, carrying buffered 16-bit samples and a packet timestamp.

TeensyInterface parses these packets and forwards them to the controller, which then updates the GUI, plots, and data manager.


Data organization

Each session receives a timestamped folder containing:

EXP_YYYY-MM-DD_HH-MM-SS/
├── metadata.mat
├── Trial_001.mat
├── Trial_002.mat
├── ...
└── Session_<mouseID>_YYYY-MM-DD_HH-MM-SS.mat

Early-training sessions use the TRA_ prefix.

Session metadata

The metadata file stores:

  • session start time;
  • experiment parameters;
  • group configuration;
  • task mode;
  • subject identifier; and
  • experiment notes.

Trial data

Each trial can contain:

  • global trial index;
  • group index;
  • within-group trial index;
  • stimulus identity;
  • trial outcome;
  • trial start and end events;
  • lick onset, offset, and duration events;
  • sniff samples and timestamps;
  • lick-port A samples and timestamps; and
  • lick-port B samples and timestamps.

At the end of the experiment, trial files are merged into a session-level MATLAB structure.


Hardware configuration in the included firmware

The current firmware is configured for the author's custom rig and includes:

  • odor-valve outputs;
  • two reward-valve outputs;
  • two digital lick inputs;
  • two analog lick inputs;
  • one analog sniff input;
  • optional digital waveform or trigger outputs; and
  • USB communication with MATLAB.

Although the MATLAB interface supports odor identifiers from 1 to 10, the included Teensy firmware is currently configured for a four-odor output implementation. Update odorPins, NUM_ODORS, and any related driver logic to match another olfactometer.

Pin numbers, electrical interfaces, active-high/active-low behavior, sensor thresholds, and valve timing must be verified for each rig before use.


Requirements

Hardware

  • Teensy 4.1
  • USB cable
  • custom olfactometer
  • odor-valve driver circuitry
  • reward-delivery hardware and driver circuitry
  • lick detector(s)
  • sniff pressure sensor and appropriate signal conditioning
  • optional USB camera
  • computer running MATLAB

Software

  • MATLAB R2024a or a compatible release
  • MATLAB serial-port support
  • MATLAB webcam support package when camera preview is used
  • Arduino IDE with Teensy board support, or PlatformIO
  • matching Teensy_OBzip.ino firmware

Initial configuration

Before running the system, review and modify the hardware-specific defaults.

MATLAB

  • Serial port in MouseBehaviorController.m
    • current default: COM8
  • Serial rate in MouseBehaviorController.m
    • current value: 2000000
  • Default data path in DataManager.m
    • current default: C:\temp
  • Camera selection and resolution in CameraManager.m
    • the current code selects the second detected camera
  • Odor names and default task parameters in ExperimentParams.m

Teensy firmware

  • odor output pins;
  • number of odor outputs;
  • reward output pins;
  • digital and analog lick-input pins;
  • sniff analog-input pin;
  • lick thresholds;
  • valve polarity;
  • optional trigger outputs; and
  • any external driver or conditioning circuitry.

Running the MATLAB interface

Place the MATLAB class files on the MATLAB path and run:

controller = MouseBehaviorController();

Constructing the controller initializes the manager objects, attempts to connect to the configured Teensy serial port, and opens the experiment GUI.

Before connecting live hardware:

  1. confirm all pin assignments;
  2. confirm the serial port;
  3. confirm valve-driver polarity;
  4. verify that every analog input remains between 0 and 3.3 V;
  5. test outputs with valves disconnected or with safe dummy loads;
  6. verify reward duration and fluid delivery; and
  7. validate event timing and saved data with a short test session.

Repository status

This repository documents a working custom laboratory system, but it remains hardware-specific research software. Important future improvements include:

  • moving hardware settings into external configuration files;
  • adding a wiring diagram and analog-front-end schematic;
  • adding a simulated-hardware mode;
  • adding automated packet-protocol tests;
  • separating generic stimulus logic from odor-specific naming;
  • adding installation and calibration procedures;
  • adding example session data;
  • adding screenshots of the GUI and live plots; and
  • validating operation across additional MATLAB and Teensy software versions.

Research and development context

OBzip was developed to support custom olfactometer-based mouse behavioral experiments in an academic neuroscience setting. The project integrates experimental design, embedded control, sensor acquisition, behavioral-task logic, graphical software, and reproducible data organization in a single extensible framework.

Developer: Honggoo Chae, Ph.D.
Contact: mnjchae@gmail.com

About

Object-oriented, extensible behavioral testing framework for Odor Discrimination and multi-modal experiments. Features real-time Teensy/MATLAB integration and automated data logging.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages