scieee AI-readable full text Open interactive document viewer

Generation of real-time control commands from EEG signals

Franco i Moral, Ferran

Abstract

Brain-computer interfaces (BCI) have been studied for decades for their potential to control devices by monitoring brain activity. Specifically, MI-based BCI systems (Motor Imagery) have proven highly effective in the field of neurorehabilitation, as the brain patterns generated closely resemble those produced during actual movements. This work proposes a protocol designed to acquire and analyze BCI data using the Bitbrain Hero Helmet device, aiming to explore its use in practical applications. The project is part of POSMOFYA, an acronym for the Hybrid Platform of OrthosisWheelchair to ensure compatibility of Mobility, Functionality, and Acceptability for use in domestic environments. This hybrid platform, as its name suggests, integrates an automated wheelchair and a robotic arm. The ultimate goal is to enable efficient and practical control in domestic environments. The developed protocol is based on principles of robustness and precision, aiming to enhance the ability to recognize users’ movement intentions. This work is structured into several phases, beginning with the experimental design. Using the PsychoPy software and the LabStreaming Layer (LSL) protocol, motor imagery tasks were defined focusing on two specific actions: right wrist flexion and left wrist flexion. These tasks were designed to generate brain patterns associated with clear movement intentions, with the goal of training a Machine Learning (ML) system. The strategy ensures precise and consistent capture of brain signals, essential for advancing the development of practical applications within the project framework. The results reflect the challenges of working with EEG signals. Although the Decision Tree algorithm applied to Common Spatial Patterns (CSP) achieved a validation accuracy of 42.9% in offline mode, and K-Nearest Neighbors (KNN) reached 51.0% accuracy with literature-based features, the predictions were biased towards a single class. This highlights limitations in signal discrimination and variability between sessions. Despite the difficulties, the project has provided valuable lessons: the need to improve EEG systems and explore advanced techniques such as Regularized CSP or hybrid methods with deep learning to increase robustness and precision. Additionally, the basic steps of the online pipeline were validated, indicating that better optimization could result in more reliable practical applications. These findings not only highlight the field’s challenges but also point to opportunities for improvement in future research.

Full text

Treball de Fi de Màster Màster en Neuroenginyeria i Rehabilitació Generation of real-time control commands from EEG signals REPORT Author: Ferran Franco i Moral Director: Joan Francesc Alonso López Co-director: Andres El-Fakdi Sencianes Co-director: Alicia Casals Gelpí Date: February 2025 Escola Tècnica Superior d’Enginyeria Industrial de Barcelona Pag. 2 Report Generation of real-time control commands from EEG signals Pag. 3 Resum Les interfícies cervell-ordinador (BCI) han estat investigades durant dècades pel seu potencial per controlar dispositius a través del monitoratge de l'activitat cerebral. En particular, els sistemes BCI basats en Motor Imagery (MI) han demostrat una gran efectivitat en el camp de la neurorehabilitació, ja que els patrons cerebrals generats són similars als produïts durant els moviments reals. Aquest treball proposa un protocol dissenyat per adquirir i analitzar dades BCI utilitzant el dispositiu Bitbrain Hero Helmet, amb l'objectiu d'explorar el seu ús en aplicacions pràctiques. El projecte forma part de POSMOFYA, acrònim de la Plataforma Híbrida Órtesis-Silla para hacer compatible la Movilidad, Funcionalidad y Aceptabilidad de aplicación en entornos domésticos, una plataforma híbrida que, com el nom indica, integra una cadira de rodes automatitzada i un braç robòtic. L'objectiu final és permetre un control eficient i pràctic en entorns domèstics. El protocol desenvolupat es basa en principis de robustesa i precisió, amb la intenció de millorar la capacitat de reconèixer les intencions de moviment dels usuaris. Aquest treball s’estructura en diverses fases, iniciant amb el disseny experimental. Amb l’ús del programari PsychoPy i el protocol LabStreaming Layer (LSL), es van establir tasques de motor imagery enfocades a dues accions específiques: la flexió del canell dret i la flexió del canell esquerre. Aquestes tasques es van dissenyar per generar patrons cerebrals associats a intencions de moviment clares, amb l’objectiu d’entrenar un sistema de Machine Learning (ML). L’estratègia permet assegurar una captura precisa i consistent de les senyals cerebrals, fonamental per avançar en el desenvolupament d’aplicacions pràctiques en el marc del projecte. Els resultats reflecteixen els desafiaments de treballar amb senyals EEG. Tot i que l'algorisme d'Arbre de Decisió aplicat a Common Spatial Patterns (CSP) va obtenir una precisió del 42,9% en mode offline i el K-Nearest Neighbors (KNN) una precisió del 51,0% amb característiques basades en la literatura, les prediccions es van mostrar esbiaixades cap a una sola classe. Aquest fet posa de manifest limitacions en la discriminació de senyals i la variabilitat entre sessions. Malgrat les dificultats, el projecte ha proporcionat lliçons valuoses: la necessitat de millorar els sistemes EEG i d'explorar tècniques avançades com CSP regularitzat o mètodes híbrids amb deep learning per augmentar la robustesa i precisió. A més, s'han validat els passos bàsics del pipeline online, indicant que una millor optimització podria traduir-se en aplicacions pràctiques més fiables. Aquestes troballes no només destaquen els reptes del camp sinó també oportunitats de millora per futures recerques. Pag. 4 Report Resumen Las interfaces cerebro-computador (BCI) han sido investigadas durante décadas por su potencial para controlar dispositivos mediante el monitoreo de la actividad cerebral. En particular, los sistemas BCI basados en Motor Imagery (MI) han demostrado gran efectividad en el ámbito de la neurorrehabilitación, ya que los patrones cerebrales generados son similares a los producidos durante los movimientos reales. Este trabajo propone un protocolo diseñado para adquirir y analizar datos BCI utilizando el dispositivo Bitbrain Hero Helmet, con el objetivo de explorar su uso en aplicaciones prácticas. El proyecto forma parte de POSMOFYA, acrónimo de Plataforma Híbrida Órtesis-Silla para hacer compatible la Movilidad, Funcionalidad y Aceptabilidad de aplicación en entornos domésticos, una plataforma híbrida que, como su nombre indica, integra una silla de ruedas automatizada y un brazo robótico. El objetivo final es permitir un control eficiente y práctico en entornos domésticos. El protocolo desarrollado se basa en principios de robustez y precisión, con la intención de mejorar la capacidad de reconocer las intenciones de movimiento de los usuarios. Este trabajo se estructura en varias fases, comenzando con el diseño experimental. Con el uso del software PsychoPy y el protocolo LabStreaming Layer (LSL), se establecieron tareas de motor imagery centradas en dos acciones específicas: la flexión de la muñeca derecha y la flexión de la muñeca izquierda. Estas tareas se diseñaron para generar patrones cerebrales asociados con intenciones de movimiento claras, con el objetivo de entrenar un sistema de Machine Learning (ML). La estrategia permite asegurar una captura precisa y consistente de las señales cerebrales, fundamental para avanzar en el desarrollo de aplicaciones prácticas en el marco del proyecto. Los resultados reflejan los desafíos de trabajar con señales EEG. Aunque el algoritmo de Árbol de Decisión aplicado a Common Spatial Patterns (CSP) obtuvo una precisión del 42,9% en modo offline y el K-Nearest Neighbors (KNN) una precisión del 51,0% con características basadas en la literatura, las predicciones mostraron sesgos hacia una sola clase. Esto pone de manifiesto limitaciones en la discriminación de señales y la variabilidad entre sesiones. A pesar de las dificultades, el proyecto ha proporcionado lecciones valiosas: la necesidad de mejorar los sistemas EEG y explorar técnicas avanzadas como CSP regularizado o métodos híbridos con deep learning para aumentar la robustez y la precisión. Además, se han validado los pasos básicos del pipeline online, indicando que una mejor optimización podría traducirse en aplicaciones prácticas más fiables. Estos hallazgos no solo destacan los retos del campo, sino también oportunidades de mejora para futuras investigaciones. Generation of real-time control commands from EEG signals Pag. 5 Abstract Brain-computer interfaces (BCI) have been studied for decades for their potential to control devices by monitoring brain activity. Specifically, MI-based BCI systems (Motor Imagery) have proven highly effective in the field of neurorehabilitation, as the brain patterns generated closely resemble those produced during actual movements. This work proposes a protocol designed to acquire and analyze BCI data using the Bitbrain Hero Helmet device, aiming to explore its use in practical applications. The project is part of POSMOFYA, an acronym for the Hybrid Platform of OrthosisWheelchair to ensure compatibility of Mobility, Functionality, and Acceptability for use in domestic environments. This hybrid platform, as its name suggests, integrates an automated wheelchair and a robotic arm. The ultimate goal is to enable efficient and practical control in domestic environments. The developed protocol is based on principles of robustness and precision, aiming to enhance the ability to recognize users’ movement intentions. This work is structured into several phases, beginning with the experimental design. Using the PsychoPy software and the LabStreaming Layer (LSL) protocol, motor imagery tasks were defined focusing on two specific actions: right wrist flexion and left wrist flexion. These tasks were designed to generate brain patterns associated with clear movement intentions, with the goal of training a Machine Learning (ML) system. The strategy ensures precise and consistent capture of brain signals, essential for advancing the development of practical applications within the project framework. The results reflect the challenges of working with EEG signals. Although the Decision Tree algorithm applied to Common Spatial Patterns (CSP) achieved a validation accuracy of 42.9% in offline mode, and K-Nearest Neighbors (KNN) reached 51.0% accuracy with literature-based features, the predictions were biased towards a single class. This highlights limitations in signal discrimination and variability between sessions. Despite the difficulties, the project has provided valuable lessons: the need to improve EEG systems and explore advanced techniques such as Regularized CSP or hybrid methods with deep learning to increase robustness and precision. Additionally, the basic steps of the online pipeline were validated, indicating that better optimization could result in more reliable practical applications. These findings not only highlight the field’s challenges but also point to opportunities for improvement in future research. Pag. 6 Report Generation of real-time control commands from EEG signals Pag. 7 Contents RESUM ______________________________________________________ 3 RESUMEN ___________________________________________________ 4 ABSTRACT ___________________________________________________ 5 CONTENTS ___________________________________________________ 7 GLOSSARY __________________________________________________ 9 LIST OF FIGURES ____________________________________________ 10 LIST OF TABLES _____________________________________________ 12 1. PREFACE _______________________________________________ 14 1.1. How the project originated ........................................................................... 14 1.2. Motivation ..................................................................................................... 14 2. INTRODUCTION __________________________________________ 15 2.1. Problem Statement ...................................................................................... 15 2.2. Justification .................................................................................................. 16 2.3. Scope ........................................................................................................... 16 2.4. Prerequisites ................................................................................................ 16 2.5. Objectives .................................................................................................... 17 3. THEORETICAL FRAMEWORK ______________________________ 18 3.1. Movement-Limiting Disorders ...................................................................... 18 3.2. Electroencephalography (EEG) ................................................................... 18 3.2.1. Frequency Bands ............................................................................................ 19 3.2.2. 10-20 system .................................................................................................. 20 3.3. Brain-Computer Interfaces (BCI) ................................................................. 21 3.4. Overview of Motor Imagery-Based BCIs...................................................... 22 3.4.1. Challenges in MI signal Classification ............................................................. 22 3.4.2. Dry EEG Systems in BCIs ............................................................................... 22 3.4.3. Applications in Assistive Technologies ............................................................ 23 3.5. Key Features ................................................................................................ 23 3.5.1. Generic Features based on Literature ............................................................. 23 3.5.2. Common Spatial Patterns (CSP)..................................................................... 25 3.5.3. Limitations ....................................................................................................... 25 3.6. Lab Streaming Layer (LSL) protocol ............................................................ 27 3.7. PsychoPy ..................................................................................................... 29 Pag. 8 Report 4. METHODOLOGY AND EQUIPMENT__________________________ 30 4.1. Participants .................................................................................................. 30 4.2. Experimental Design .................................................................................... 30 4.3. Signal Acquisition ......................................................................................... 31 4.4. Experimental paradigm ................................................................................ 31 4.4.1. Software .......................................................................................................... 32 4.5. EEG Preprocessing ..................................................................................... 39 4.6. Feature extraction ........................................................................................ 40 4.6.1. Literature based features ................................................................................ 40 4.6.2. Common Spatial Patterns ............................................................................... 41 4.6.3. Summary of Feature Extraction Implementation ............................................. 41 4.7. Machine Learning Analysis .......................................................................... 42 4.7.1. Features Based on Literature .......................................................................... 42 4.7.2. Common Spatial Patterns ............................................................................... 44 5. RESULTS _______________________________________________ 46 5.1. Literature-Based Features ........................................................................... 46 5.1.1. Data Overview ................................................................................................ 46 5.1.2. Feature Extraction and Analysis ...................................................................... 47 5.1.3. Classification Results ...................................................................................... 50 5.2. Common Spatial Patterns (CSP) ................................................................. 53 5.2.1. Data Overview ................................................................................................ 53 5.2.2. Feature Extraction and Analysis ...................................................................... 53 5.2.3. Classification Results ...................................................................................... 55 6. DISCUSSION ____________________________________________ 58 6.1. Literature-based Features ............................................................................ 58 6.2. Common Spatial Patterns (CSP) ................................................................. 59 6.3. Comparison of Classifier Performance ........................................................ 59 7. LIMITATIONS AND FUTURE WORK __________________________ 61 8. PLANNING ______________________________________________ 63 9. ENVIRONMENTAL IMPACT ANALYSIS _______________________ 64 10. ECONOMIC ANALYSIS ____________________________________ 65 11. CONCLUSIONS __________________________________________ 66 12. ACKNOWLEDGMENTS ____________________________________ 67 13. BIBLIOGRAPHY __________________________________________ 68 14. ADDITIONAL BIBLIOGRAPHY ______________________________ 75 Generation of real-time control commands from EEG signals Pag. 9 Glossary TFM Treball fi de grau (Final Master Thesis in Catalan) EEG Electroencephalography BCI Brain-Computer interface MI Motor Imagery ICA Independent Component Analysis SCI Spinal cord injury ALS Amyotrophic lateral sclerosis LSL Lab streaming layer ML Machine learning SVM Support vector machine KNN K-Nearest Neighbors RMS Root Mean Square PTP Peak-to-Peak Amplitude POSMOFYA Plataforma Híbrida Órtesis-Silla para hacer compatible la Movilidad, Funcionalidad y Aceptabilidad de aplicación en entornos domésticos. PNS Peripheral Nervous System CNS Central Nervous System SCI Spinal Cord Injury LAN Local Area Network NTP Network Time Protocol XDF Extensible Data Format Pag. 16 Report 2.2. Justification Given the variability in EEG signal quality, the question arises as to whether it is possible to create a BCI system with Dry EEG helmets. Dry EEG helmets have been actively researched by multiple studies trying to find if this technique can be able to provide good results compared with wet EEG helmets [11,12,13]. In addition to addressing the limitations of dry EEG systems, this project is justified by the growing demand for non-invasive, portable, and user-friendly solutions in neurorehabilitation and assistive technologies [14]. Wet EEG helmets, while providing high-quality signals, require labour-intensive preparation and maintenance, limiting their applicability in daily life scenarios and large-scale implementations [15]. Dry EEG systems offer a practical alternative by significantly reducing setup time and enabling broader adoption, provided their performance can be optimized [15]. 2.3. Scope The scope of this project is to develop and validate a dry EEG-based BCI system that serves as an additional control tool for the POSMOFYA initiative. This system is designed to demonstrate acceptable accuracy in performing MI tasks, with the long-term aim of integrating and testing it on the actual POSMOFYA wheelchair. Temporally, the project spans from initial algorithm design to experimental validation within controlled environments. The spatial application focuses on assistive device integration, ensuring compatibility with existing POSMOFYA components. Recognizing the time constraints of this thesis, the technological focus is on establishing a foundational pipeline that includes signal acquisition, preprocessing, classifier training, and real-time classification. This project aims to provide a first approach to a dry EEGbased BCI system, structured as a modular framework with clearly defined components. Each block of the system is designed to serve as a foundation for further refinement and optimization in subsequent research. While this work does not extend to hardware production or large-scale deployment, it emphasizes the importance of laying a scalable groundwork that can evolve over time. By prioritizing usability, adaptability, and continuous improvement, this project seeks to contribute to the broader goal of developing more accessible and effective BCI-driven assistive technologies. Generation of real-time control commands from EEG signals Pag. 17 2.4. Prerequisites Several prerequisites were established to ensure the project’s feasibility and success: - Equipment Selection: The Bitbrain Hero Helmet was chosen for its dry electrode technology, which simplifies setup while providing high-resolution EEG signal acquisition. Utilizing dry electrode technology offers an economical and efficient solution to the problem being addressed. - Software Tools: PsychoPy was selected for experiment design, while the LabStreaming Layer (LSL) was employed for synchronized data collection and streaming. - Signal Processing Knowledge: Familiarity with EEG preprocessing techniques, such as filtering, artifact removal, and feature extraction methods (e.g., EventRelated Desynchronization (ERD) and Event-Related Synchronization (ERS)), was essential. This expertise was acquired during the Master’s program in Neuroengineering and Rehabilitation, with this project serving as the final master’s thesis. - Machine Learning Expertise: Familiarity in implementing classifiers for real-time signal decoding was crucial, with a focus on algorithms suitable for EEG data, such as Support Vector Machines (SVMs) and neural networks. 2.5. Objectives In this exploratory project, the goal is to develop a robust BCI system using a dry EEG helmet to contribute to the POSMOFYA project. The specific objectives are: - Signal Acquisition and Analysis: Design a protocol for acquiring and analysing motor imagery (MI) data using the Bitbrain Hero Helmet, focusing on two movement classes: right wrist flexion and left wrist flexion. - Machine Learning Integration: Implement a machine learning pipeline for real-time classification of MI signals, ensuring accurate and reliable predictions for control tasks. - Usability and Practicality: Demonstrate the feasibility of using dry electrode EEG systems in practical applications by optimizing setup efficiency without compromising signal quality, paving the way for integration with the POSMOFYA wheelchair in future iterations. Pag. 18 Report 3. Theoretical Framework This chapter provides a thorough overview of the foundational knowledge essential for understanding the research conducted in this work. It begins by defining neuromuscular disorders and exploring the tools designed to address the movement limitations they impose. The discussion then shifts to the principles of EEG, its role in Brain-Computer Interfaces (BCI), and the significance of Motor Imagery (MI). Furthermore, the chapter examines the tools and methodologies employed in BCI development, along with the key features integral to working with MI and BCI systems. 3.1. Movement-Limiting Disorders Movement disorders represent a complex group of neurological conditions encompassing a wide spectrum of impairments, ranging from reduced movement (hypokinesia) to excessive movement (hyperkinesia) [16]. While Parkinson’s disease is often regarded as the classical example of movement disorder, many other pathologies fall within this category. For instance, Huntington’s disease, a condition with a strong genetic basis, also qualifies as a movement disorder [16]. In addition to these classic examples, conditions such as spinal cord injury (SCI) can also be classified as movement-limiting disorders. SCI involves a lesion to the spinal cord resulting from causes such as falls, motor vehicle accidents, or acts of violence. These injuries lead to varying degrees of dysfunction in sensory, motor, and autonomic functions due to the partial or complete loss of communication between the brain and body regions below the site of injury [17,18,19]. SCI is further associated with a range of secondary complications of varying severity, significantly affecting quality of life and contributing to increased morbidity and mortality [17,19]. 3.2. Electroencephalography (EEG) Electroencephalography (EEG) is a non-invasive neurophysiological method that measures the brain's electrical activity through electrodes placed on the scalp. It captures the synchronous firing of large populations of neurons, offering a temporally precise measure of brain function with millisecond resolution [20]. Despite the development of advanced imaging techniques, EEG remains a cornerstone in clinical and research applications. It is indispensable for evaluating seizures, distinguishing seizure types, and investigating conditions that mimic seizures. Additionally, it is employed in assessing comatose patients, monitoring encephalopathies, and exploring sensory, perceptual, and cognitive processes. [21] Generation of real-time control commands from EEG signals Pag. 19 The electrical properties of the brain were first discovered by English scientist Richard Caton in 1875, and approximately 50 years later, German psychiatrist Hans Berger recorded the first human EEG, marking a pivotal advancement in neuroscience [22, 23]. 3.2.1. Frequency Bands The frequency range of interest in EEG recordings typically spans from 0.5 to 30 Hz. Since the early use of this technology, five frequency rhythms have been identified as being associated with different types of brain activity [24].  Delta rhythm (0.5–4 Hz): Characterized by high-amplitude waves, these are typically observed in infants or during slow-wave sleep in adults.  Theta rhythm (4–8 Hz): Linked to drowsiness in adults and teenagers, this rhythm is more pronounced in children. It is also associated with pleasurable states and is predominantly found in the parietal and temporal lobes.  Alpha rhythm (8–13 Hz): Present in awake, relaxed individuals, this rhythm is associated with eye closure and brain-wide inhibition control. When occurring over the motor cortex, it is referred to as the mu rhythm, which is notably suppressed during motor actions.  Beta rhythm (13–30 Hz): Active during states ranging from calm alertness to mild obsessive focus, this rhythm is associated with active thinking, attention, focus, and both physical and high-concentration activities. Fig 1. EEG rhythms [25] Pag. 20 Report 3.2.2. 10-20 system The 10-20 system is a globally recognized standard for electrode placement on the scalp. Its primary purpose is to provide a standardized approach to EEG acquisition, ensuring studies can be consistently reproduced and accurately analysed [26]. The numbers "10" and "20" refer to the percentage distances between adjacent electrodes, measured relative to the total front-to-back or right-to-left span of the head. See Fig. 2. Fig 2. 10-20 system [27] In addition to the 10-20 system, several other electrode placement systems are used for EEG recordings, depending on the desired spatial resolution and application [28]:  10-10 System: An extension of the 10-20 system, offering higher resolution with 81 positions for more detailed scalp coverage.  10-5 System: A further refinement of the 10-10 system, providing even more electrode positions for enhanced precision.  High-Density Systems: These include setups like the EGI 64 and 128-channel Geodesic Sensor Nets, designed for advanced studies requiring detailed spatial resolution.  Customizable Placement: Tailored electrode arrangements are used in specific research or clinical applications, particularly in neurotechnology.  Ear-Based Systems: Specialized setups focused on detecting frequency components using sensors placed in or around the ears. These systems allow for flexibility and precision tailored to the specific needs of various EEG studies and applications. Generation of real-time control commands from EEG signals Pag. 21 3.3. Brain-Computer Interfaces (BCI) A brain-computer interface (BCI) system establishes a direct communication pathway between the brain and an external device [29]. These systems have been under development for decades, with the choice of BCI technology largely dictated by its intended application [30]. Among the non-invasive BCI paradigms reported in the literature, the most prominent and effective approaches are based on evoked responses (P300), steady-state visually evoked potentials (SSVEP), and motor imagery (MI) [31]. Despite this, research focusing on EEG-based MI for lower limb movements in BCIcontrolled applications remains relatively limited [32, 33]. Many such studies have been confined to offline scenarios due to the complexities involved in the movements and the experimental setups, which often generate EEG signals that differ significantly from those obtained in realistic online environments [34]. Fig 3. Brain-Computer Interface scheme [35] BCI operates following four main stages [36]: 1. Signal Acquisition and Pre-Processing: Brain signals are recorded using sensors and amplified to prepare them for further processing. Filtering may also be applied to enhance desirable characteristics and reduce noise. 2. Feature Extraction and Selection: The recorded signals are analysed to identify specific features that correlate with the user’s intended actions. 3. Feature Translation: These extracted features are then transformed into actionable commands for the output device. 4. Control Interface: The operation of the device provides feedback to the user, creating a closed-loop control system. Pag. 22 Report 3.4. Overview of Motor Imagery-Based BCIs Motor Imagery (MI) is a mental process where individuals simulate motor movements without physically executing them. This mental rehearsal triggers similar neural patterns to those of actual movements, which can be captured non-invasively using EEG. MI-based BCIs have demonstrated immense potential in enabling motor rehabilitation, enhancing neuroplasticity, and providing control mechanisms for robotic systems [37, 38]. Key elements of MI-based BCIs include:  Event-Related Desynchronization (ERD) and Synchronization (ERS): These neural patterns, detectable through EEG, serve as biomarkers for motor intention and are crucial for feature extraction [38, 39].  Machine Learning for Classification: Modern approaches employ deep learning and traditional classifiers to decode MI signals. Deep learning methods, such as Convolutional Neural Networks (CNNs), have shown promising results in handling EEG's high-dimensional and noisy nature [39]. 3.4.1. Challenges in MI signal Classification Despite significant advancements, several challenges persist:  Noise and Artifacts: EEG signals are highly susceptible to artifacts from muscle movements, eye blinks, and environmental factors [39].  Inter-subject Variability: Differences in neural patterns across individuals necessitate robust and generalizable classifiers [37,39].  Real-Time Processing: Achieving low-latency and accurate signal decoding is critical for practical applications [38]. This project builds upon these theoretical foundations, leveraging advancements in EEG technology and machine learning to address these challenges and push the boundaries of MI-based BCI applications. 3.4.2. Dry EEG Systems in BCIs The transition from wet to dry EEG systems addresses several challenges in practical applications, such as setup complexity and user comfort. Studies have highlighted the feasibility and accuracy of dry systems, demonstrating their capability in capturing MIrelated signals [38]. These systems ensure portability and ease of use, making them suitable for real-world environments [40]. Generation of real-time control commands from EEG signals Pag. 23 3.4.3. Applications in Assistive Technologies MI-based BCIs are increasingly used in assistive technologies, particularly for controlling robotic wheelchairs and arms. The integration of BCIs with mobility solutions has been extensively researched, with emphasis on real-time control, adaptability, and user acceptance [39, 40]. For instance, EEG-based control systems have been deployed in navigating real-world environments and performing complex tasks like object manipulation using robotic arms [38, 39]. 3.5. Key Features Understanding the core features of BCI systems is crucial for their effective design and application. To develop a functional and accurate BCI system, specific features must be selected to serve as input for machine learning algorithms. This section is divided into two subsections: the first addresses Generic Features based on Literature, emphasizing commonly recognized characteristics and methodologies reported in academic research. The second explores into Common Spatial Patterns (CSP), a widely adopted technique for feature extraction and classification in BCI systems [41, 42]. Together, these subsections provide a comprehensive foundation for selecting and utilizing features essential for building robust BCI systems. 3.5.1. Generic Features based on Literature The success of BCI systems in MI tasks relies on the ability to identify and extract robust EEG features. These features, can be drawn from time, frequency and entropy domains and they offer significant insights into neural activity. Many papers appeared on the last years trying to find which are or could be some of the most interesting features to study MI and have a successful BCI system [43,44,45,46,47,48]. Here are some of the most commonly used features: Table 1. Commonly used EEG features for BCI systems based on MI [43,44,45,46,47,48]. Features Definition Time domain Features Root Mean Square (RMS) Provides an estimate of the signal’s amplitude and is used to evaluate overall signal strength [43,44]. Peak-to-Peak Amplitude (PTP) Assesses amplitude variability, aiding in identifying neural activity differences across MI states [44,45]. Pag. 24 Report Fractal Dimension (FD), Hurst Exponent, Skewness and Kurtosis These metrics measure the complexity and statistical properties of EEG signals, essential for distinguishing MI patterns [43,46]. Frequency Domain Features Delta, Theta, Alpha, Beta and Gamma Power These frequency bands are closely associated with cognitive and motor tasks, with changes observed during MI in the corresponding motor and sensory regions [44,45]. Power Spectral Density (PSD) Commonly used to quantify event-related desynchronization/synchronization (ERD/ERS) during MI tasks [43,45]. Entropy and Complexity Features Sample Entropy, Shannon Entropy and Permutation Entropy These measures quantify irregularity and unpredictability in EEG, offering insights into neural dynamics using MI [44,46,47]. Lempel-Ziv Complexity Reflects the compressibility of EEG signals, highlighting their randomness and underlying neural processing efficiency [45,46]. Advanced Feature Extraction Techniques Common Spatial Patterns (CSP) A widely used method for spatial filtering, CSP effectively discriminates between MI tasks by optimizing the variance of EEG signals [45,46,47]. Wavelet Transform (WT) Often combined with CSP, WT enhances feature extraction by decomposing EEG signals into the time-frequency domain [45,46]. These EEG features have been extensively validated in various MI-based BCI frameworks, showcasing their utility in improving classification accuracy and system performance. Additionally, integrating these features into modern machine learning methods amplifies their effectiveness in real-world applications [43, 44, 45, 46]. Generation of real-time control commands from EEG signals Pag. 25 3.5.2. Common Spatial Patterns (CSP) Among the advanced techniques for EEG feature extraction, Common Spatial Patterns (CSP) stands out as one of the most powerful and widely used methods in the domain of BCIs [49]. CSP is specifically designed to extract discriminative spatial features by optimizing the variance differences between two or more classes of motor imagery tasks [49]. This optimization enables effective spatial filtering of EEG signals, often leading to significant improvements in classification accuracy for motor imagery tasks [50]. CSP operates by learning spatial filters that maximize the variance for one class while minimizing it for another. This approach emphasizes the spatial patterns most relevant to the differences in brain activity associated with the motor tasks. By transforming the EEG data into a space where these patterns are highlighted, CSP facilitates the extraction of features that are highly informative for classification [51]. Over the years, CSP has seen numerous variations and enhancements to address its limitations, such as susceptibility to noise, overfitting in high-dimensional data, and dependence on specific experimental setups. - Filter Bank CSP (FBCSP) incorporates band-pass filtering to isolate frequency bands of interest, often improving robustness [50]. - Regularized CSP (R-CSP) applies regularization techniques to mitigate overfitting, especially in datasets with a small number of trials [51]. - Riemannian Geometry-based CSP (RG-CSP) projects covariance matrices onto a Riemannian manifold, leveraging the intrinsic geometric properties of these matrices to enhance feature extraction [51]. Recent research has also integrated CSP with deep learning frameworks to combine its feature extraction capabilities with the pattern recognition strength of neural networks. These hybrid approaches have shown promise in improving classification accuracy and reducing dependency on manual feature engineering [50]. 3.5.3. Limitations Firstly, the frequent use of healthy subjects in BCI studies can lead to unrealistic results, as it has been shown that target users (e.g., individuals with motor disabilities) typically perform worse [51]. Additionally, MI-BCIs require users to undergo extensive training sessions for calibration, which can become excessively time-consuming. This prolonged training often leads to fatigue, further diminishing performance, particularly in patients [52]. Pag. 32 Report The use of wrist flexion and extension for motor imagery tasks was selected as it involves fewer muscles, making it more suitable for untrained participants. While hand opening and closing are often used in MI-based BCI studies for their functional relevance, similar accuracy is achieved with wrist movements [64]. These design choices align with prior MI studies that have highlighted the importance of simplicity and repeatability in task selection for achieving reliable neural patterns. Additionally, resting-state data was recorded on separate days to capture the participant's baseline neural activity. This phase consisted of six sessions, with each session comprising 10 minutes of recording divided equally into 5 minutes with eyes open and 5 minutes with eyes closed. The final dataset, therefore, consisted of structured data from 10 days of motor imagery tasks and 6 sessions of resting-state recordings. This multi-day, multi-condition approach had the intention to provide a robust dataset for analysis, enabling the differentiation of task-specific neural patterns from baseline activity and accounting for potential day-to-day variability in brain activity. Such a dataset should ensure reliability in detecting subtle changes in neural activity while supporting the development of accurate and generalizable BCI systems. 4.4.1. Software The BitBrain Hero helmet supports integration with various BCI applications beyond its default suite, thanks to its available APIs (e.g., Python, C++, and other interfaces) for data access and processing. For the purpose of developing a motor imagery (MI) experiment, it was necessary to design an experimental protocol that could generate MI triggers (left and right) and ensure their synchronization with EEG data. PsychoPy was employed to create this protocol, providing precise timing and alignment between the presented stimuli and the recorded neural signals. Fig 7. Wrist flexion and extension [65] Generation of real-time control commands from EEG signals Pag. 33 4.4.1.1. PsychoPy To administer the experimental tasks, a custom experimental pipeline was developed within PsychoPy (see section 3.7), enabling the design of a motor imagery experiment based on the guidelines outlined in point 4.4. The structure shown in Fig. 8 was implemented to organize the task sequence. Fig 8. PsychoPy pipeline followed to obtain EEG MI data in this project. Pipeline Explanation 1. LSL Definition: The initial stage establishes the connection between the EEG recording software and the PsychoPy tool via the Lab Streaming Layer (LSL). During this step, the LabRecorder [61] software is used to synchronize the data streams (see section 3.6). 2. Pause: After confirming the connection, participants are prompted to press the "space" key to proceed to the next stage. This ensures that the participant is ready before the task begins (see Fig. 9.A). 3. Presentation: At this stage, participants are presented with the instructions for the task. The following message is displayed on the screen: "Welcome. Please think of moving the hand indicated by the blue arrows that will appear." This step ensures participants understand the task before proceeding (see Fig. 9.B). 4. Fixation: A fixation cross is displayed on the screen for 10 seconds (see Fig. 9.C). This step serves to center the participant's attention and prepare them for the task. 5. Task Loop: Following the fixation phase, the main task is repeated 40 times in a loop. Depending on the specific exercise being conducted, the participants are shown a blue arrow pointing either to the left, the right, or in a randomized direction (see Fig. 9.D and Fig 9.E). Participants are instructed to imagine Pag. 34 Report extending their hand in the direction indicated by the arrow. This process is performed through a 2.5 second time. The inclusion of three different types of tasks—left-hand movement, right-hand movement, and random direction— provides diverse neural data for analysis. (see Fig 10.C and 10.D) 6. Closure: At the end of the task, a message is displayed on the screen: "Thank you for your time." This message signals the conclusion of the experiment and formally ending the task. Fig 9. Images that can appear on the task from the PsychoPy pipeline that has been followed. A B C D E F Generation of real-time control commands from EEG signals Pag. 35 In addition to the task pipeline described, the study included a baseline recording phase to account for the participant's "resting-state" neural activity (see Fig 11). This phase was conducted in two conditions: 5 minutes with eyes open and 5 minutes with eyes closed. During the eyes-open condition, the participant was instructed to focus on a fixation cross displayed on the screen, while in the eyes-closed condition, the participant was asked to relax without any visual stimuli. This baseline data was essential for preprocessing, as it facilitated the identification and removal of noise and artifacts inherent to the dry EEG helmet. By comparing task-related signals to these baseline recordings, the analysis aimed to isolate motor-related neural patterns with greater accuracy. B. Fixation routine C. Fixation-loop routine A. Presentation routine D. Trial routine E. Trial routine Fig 10. PsychoPy routine blocks Pag. 36 Report Fig 11. PsychoPy pipeline followed to obtain resting-state EEG data in this project This PsychoPy pipeline starts as the other one, the only differences are related with the following points: 1. Presentation: At this stage, participants are presented with the instructions for the task. The following message is displayed on the screen: "Welcome, please stand still and relax. When 'EO' appears on the screen, keep looking at it. When it changes to 'EC,' close your eyes and wait until the end of the test to open them again. Thank you." This step ensures participants understand the task before proceeding (see Fig. 12.A). 2. Fixation_EO: A fixation cross will appear on the screen for 5 minutes (see Fig. 12.B). During this time, the participant is instructed to maintain focus on the cross until the next block appears. 3. Hold_Up: Participants are presented with instructions to close their eyes. The following message is displayed: "Now let's change to EC. You will wait here for 5 minutes. Please set your timer." Since the task was performed by a single subject without external monitoring, the participant was allowed time to set a 5-minute timer to know when to finish the eyes-closed block. (see Fig. 12.C). 4. Fixation_EC: A fixation cross will appear on the screen for 5 minutes (see Fig. 12.D). However, the participant will not see this image because their eyes should remain closed during this block. Generation of real-time control commands from EEG signals Pag. 37 Fig 12. Images that can appear on the task from the PsychoPy pipeline that has been followed for resting-state. A B C D 5 Pag. 38 Report Data acquisition was synchronized using the Lab Streaming Layer (LSL) protocol, ensuring precise timing and seamless integration between the EEG system and the PsychoPy tool. During each session, real-time monitoring was employed to ensure data quality, allowing for any necessary adjustments to maintain signal integrity and reduce noise. This approach guaranteed the reliability and accuracy of the recorded neural data, supporting subsequent analysis and interpretation. Fig 13. Bitbrain Viewer app main screen visualization This structured sequence was designed to ensure clarity, consistency, and robust data collection while optimizing the participant’s experience. Generation of real-time control commands from EEG signals Pag. 39 4.5. EEG Preprocessing The collected EEG data underwent comprehensive preprocessing to remove noise and artifacts, ensuring its suitability for subsequent analysis. These steps were implemented using Python, a versatile and widely-used programming language renowned for its robust libraries and tools in data analysis, signal processing, and scientific computing. The codes used in order to follow this pipeline can be found on the Github repository [66]. Below are the various steps followed to preprocess the data: 1. Data Loading and Integration: EEG data streams were loaded from .xdf files using the pyxdf library, ensuring synchronization with event markers provided by the Lab Streaming Layer (LSL). Each stream's sampling rate, channel count, and data shape were logged to verify integrity. 2. Baseline Correction: A 10-second baseline signal was calculated from the initial samples of the EEG data (in on-line mode). The average baseline value was subtracted from the entire dataset to correct for baseline shifts and minimize lowfrequency drifts (in offline mode). 3. Band-Pass and Notch Filtering: A band-pass filter (0.3–30 Hz) was applied to retain neural activity within the frequency range relevant to motor imagery [50]. Additionally, a notch filter was used to eliminate 50 Hz line noise caused by electrical interference. 4. Independent Component Analysis (ICA): Fast Independent Component Analysis (FastICA) was performed on the EEG data to isolate and remove artifacts, such as eye blinks or muscle movements. FastICA was specifically chosen for this preprocessing step due to its suitability for real-time applications, allowing artifact removal to be performed online. This ensured that task-related neural signals were preserved and not contaminated by extraneous noise, while enabling efficient preprocessing in dynamic experimental setups. 5. Event Identification and Segmentation: Event markers embedded in the data streams were identified and matched to the corresponding experimental conditions. EEG data was segmented into 1.5-second epochs based on these markers, aligning the neural data with the motor imagery tasks (e.g., left-hand, right-hand, or random trials). 6. Uniform Length Adjustment: To ensure consistency in data dimensionality, all 1.5-second epochs were either truncated or zero-padded to maintain a fixed number of samples across trials. Pag. 40 Report 7. Data Storage: Processed data and event labels were saved in .json files for further analysis. Additionally, filtered raw data and ICA-filtered data were saved in .fif files for reproducibility and compatibility with MNE-based pipelines. 4.6. Feature extraction Feature extraction plays a critical role in identifying and isolating patterns within EEG data that correlate with motor imagery tasks. This process is essential for the success of EEG motor imagery classification and was carried out using two complementary strategies: Literature-Based Features and Common Spatial Patterns (CSP). Both methods aimed to enhance the discriminative power of the data, providing robust representations for subsequent classification tasks. Below is an explanation of each approach. 4.6.1. Literature based features Features commonly reported in EEG studies were extracted to capture both time-domain and frequency-domain properties of the signals [43,44,45,46,47,48]: 1. Time-Domain Features  Root Mean Square (RMS): This feature evaluates the overall strength of the EEG signal and is commonly used in motor imagery research.  Peak-to-Peak Amplitude (PTP): Measures the variability in signal amplitude, providing insights into the dynamic range of neural activity. 2. Frequency-Domain Features  Power Spectral Density (PSD): The PSD was calculated for key frequency bands (delta, theta, alpha, beta, gamma) to isolate motor imagery-related oscillations. 3. Entropy and Complexity Measures  Sample Entropy: Quantifies the irregularity in neural signals, which may indicate the complexity of cognitive processing.  Lempel-Ziv Complexity: Measures randomness in EEG data, reflecting neural processing efficiency. Generation of real-time control commands from EEG signals Pag. 41 4.6.2. Common Spatial Patterns CSP is a popular method for extracting discriminative spatial features from EEG signals, specifically designed for motor imagery classification [48, 49, 50]. The technique optimizes spatial filters to enhance the variance of one class (e.g., left-hand imagery) while suppressing the variance of the other class (e.g., right-hand imagery). Key aspects include:  Variance Optimization: CSP maximizes variance for one class while minimizing it for the other.  Spatial Pattern Identification: It highlights patterns most relevant for classification.  Regularization: Variants like Regularized CSP (R-CSP) mitigate overfitting by introducing constraints in high-dimensional datasets. CSP calculation was performed through a Python code that follows the next pipeline: 1. Preprocessing: Applies ICA, baseline correction, and filtering. 2. Event Segmentation: Splits the EEG data into 1.5-second segments based on event markers. 3. CSP Training and Transformation: o Computes spatial filters. o Applies these filters to the segmented data to extract CSP features. 4. Saving Results: Stores CSP features and corresponding labels for machine learning classification. 4.6.3. Summary of Feature Extraction Implementation The features were extracted using a Python-based implementation, designed to support both online and offline workflows. This dual-mode approach ensures compatibility with real-time experimental setups and post hoc analyses, leveraging the following steps: 1. Data Acquisition: EEG signals were streamed live via LSL for real-time processing or retrieved from pre-recorded .fif files for offline analyses. 2. Baseline Subtraction: A baseline correction step was performed to normalize the EEG data and mitigate low-frequency drifts. 3. Filtering: Band-pass and notch filters were applied to retain task-relevant Pag. 48 Report  Alpha and Beta Power: The frequency features (Alpha and Beta power) exhibit highly skewed distributions with significant outliers. However, both histograms and box plots reveal that these features are concentrated near the lower range, showing minimal differentiation between motor imagery classes in the observed data (see Figures 16 and 17). right left side left right side Fig 16. Histogram and Box plot of alpha power by side (in z-scores) Fig 17. Histogram and Box plot of beta power by side (in z-scores) (Hz) (Hz) Generation of real-time control commands from EEG signals Pag. 49  Entropy Features: Sample entropy and permutation entropy show more symmetrical distributions. Box plots reveal minor variations in medians between "left" and "right" classes. Permutation entropy, in particular, appears to have slightly more distinguishable distributions between the two classes (see Figures 18 and 19). The statistical and visual analyses of these features suggest that while some features (e.g., RMS, PTP, and entropy measures) provide moderate separability, others (e.g., Alpha and Beta power) show considerable overlap, indicating limited discriminative power for motor imagery classification in their current form. side right left side right left Fig 18. Histogram and Box plot of sample entropy by side (in z-scores) Fig 19. Histogram and Box plot of permutation entropy by side (in z-scores) (Hz) (Hz) Pag. 50 Report 5.1.3. Classification Results Machine learning classifiers were evaluated to analyse the discriminative power of extracted features in the context of motor imagery tasks. The analysis included both training and validation phases, utilizing classifiers such as Linear Discriminant Analysis (LDA), Support Vector Machines (SVM), Decision Trees (DT), and K-Nearest Neighbours (KNN). Evaluation metrics, including accuracy, precision, recall, and ROC AUC, were calculated, alongside visualizations like ROC curves, confusion matrices, and classification reports. Training Phase Results The performance of machine learning classifiers was evaluated on the training dataset to assess their ability to learn patterns from the data. This analysis provides insights into how well each model captures the relationships between features and motor imagery tasks, with metrics such as accuracy, precision, recall, and ROC AUC serving as indicators of training performance. The following table summarizes the results of the machine learning classifiers on the training dataset (Table 3). The training performance metrics are also visualized in Figure 20 (top panel), showing a bar plot comparison of accuracy, precision, recall, and ROC AUC for each model. Additionally, the corresponding training ROC curves for the classifiers are illustrated in Figure 21 (top panel). Table 3. Machine Learning Classifiers on training dataset for Literature based features Classifier Accuracy (%) Precision (%) Recall (%) ROC AUC LDA 60.2 58.9 46.2 0.62 SVM 76.1 75.2 72.1 0.82 DT 85.2 84.1 83.8 0.85 KNN 75.0 74.1 70.9 0.82 Validation Phase Results To evaluate the generalization performance of the classifiers, their accuracy, precision, recall, and ROC AUC were assessed on the validation/test dataset. This step ensures that the models are not overfitting to the training data and provides a realistic assessment of their predictive capabilities on unseen data. Generation of real-time control commands from EEG signals Pag. 51 The following table presents the performance of the classifiers on the validation/test dataset (Table 4). Validation performance metrics are visualized in Figure 20 (bottom panel), providing a bar plot comparison of accuracy, precision, recall, and ROC AUC for the models. The validation ROC curves are depicted in Figure 21 (bottom panel) to further illustrate the generalization performance. Table 4. Machine Learning Classifiers on validation dataset for Literature based features Classifier Accuracy (%) Precision (%) Recall (%) ROC AUC LDA 50.0 50.0 100.0 0.50 SVM 50.0 50.0 100.0 0.50 DT 50.0 50.0 100.0 0.50 KNN 51.0 50.7 80.4 0.50 Fig 20. Training vs Validation Metrics comparison for Literature Based features Pag. 52 Report Fig 21. Training vs Validation ROC Curves comparison for Literature Based features Generation of real-time control commands from EEG signals Pag. 53 5.2. Common Spatial Patterns (CSP) 5.2.1. Data Overview The EEG data analysed using Common Spatial Patterns (CSP) were acquired during motor imagery (MI) tasks involving rightand left-hand movements. The data were recorded over ten sessions, with 40 trials per class per session. This resulted in a dataset comprising balanced class distributions of 400 trials each for right-hand and left-hand motor imagery. The CSP features were extracted by applying spatial filters optimized to maximize the variance differences between the two classes. The dataset was divided into:  Training Set: 651 trials (60% of the total data), balanced across classes.  Validation Set: 240 trials (40% of the total data), balanced across classes. 5.2.2. Feature Extraction and Analysis Features Distribution The CSP method transformed the EEG data into a four-dimensional feature space, with each dimension representing a spatial filter optimized for class discrimination. The distributions of these features for the training and validation sets were analyzed and visualized. CSP Training Features Figure 22 displays the class distribution in the training dataset. The two classes, corresponding to motor imagery of rightand left-hand movements, are balanced with nearly equal representation in the dataset. Fig 22. Class Distribution in Training Data Pag. 54 Report Figure 23 illustrates the distributions of the four CSP components extracted from the training dataset. Each component corresponds to a spatial filter optimized for discriminating between the two motor imagery classes. These histograms show that the CSP features are well-distributed, with distinct separability between the classes for certain components. Comparison of Training and Validation CSP Features To evaluate whether the CSP features generalize across datasets, Figure 24 compares the density distributions of CSP components in the training and validation datasets. Fig 23. Training CSP Feature Distribution Fig 24. Comparison of CSP Feature Distributions (Training vs. Validation) Generation of real-time control commands from EEG signals Pag. 55 5.2.3. Classification Results The classification performance of the CSP features was evaluated using four models: Linear Discriminant Analysis (LDA), Support Vector Machine (SVM), Decision Tree (DT), and K-Nearest Neighbours (KNN). The results for both training and validation phases are summarized below. Training Phase Results The performance of machine learning classifiers was evaluated on the training dataset to assess their ability to learn patterns from the data. This analysis provides insights into how well each model captures the relationships between features and motor imagery tasks, with metrics such as accuracy, precision, recall, and ROC AUC serving as indicators of training performance. The following table summarizes the results of the machine learning classifiers on the training dataset (Table 5). The training performance metrics are also visualized in Figure 25 (top panel), showing a bar plot comparison of accuracy, precision, recall, and ROC AUC for each model. Additionally, the corresponding training ROC curves for the classifiers are illustrated in Figure 26 (top panel). Table 5. Machine Learning Classifiers on training dataset for CSP features Classifier Accuracy (%) Precision (%) Recall (%) ROC AUC LDA 92.4 94.3 93.7 0.95 SVM 90.6 92.1 92.8 0.93 DT 89.3 91.8 92.4 0.91 KNN 88.1 90.2 89.1 0.89 Validation Phase Results To evaluate the generalization performance of the classifiers, their accuracy, precision, recall, and ROC AUC were assessed on the validation/test dataset. This step ensures that the models are not overfitting to the training data and provides a realistic assessment of their predictive capabilities on unseen data. The following table presents the performance of the classifiers on the validation/test dataset (Table 6). Validation performance metrics are visualized in Figure 25 (bottom panel), providing a bar plot comparison of accuracy, precision, recall, and ROC AUC for the models. The validation ROC curves are depicted in Figure 26 (bottom panel) to further illustrate the generalization performance. Pag. 56 Report Table 6. Machine Learning Classifiers on validation dataset for CSP features Classifier Accuracy (%) Precision (%) Recall (%) ROC AUC LDA 38.8 43.4 74.2 0.18 SVM 28.8 31.9 37.5 0.22 DT 42.9 43.5 47.5 0.43 KNN 34.6 39.4 57.5 0.36 Fig 25. Training vs Validation Metrics comparison for CSP Features Generation of real-time control commands from EEG signals Pag. 57 Fig 26. Training vs Validation ROC Curves comparison for CSP features Pag. 64 Report 9. Environmental impact analysis The environmental impact of developing this project has been evaluated, considering the resources and equipment utilized. In addition, the manufacturing of these devices contributes significantly to their carbon footprint. For example, the production of electronic devices releases approximately 22.7 kg of CO2 per kilogram of equipment. Laptops, which typically weigh around 2 kg, have an estimated manufacturing footprint of 110 kg CO2e. While these figures are substantial, it is important to note that the equipment used in this project was not acquired specifically for this purpose, thereby reducing its direct environmental impact on the project. A key environmental benefit of this project is the use of the Bitbrain Hero Helmet, which employs dry electrodes instead of disposable adhesive ones. This eliminates the need for single-use electrodes, significantly reducing waste typically associated with EEG data acquisition. In projects using adhesive electrodes, hundreds of units may be disposed of, contributing to environmental degradation. The use of dry electrodes thus represents a more sustainable and eco-friendly approach. Additionally, while the carbon footprint of manufacturing the devices involved in this project must be acknowledged—estimated at approximately 1 ton of CO2 for 1000€ worth of technology—the devices were not acquired solely for this project, which mitigates their direct environmental impact. Lastly, all transportation related to this project prioritized public transport, avoiding private vehicle use and minimizing travel-related carbon emissions. Generation of real-time control commands from EEG signals Pag. 65 10. Economic analysis A description of the budget spent on this study, involving personal, software, material and office-related costs is detailed below. Table 7. Personal costs of the study Table 8. Software costs Table 9. Material costs Table 10. Office related costs Pag. 66 Report 11. CONCLUSIONS This project explored the feasibility of developing a Brain-Computer Interface (BCI) system using a dry EEG helmet to classify motor imagery (MI) tasks. The results highlight both the potential and limitations of such systems. The classification performance differed depending on the approach used. For literature-based features, the K-Nearest Neighbors (KNN) algorithm achieved a validation accuracy of 51.0%. However, the confusion matrices indicated significant limitations, as the model predominantly predicted a single class, reducing its practical discriminative ability. On the other hand, applying Common Spatial Patterns (CSP) features with a Decision Tree classifier showed some improvement, achieving a validation accuracy of 42.9%. While this approach demonstrated better balance in predictions, it still faced challenges related to generalization and overfitting. The use of a dry EEG system introduced notable obstacles. Signal quality was compromised due to the sensitivity of dry electrodes to noise and artifacts, which affected the reliability of feature extraction and classification. Furthermore, variability in EEG signals across sessions and even within the same day posed additional challenges. This variability, influenced by factors such as electrode placement and participant state, highlighted the importance of robust calibration protocols to ensure consistency. Although the project included functional code for real-time testing, the low accuracies achieved by the trained models limited their practical application. As a result, online tests were not extensively conducted, as they did not offer meaningful insights. Despite these limitations, this work provides a foundation for future advancements in BCI systems. Integrating more advanced EEG technologies, improved feature extraction methods, and robust machine learning techniques could significantly enhance system reliability and adaptability, paving the way for more practical and impactful applications in assistive technologies. Generation of real-time control commands from EEG signals Pag. 67 12. Acknowledgments I would like to express my deepest gratitude to the individuals who have been crucial in the successful completion of this project. First, a huge thanks to my master’s project Director, Joan Francesc Alonso López, for sharing his expertise, offering his support, and always guiding me in the right direction. His help has been crucial in shaping this work. I also want to deeply thank my Co-director, Andres El-Fakdi Sencianes, for his dedication, encouragement, and constant motivation. His support kept me going, even when things got tough, and his guidance made a huge difference in reaching our goals. A big thank you as well to my Co-director, Alicia Casals Gelpí, and the rest of the robotics team, for their guidance and for giving me the tools and facilities to make this project happen. Lastly, I’m grateful to my partner, my family, and my closest friends. Your love, support, and encouragement were exactly what I needed whenever things felt overwhelming. Their presence and understanding have been a source of strength during challenging times, and I am grateful for their love and belief in me. Pag. 68 Report 13. Bibliography [1] https://www.bitbrain.com/es/productos-neurotecnologia/dry-eeg/hero [2] R. Sharma, M. Kim, and A. Gupta, “Motor imagery classification in brain-machine interface with machine learning algorithms: Classical approach to multi-layer perceptron model,” *Biomed. Signal Process. Control*, vol. 71, p. 103101, 2022, doi: 10.1016/j.bspc.2021.103101. [3] H.-J. Hwang, J.-H. Lim, Y.-J. Jung, H. Choi, S.-W. Lee, and C.-H. Im, “Development of an SSVEP-based BCI spelling system adopting a QWERTY-style LED keyboard,” J. Neurosci. Methods, vol. 208, no. 1, pp. 59–65, Apr. 2012, doi: 10.1016/j.jneumeth.2012.04.011. [4] A. C. Lopes, G. Pires, and U. Nunes, “Assisted navigation for a brain-actuated intelligent wheelchair,” Rob. Auton. Syst., vol. 61, no. 3, pp. 245–258, Mar. 2013, doi: 10.1016/j.robot.2012.11.002. [5] T. Carlson and J. R. Millán, “Brain-controlled wheelchairs: a robotic architecture,” IEEE Rob. Autom. Mag., vol. 20, no. 1, pp. 65–73, Mar. 2013, doi: 10.1109/MRA.2012.2229936. [6] J. L. Collinger, B. Wodlinger, J. E. Downey, W. Wang, E. C. Tyler-Kabara, D. J. Weber, et al., “High performance neuroprosthetic control by an individual with tetraplegia,” Lancet, vol. 381, no. 9866, pp. 557–564, Feb. 2013, doi: 10.1016/S0140-6736(12)61816-9. [7] G. Huang, Z. Zhao, S. Zhang, Z. Hu, J. Fan, M. Fu, J. Chen, Y. Xiao, J. Wang, and G. Dan, “Discrepancy between interand intra-subject variability in EEG-based motor imagery brain-computer interface: Evidence from multiple perspectives,” Front. Neurosci., vol. 17, p. 1122661, 2023, doi: 10.3389/fnins.2023.1122661. [8] J. Ma, B. Yang, W. Qiu, Y. Li, S. Gao, and X. Xia, “A large EEG dataset for studying cross-session variability in motor imagery brain-computer interface,” Sci. Data, vol. 9, no. 1, 2022, doi: 10.1038/s41597-022-01647-1 [9] A. Piszcz, I. Rojek, and D. Mikołajewski, “Impact of Virtual Reality on Brain– Computer Interface Performance in IoT Control—Review of Current State of Knowledge,” Appl. Sci., vol. 14, no. 22, p. 10541, 2024, doi: 10.3390/app142210541. [10] A. Palumbo, V. Gramigna, B. Calabrese, and N. Ielpo, “Motor-Imagery EEG-Based BCIs in Wheelchair Movement and Control: A Systematic Literature Review,” Sensors, vol. 21, no. 18, p. 6285, Sep. 2021, doi: 10.3390/s21186285. Generation of real-time control commands from EEG signals Pag. 69 [11] T. O. Zander, M. Lehne, K. Ihme, S. Jatzev, J. Correia, C. Kothe, B. Picht, and F. Nijboer, “A dry EEG-system for scientific research and brain-computer interfaces,” Front. Neurosci., vol. 5, p. 53, May 2011, doi: 10.3389/fnins.2011.00053. [12] T. O. Zander, L. M. Andreessen, A. Berg, M. Bleuel, J. Pawlitzki, L. Zawallich, L. R. Krol, and K. Gramann, “Evaluation of a dry EEG system for application of passive brain-computer interfaces in autonomous driving,” Front. Hum. Neurosci., vol. 11, p. 78, 2017, doi: 10.3389/fnhum.2017.00078. [13] C. Guger, G. Krausz, and G. Edlinger, “Brain-computer interface control with dry EEG electrodes,” 2011. [14] M. Spüler, “A high-speed brain-computer interface (BCI) using dry EEG electrodes,” PLoS ONE, vol. 12, no. 2, p. e0172400, 2017, doi: 10.1371/journal.pone.0172400. [15] H. Hinrichs, M. Scholz, A. K. Baum, J. W. Y. Kam, R. T. Knight, and H. Heinze, “Comparison between a wireless dry electrode EEG system with a conventional wired wet electrode EEG system for clinical applications,” Sci. Rep., vol. 10, no. 1, 2020, doi: 10.1038/s41598-020-62154-0. [16] Chaudhuri, P. K. R., & Ondo, W. (2010). “Movement disorders in clinical practice. Springer”. https://books.google.es/books?id=bW8sPxMAG3AC [17] M. N. Hatch, T. R. Cushing, G. D. Carlson, and E. Y. Chang, “Neuropathic pain and SCI: Identification and treatment strategies in the 21st century,” J. Neurol. Sci., vol. 384, pp. 75–83, Jan. 2018, doi: 10.1016/j.jns.2017.11.018. [18] R. Shiao and C. A. Lee-Kubli, “Neuropathic Pain After Spinal Cord Injury: Challenges and Research Perspectives,” Neurotherapeutics, vol. 15, no. 3, pp. 635– 653, Jul. 2018, doi: 10.1007/s13311-018-0633-4. [19] E. M. Hagen and T. Rekand, “Management of Neuropathic Pain Associated with Spinal Cord Injury,” Pain Ther., vol. 4, no. 1, pp. 51–65, Jun. 2015, doi: 10.1007/s40122-015-0033-y. [20] G. A. Light, L. E. Williams, F. Minow, J. Sprock, A. Rissling, R. Sharp, N. R. Swerdlow, and D. L. Braff, “Electroencephalography (EEG) and event-related potentials (ERPs) with human participants,” Curr. Protoc. Neurosci., vol. Chapter 6, pp. Unit 6.25.1–24, Jul. 2010, doi: 10.1002/0471142301.ns0625s52. PMID: 20578033; PMCID: PMC2909037. [21] A. Rayi and N. I. Murr, "Electroencephalogram," in StatPearls [Internet], Treasure Island (FL): StatPearls Publishing, 2024 Jan–. Available from: https://www.ncbi.nlm.nih.gov/books/NBK563295/. Pag. 70 Report [22] L. F. Haas, “Hans Berger (1873–1941), Richard Caton (1842–1926), and electroencephalography,” J. Neurol. Neurosurg. Psychiatry, vol. 74, no. 1, p. 9, Jan. 2003, doi: 10.1136/jnnp.74.1.9. PMID: 12486257; PMCID: PMC1738204. [23] M. Tudor, L. Tudor, and K. I. Tudor, “Hans Berger (1873–1941)–povijest elektroencefalografije [Hans Berger (1873–1941)–the history of electroencephalography],” Acta Med Croatica, vol. 59, no. 4, pp. 307–313, 2005. Croatian. PMID: 16334737. [24] M. Roohi-Azizi, L. Azimi, S. Heysieattalab, and M. Aamidfar, “Changes of the brain’s bioelectrical activity in cognition, consciousness, and some mental disorders,” Med. J.Islam. Repub. Iran, vol. 31, no. 1, p. 53, 2017. [25] P. Campisi, D. La Rocca, and G. Scarano, “EEG for automatic person recognition,” Computer (Long. Beach. Calif)., vol. 45, no. 7, pp. 87–89, 2012. [26] R. Lesser and T. W. Picton, “American Electroencephalographic Society Guidelines for Standard Electrode Position Nomenclature1,” J. Clin. Neurophysiol., vol. 8, no. 2, pp. 200–202, 1991. [27] N. Foldvary-Schaefer and M. M. Grigg-Damberger, “Identifying interictal and ictal epileptic activity in polysomnograms,” Sleep Med. Clin., vol. 7, no. 1, pp. 39–58, 2012. [28] G. Reynolds and J. Richards, “Cortical source localization of infant cognition,” Dev. Neuropsychol., vol. 34, no. 3, pp. 312–329, 2009. [29] N. Triana-Guzman, A. D. Orjuela-Cañon, A. L. Jutinico, O. Mendoza-Montoya, and J. M. Antelis, “Decoding EEG rhythms offline and online during motor imagery for standing and sitting based on a brain-computer interface,” Front. Neuroinform., vol. 16, 2022, doi: 10.3389/fninf.2022.961089. [30] F. Lotte and C. Guan, “Regularizing common spatial patterns to improve BCI designs: unified theory and new algorithms,” IEEE Trans. Biomed. Eng., vol. 58, pp. 355–362, 2011, doi: 10.1109/TBME.2010.2082539. [31] M. H. Lee, O. Y. Kwon, Y. J. Kim, H. K. Kim, Y. E. Lee, J. Williamson, et al., “EEG dataset and OpenBMI toolbox for three BCI paradigms: an investigation into BCI illiteracy,” Gigascience, vol. 8, pp. 1–16, 2019, doi: 10.1093/gigascience/giz002. [32] E. V. Bobrova, V. V. Reshetnikova, A. A. Frolov, and Y. P. Gerasimenko, “Use of imaginary lower limb movements to control brain-computer interface systems,” Neurosci. Behav. Physiol., vol. 50, pp. 585–592, 2020, doi: 10.1007/s11055-02000940-z. Generation of real-time control commands from EEG signals Pag. 71 [33] V. Asanza, E. Peláez, F. Loayza, L. L. Lorente-Leyva, and D. H. Peluffo-Ordóñez, “Identification of lower-limb motor tasks via brain-computer interfaces: a topical overview,” Sensors, vol. 22, pp. 1–24, 2022, doi: 10.3390/s22052028. [34] M. Rodríguez-Ugarte, E. Iáñez, M. Ortíz, and J. M. Azorín, “Personalized offline and pseudo-online BCI models to detect pedaling intent,” Front. Neuroinform., vol. 11, p. 45, 2017, doi: 10.3389/fninf.2017.00045. [35] A. Mora-Cortes, N. Manyakov, N. Chumerin, and M. Van Hulle, “Language model applications to spelling with brain-computer interfaces,” Sensors (Basel), vol. 14, no. 4, pp. 5967–5993, 2014. [36] J. J. Shih, D. J. Krusienski, and J. R. Wolpaw, “Brain-computer interfaces in medicine,” Mayo Clin. Proc., vol. 87, no. 3, pp. 268–279, 2012. [37] E. M. Smith, M. L. Toro Hernandez, I. D. Ebuenyi, *et al.*, “Assistive technology use and provision during COVID-19: results from a rapid global survey,” *Int. J. Health Policy Manag.*, vol. 11, no. 6, pp. 747–756, 2022, doi: 10.34172/ijhpm.2020.210. [38] Ceradini, M., Lassi, M., Losanno, E., et al. (2023). Feasibility and Accuracy of a Dry and Wireless EEG Helmet for Upper Limb Motor Imagery-Based Brain-Computer Interfaces. IEEE International Conference on Metrology for eXtended Reality, Artificial Intelligence, and Neural Engineering (MetroXRAINE). https://doi.org/10.1109/METROXRAINE58569.2023.1040554​:contentRefere nce[oaicite:2]{index=2}. [39] Altaheri, H., Muhammad, G., Alsulaiman, M., et al. (2023). Deep learning techniques for classification of electroencephalogram (EEG) motor imagery (MI) signals: A review. Neural Computing and Applications, 35, 14681–14722. https://doi.org/10.1007/s00521-021-063525​:contentReference[oaicite:3]{index=3}. [40] Palumbo, A., Gramigna, V., Calabrese, B., & Ielpo, N. (2021). Motor-Imagery EEGBased BCIs in Wheelchair Movement and Control: A Systematic Literature Review. Sensors, 21(18), 6285. https://doi.org/10.3390/s21186285​:contentReference[oaicite:1]{index=1}. [41] W. Huang, X. Liu, W. Yang, Y. Li, Q. Sun, and X. Kong, “Motor Imagery EEG Signal Classification Using Distinctive Feature Fusion with Adaptive Structural LASSO,” Sensors (Basel), vol. 24, no. 12, p. 3755, Jun. 2024, doi: 10.3390/s24123755. PMID: 38931540; PMCID: PMC11207242. [42] X. Wang, X. Dai, Y. Liu, X. Chen, Q. Hu, R. Hu, and M. Li, “Motor imagery electroencephalogram classification algorithm based on joint features in the spatial Pag. 72 Report and frequency domains and instance transfer,” Front. Hum. Neurosci., vol. 17, 2023, doi: 10.3389/fnhum.2023.1175399. [43] N. K. Al-Qazzaz, Z. A. A. Alyasseri, K. H. Abdulkareem, N. S. Ali, M. N. Al-Mhiqani, and C. Guger, "EEG feature fusion for motor imagery: A new robust framework towards stroke patients rehabilitation," Computers in Biology and Medicine, vol. 137, 2021, doi: 10.1016/j.compbiomed.2021.104799. [44] W. Yi, S. Qiu, H. Qi, L. Zhang, B. Wan, and D. Ming, "EEG feature comparison and classification of simple and compound limb motor imagery," Journal of NeuroEngineering and Rehabilitation, vol. 10, no. 106, 2013, doi: 10.1186/17430003-10-106. [45] X. Geng, D. Li, H. Chen, P. Yu, H. Yan, and M. Yue, "An improved feature extraction algorithm of EEG signals based on motor imagery brain-computer interface," Alexandria Engineering Journal, vol. 61, no. 11, pp. 4807–4820, 2022, doi: 10.1016/j.aej.2021.10.034. [46] X. Zhao, D. Liu, L. Ma, Q. Liu, K. Chen, S. Xie, and Q. Ai, "Deep CNN model based on serial-parallel structure optimization for four-class motor imagery EEG classification," Biomedical Signal Processing and Control, vol. 72, 2022, doi: 10.1016/j.bspc.2021.103338. [47] W. Huang, X. Liu, W. Yang, Y. Li, Q. Sun, and X. Kong, "Motor Imagery EEG Signal Classification Using Distinctive Feature Fusion with Adaptive Structural LASSO," Sensors (Basel), vol. 24, no. 12, p. 3755, Jun. 2024, doi: 10.3390/s24123755. PMID: 38931540; PMCID: PMC11207242. [48] X. Wang, X. Dai, Y. Liu, X. Chen, Q. Hu, R. Hu, and M. Li, "Motor imagery electroencephalogram classification algorithm based on joint features in the spatial and frequency domains and instance transfer," Frontiers in Human Neuroscience, vol. 17, 2023, doi: 10.3389/fnhum.2023.1175399. [49] Y. Wang, X. Gao, S. Gao, & Z. Kuang, “Common Spatial Pattern Method for Channel Selection in Motor Imagery Based Brain-Computer Interface,” Proc. IEEE Eng. Med. Biol. Soc. Conf., pp. 5392–5395, 2005. doi: 10.1109/IEMBS.2005.1615701. [50] S. Omari, A. Omari, & M. Abderrahim, “Multiple tangent space projection for motor imagery EEG classification,” Appl. Intell., vol. 53, pp. 21192–21200, 2023. doi: 10.1007/s10489-023-04551-2. [51] M. R. Nuwer, “10-10 electrode system for EEG recording,” Clin. Neurophysiol., vol. 129, no. 5, p. 1103, May 2018. Generation of real-time control commands from EEG signals Pag. 73 [52] S. Park, J. Ha, D. H. Kim, and L. Kim, “Improving Motor Imagery-Based BrainComputer Interface Performance Based on Sensory Stimulation Training: An Approach Focused on Poorly Performing Users,” Front. Neurosci., vol. 15, no. November, pp. 1–12, 2021. [53] N. Padfield, J. Zabalza, H. Zhao, V. Masero, and J. Ren, “EEG-based braincomputer interfaces using motor-imagery: Techniques and challenges,” Sensors (Switzerland), vol. 19, no. 6, pp. 1–34, 2019. [54] A. Saibene, M. Caglioni, S. Corchs, & F. Gasparini, “EEG-Based BCIs on Motor Imagery Paradigm Using Wearable Technologies: A Systematic Review,” Sensors, vol. 23, no. 5, p. 2798, Mar. 2023. doi: 10.3390/s23052798. PMID: 36905004; PMCID: PMC10007053. [55] C. Kothe, S. Y. Shirazi, T. Stenner, D. Medine, C. Boulay, M. I. Grivich, T. Mullen, A. Delorme, and S. Makeig, “The Lab Streaming Layer (LSL): A software system for multimodal real-time data acquisition, synchronization, and storage in neuroscience applications,” bioRxiv, 2024. doi: 10.1101/2024.02.13.580071. [56] https://labstreaminglayer.readthedocs.io/info/user_guide.html [57] https://www.psychopy.org/ [58] J. W. Peirce, “PsychoPy—Psychophysics software in Python,” J. Neurosci. Methods, vol. 162, no. 1–2, pp. 8–13, 2007, doi: 10.1016/j.jneumeth.2006.11.017. [59] S. Pattnaik, M. Dash, and S. K. Sabut, “DWT-based feature extraction and classification for motor imaginary EEG signals,” 2016 Int. Conf. Syst. Med. Biol. ICSMB 2016, no. January, pp. 186–201, 2017. [60] P. Rithwik, V. K. Benzy, and A. P. Vinod, “High accuracy decoding of motor imagery directions from EEG-based brain computer interface using filter bank spatially regularised common spatial pattern method,” Biomed. Signal Process. Control, vol.72, no. PA, p. 103241, 2022. [61] J. Kalcher, D. Flotzinger, C. Neuper, S. Gölly, and G. Pfurtscheller, “Graz braincomputer interface II: Towards communication between humans and computers based on online classification of three different EEG patterns,” Med. Biol. Eng. Comput., vol. 34, no. 5, pp. 382–388, 1996. [62] C. Brunner, R. Leeb, G. R. Müller-Putz, A. Schlögl, and G. Pfurtscheller, “BCI Competition 2008-Graz data set A Experimental paradigm.” [63] A. Suwannarat, S. Pan-ngum, and P. Israsena, “Comparison of EEG measurement