DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash...

149
1 POLITECNICO DI MILANO Scuola di Ingegneria Industriale e dell’Informazione Corso di Studio in Ingegneria Biomedica Dipartimento di Elettronica, Informazione e Bioingegneria DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A NEUROPROSTHESIS FOR THE PARETIC HAND Tesi di Laurea Magistrale Relatore: Prof. Carlo Albino Frigo Co-Relatore: Dr. Rune Thorsen, M.Sc.e.e. (Fondazione Don Carlo Gnocchi, IRCCS) Autore: Mattia Schiavone ANNO ACCADEMICO 2016/2017

Transcript of DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash...

Page 1: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

1

POLITECNICO DI MILANO Scuola di Ingegneria Industriale e dell’Informazione

Corso di Studio in Ingegneria Biomedica

Dipartimento di Elettronica, Informazione e Bioingegneria

DESIGN AND IMPLEMENTATION OF THE

FIRMWARE OF A NEUROPROSTHESIS FOR

THE PARETIC HAND

Tesi di Laurea Magistrale

Relatore: Prof. Carlo Albino Frigo

Co-Relatore: Dr. Rune Thorsen, M.Sc.e.e.

(Fondazione Don Carlo

Gnocchi, IRCCS)

Autore:

Mattia Schiavone

ANNO ACCADEMICO 2016/2017

Page 2: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

2

ACKNOWLEDGMENTS

This project has been developed at Fondazione Don Gnocchi Onlus (Centro IRCCS “S.

Maria Nascente”, Milano). I am deeply grateful to Dr. Rune Thorsen, M.Sc.e.e., who

guided me during this project, for his dedication and his enthusiasm. I thank also all the

other people working at Fondazione Don Gnocchi, who have been helpful. Finally, I want

to thank Prof. Carlo Albino Frigo for his suggestions and his helpfulness.

Page 3: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

3

INDEX

GLOSSARY 5

SUMMARY (ENGLISH) 6

SUMMARY (ITALIAN) 11

1. INTRODUCTION 17

1.1 OBJECTIVE OF THE PROJECT 17

1.2 FIELD OF APPLICATION 18

1.3 THE MUSCLE CONTRACTION 19

1.4 ARTIFICIAL CONTRACTION: FES 25

1.5 STATE OF THE ART: EXISTNG DEVICES 39

1.6 CHARACTERISTICS OF THE DEVELOPED SYSTEM 44

2. MATERIAL AND METHODS 47

2.1 CIRCUIT FEATURES 47

2.1.1 AD8232 - CONDITIONING 48

2.1.2 HVPS AND VCCS 53

2.2 MICROCONTROLLER, FUNCTIONS, METHODS 56

2.2.1 MICROCONTROLLER 56

2.2.2 FIXED-POINT ARITHMETIC 58

2.2.3 UART 61

2.2.4 SPI INITIALIZATION AND USE 61

2.2.5 TIMERS AND TIMERS INTERRUPTS 66

2.2.6 FLASH MEMORY 68

2.2.7 LED 70

2.2.8 BUTTON 72

2.3 FIRMWARE AND CYCLE 73

2.3.1 MAIN PROGRAM - CONFIGURATION 73

2.3.2 MAIN CYCLE 77

2.4 TESTS 95

2.4.1 OPERATION MODES 96

2.4.2 TEST SETUP AND ARTIFICIAL EMG 97

2.4.3 STIMULATION AND BATTERY CONSUMPTION 100

2.4.4 FAST RESTORE 101

2.4.5 COMB AND HIGH PASS FILTER 102

2.4.6 SOLID STATE RELAYS NOISE 102

2.4.7 PHYSIOTHERAPISTS SURVEY 103

Page 4: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

4

3. RESULTS 105

3.1 FAST RESTORE 107

3.2 STIMULATION AND CONTROL 108

3.3 MOVEMENT ARTEFACTS AND HP FILTER 113

3.4 FIR FILTER 115

3.5 OUTPUT ZENER DIODES 116

3.6 PHYSIOTHERAPISTS SURVEY RESULTS 117

4. DISCUSSION 119

4.1 PROS OF THE DEVICE 119

4.2 CONSIDERATIONS ON CONSUMPTION 123

4.3 CONDITIONING BLOCK DISCUSSION 124

4.4 FUTURE DEVELOPMENTS 126

4.4.1 FIRMWARE 126

4.4.2 CIRCUIT: BATTERY LEVEL 126

4.4.3 SUPPORT OF THE SYSTEM 128

4.5 CONSIDERATIONS ON THE SURVEY 129

APPENDIX A: ELECTRODES AND ELECTROMYOGRAPHY 131

APPENDIX B: COMMUNICATION INTERFACES (UART AND SPI) 137

APPENDIX C: MICROCONTROLLER SIGNALS TABLE 142

LITERATURE 145

Page 5: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

5

GLOSSARY

ADC: Analog To Digital Converter

DAC: Digital To Analog Converter

DMA: Direct Memory Access

EMG: Electromyography/Electromyogram

HP: High Pass

HVPS: High Voltage Power Supply

INA: Instrumentation Amplifier

LP: Low Pass

MeCFES: Myoelectrically Controlled Functional Electrical Stimulation

OpAmp: Operational Amplifier

RAM: Random Access Memory

SPI: Serial Peripheral Interface

UART: Universal Asynchronous Receiver/Transmitter

VCCS: Voltage Controlled Current Source

Page 6: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

6

SUMMARY (ENGLISH)

The purpose of the project is to develop and implement the firmware of a neuroprosthesis,

in order to recover the hand function. The system is addressed to neurological patients

with issues in hand movement. The device is based on functional electrical stimulation

(FES), which activates the paralysed muscles with an artificial excitation of the affected

motoneurons. Following a stroke or spinal injury, neurons located below the damaged

level (although they cannot be activated by brain activity) are not damaged and they can

be artificially stimulated. Several studies have demonstrated the effectiveness of this

treatment, both as a method of rehabilitation (in order to recover the motor function) and

as assistive method during the activities of daily life.

Stimulation is delivered through the passage of electric current (with the use of two

electrodes) which causes the depolarization of the neuron membrane and the creation of an

action potential. Since the current in the tissues is obtained by the movement of ions rather

than electrons, it is important to study the stimulation waveform, in order to avoid

damages to the tissue, resulting from net quantities of charges transferred inside them.

Another important aspect is the stimulation frequency: since the principle of recruitment of

muscle fibers is different in the cases of natural or artificial activation, in the latter case,

the muscle tissue is less resistant to fatigue and a high frequency may worsen this problem.

On the other hand, a minimum stimulation frequency is required to ensure a continuous

force output. In order to facilitate the use of the device, stimulation can be activated and

controlled by different biological signals (EEG, EMG) or artificial sensors (IMUs),

without having a fixed pattern.

Regarding the recovery of the hand grasp function, there are already some implantable and

external devices, including MeCFES (Myoelectrically Controlled Functional Electrical

Stimulator), used as a starting point for the development of this new device. MeCFES is

based on the tenodesis grasp principle: a wrist extension causes a mechanical fingers

flexion and the device amplifies this effect by stimulating the finger flexors when a

muscular activity of the wrist extensors is detected. In this way, the control of the

stimulation is intuitive and the amplitude of the current delivered is proportional to the

activity recorded.

Page 7: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

7

The developed device has many differences and advantages. The circuit has been reduced

in size, as well as the batteries (three AAA 1.5 V batteries are used). The device has two

input and two output channels and the firmware has been rewritten to fit the new

components and features. The most significant innovation is the ability of the system to

communicate (via Bluetooth) with an Android application installed on an external device

such as a smartphone or a tablet. This function allows the user to change the stimulation

parameters during the use and to display the acquired EMG signal. In this way, the device

can be adapted to different body segments and several movements, which may need other

parameters. The firmware structure is the following: an EMG signal acquisition part, a

digital signal processing part, a finite state machine to deliver the stimulation, and finally a

part to communicate with the external device.

Before the analog to digital conversion, operated by the ADC in the microcontroller

(ADuCM360), an analog conditioning of the acquired signal is performed, through the

AD8232 block. In this way, the signal (< 5 mV) is amplified and filtered by the

instrumentation amplifier (INA) and the OpAmp. The total gain of the block is 200 and the

bandwidth is between 7 Hz and 480 Hz, in order to meet the EMG signal bandwidth. The

stimulation is delivered through the circuitry that allows the generation of high voltage (up

to 294 V) starting from the low voltage input (from the batteries).

Bluetooth communication with smartphone/tablet is possible thanks to the Bluetooth

module WT12-A, which communicates with the microcontroller through a Universal

Asynchronous Receiver-Transmitter (UART) component. This method is also used to

program the module itself. Another communication system used within the device is SPI

(Serial Peripheral Interface), which transfers to the DAC the values referred to the

amplitude of the stimulation current and the high voltage to be developed for its delivery.

The DAC is contained in AD5592 that is made up of converters on eight different pins.

The transferred data consists of 16 bits: the four MSBs indicate the correct pin address,

while the remaining 12 bits represents the value to be transferred. For this reason, a control

that limits the transferred values up to 12 bits has been implemented. Due to this limit, the

highest transferable high voltage value is 294 V, while the amplitude of the current can

reach very high values (more than 100 mA).

Page 8: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

8

The microcontroller contains two timers, which are relevant to the application required by

the device. The timing of the various operations is very important, especially for the

delivery of the stimulation current. For both the output channels a biphasic square wave

must be generated and the duration of the two phases must be equal, in order to avoid

damage to the tissues. For this reason, the finite state machine used for stimulation is

called in the interrupt of Timer1, which happens every 300 μs. This value can be changed

but is optimal for the type of stimulation delivered. In addition, timer0 is used to count the

time passed since the device has been switched on and a variable is incremented during its

interrupt, which happens every 1 ms.

The microcontroller contains a 128 kB flash memory. Since the memory used to save the

program corresponds to few kB, we decided to use some memory space to save some

specific data, such as stimulation parameters. This allows the user to store the currently

used parameters (by pressing a button for a long time), without having to set them every

time the device is used. During the device turning on, the saved values are read and

inserted in the corresponding variables.

In addition to the on/off button, the device contains an additional button with a two-color

led. During normal operation, the led is green, while during other operations it may change

color. Possible states of the led are the following: off, green, red, orange, blinking green

and blinking red. The button is used for two different operations: Bluetooth reset, if a

single pressure is detected and parameters saving in flash memory, if a long pressure

(more than two seconds) is detected. These timings are guaranteed thanks to the counter

incremented in the Timer0 interrupt.

In the first part of the firmware, we perform the initialization and configuration of the

microcontroller pins and all the explained components and features, before entering the

loop. This phase lasts for a few seconds and it ends with the switching on of the led, which

indicates the beginning of the loop and the start of the main functionality of the device.

First, input signals are acquired using Direct Access Memory (DMA). This feature saves

the data in the RAM while the CPU can perform other operations. The sampling rate is

1956 Hz and the acquired samples are saved in two arrays (one for each channel).

After that, the signal is analysed to compute the level of muscle activation. First, the signal

is filtered with a high pass filter to erase movement artefacts and a comb filter in order to

Page 9: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

9

eliminate the noise caused by stimulation. The frequency is 16 Hz, so this filter also erases

the 50 Hz hum. Next, blanking is performed on the first 20 samples (corresponding

approximately to 10 ms) to eliminate all the other noise during the feature extraction. The

muscular activity level is calculated through the root mean square (RMS) value across the

entire acquired samples of a single cycle (110 samples). To calculate the amplitude of

stimulation from the obtained RMS value, a piecewise linear function is used. If the value

is lower than a threshold, the stimulation will be zero; if the value is greater than the

threshold, the difference between these two values will be multiplied by a gain, obtaining

the value of the delivered current. The current cannot exceed a maximum value (to avoid

damage to the patient). In this way, the stimulation is proportional to the detected EMG

activity and it can be easily controlled.

Current delivery occurs through the development of a finite state machine, which is

activated in the interrupt of Timer1 every 300 μs. During each state, in addition to the

operations performed, the state variable is changed so that the next state is activated during

the next interrupt. In this way, the pins that control the relays and the current output are

progressively activated and deactivated, in order to form the biphasic square wave on the

two channels. The finite state machine is reset once during each cycle, so that stimulation

is delivered every 60 ms with a 16 Hz frequency (which guarantees a continuous force

production without muscle fatigue).

The last step of the loop is the communication with the Android app, which takes place in

two steps: data are first transferred from the microcontroller to the WT12-A module (via

UART) and then transferred from the latter to the external host (via Bluetooth).

The device has been tested with EMG acquisition (with electrodes positioned on the wrist

extensors of a healthy subject) and with an artificial signal generator, based on the voltage

produced by an external DAC. The tests have been carried out to assess the proper current

output, the effectiveness of the digital filters and the battery consumption. We also

analysed a disturbance caused by the activation of the solid state relays. The results have

shown how the current level is proportional and easily controllable. The spectrum analysis

of the various signals indicated the effectiveness of the filters, making the device usable to

stimulate any muscle. Battery consumption is extremely low during the operations without

Bluetooth communication and, when the communication is activated with the stimulation,

Page 10: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

10

it reaches a maximum of 375 mW. The disturbance caused by the activation of the relays

is reduced by half by adding, on each channel, two anti-parallel Zener diodes.

The device was inserted in a 3D printed box and it is used for a study on the effectiveness

of this type of rehabilitation treatment at Fondazione Don Gnocchi (Milano). At the

moment, only one stroke patient has been treated and his rehabilitation was focused on the

elbow extension. The signal was recorded by the same muscle that was stimulated (triceps)

and, despite the high noise, the device proved perfectly controllable. Ten 45-minute

sessions were held and the batteries have never been replaced. Finally, a survey (addressed

to ten physiotherapists) was also prepared. In this way, we could better understand the

potential of this type of treatment. The answers have shown that most interviewed

physiotherapists are interested in functional electrical stimulation and believe that using

smartphone and tablet apps can contribute to the spread of this technology.

The developed system has proved to be functional and adaptable to different movements

and body parts, small and wearable. Future developments of the firmware could involve

the extraction of more specific information from the EMG, in order to differentiate the

activity of each muscle and to have more specific solutions for each type of movement.

However, this would result in an increase in the amount of calculations. In the future, a

circuit and electrodes support could also be developed. It could be 3D printed and worn

around the forearm. In this way there would be no wires along the user's body, which

could have a more comfortable and cheap solution.

Page 11: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

11

SUMMARY (ITALIAN)

Lo scopo del progetto è lo sviluppo e l’implementazione del firmware di un

microcontrollore per l’utilizzo di una neuroprotesi, principalmente per permettere a

pazienti neurologici con la mano paralizzata, il recupero della funzione di prensione. Il

dispositivo si basa sulla stimolazione elettrica funzionale (FES), attraverso la quale, i

muscoli paralizzati vengono attivati tramite l’eccitazione artificiale dei motoneuroni

interessati. In seguito ad un ictus o ad un danno spinale, i neuroni che si trovano al di sotto

del livello interessato, pur non potendo essere attivati dall’attività cerebrale, non sono

danneggiati e possono essere stimolati artificialmente. Diversi studi hanno dimostrato

l’efficacia di questo trattamento, sia come metodo riabilitativo (al fine di recuperare la

funzione motoria), che come metodo di assistenza per compiere le attività della vita

quotidiana.

La stimolazione avviene tramite il passaggio di corrente elettrica, applicata mediante

l’utilizzo di due elettrodi, che causa la depolarizzazione della membrana del neurone e la

creazione di un potenziale d’azione. Poiché la corrente nei tessuti è ottenuta tramite lo

spostamento di ioni e non di elettroni, è importante studiare al meglio la modalità di

erogazione della stessa, per evitare danni ai tessuti, derivati da quantità nette di cariche

trasferite al loro interno. Un altro aspetto fondamentale è quello della frequenza di

stimolazione: poiché infatti il principio di reclutamento delle fibre muscolari è diverso in

caso di attivazione naturale o artificiale, nell’ultimo caso il tessuto muscolare è più

soggetto al fenomeno di affaticamento e una frequenza alta potrebbe peggiorare questo

aspetto. D’altra parte è necessaria una frequenza di stimolazione minima per garantire una

produzione di forza continua. Per facilitare l’utilizzo del dispositivo, la stimolazione può

essere attivata e controllata da diversi segnali biologici (EEG, EMG) o sensori artificiali

(IMU, goniometri), senza avere quindi un pattern sempre uguale a se stesso.

Per quanto riguarda il recupero della funzione di prensione della mano esistono già alcuni

dispostivi (sia impiantabili che rimovibili), tra cui MeCFES (Myoelectrically Controlled

Functional Electrical Stimulator), utilizzato come punto di partenza per lo sviluppo del

nuovo dispositivo. MeCFES si basa sul principio della prensione tramite l’estensione del

Page 12: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

12

polso e amplifica questo effetto stimolando i flessori delle dita quando viene rilevata una

sufficiente attività muscolare degli estensori del polso. Il controllo in questo modo è

intuitivo e l’ampiezza della corrente erogata è proporzionale all’attività registrata tramite

EMG.

Il dispositivo sviluppato presenta molte differenze e vantaggi. Il circuito è stato ridotto di

dimensioni, così come le batterie (sono utilizzate tre pile AAA da 1.5 V). Il dispositivo

presenta due canali in ingresso e due in uscita e il firmware è stato quindi riscritto per

adattarsi al meglio alle nuove componenti e funzionalità. La novità più rilevante è la

capacità del sistema di comunicare (tramite Bluetooth) con un applicazione Android su un

dispositivo esterno, come uno smartphone o un tablet. Questa funzione permette all’utente

di modificare i parametri di stimolazione durante l’utilizzo e di visualizzare il segnale

EMG acquisito. In questo modo il dispositivo può essere adattato a diverse parti del corpo

e diversi movimenti, che possono aver bisogno di altri parametri. Il firmware del sistema è

strutturato in modo da avere una parte di acquisizione del segnale EMG, una parte di

analisi digitale del segnale, una macchina a stati finiti per erogare la stimolazione e, infine,

una parte per comunicare con il dispositivo esterno.

Prima della conversione analogico-digitale, operata dall’ADC del microcontrollore

(ADuCM360), viene svolto un condizionamento analogico del segnale acquisito tramite il

blocco AD8232. In questo modo il segnale (di pochissimi mV) viene amplificato e filtrato

mediante amplificatori strumentali (INA) e OpAmp. Il guadagno totale del blocco è 200 e

la banda passante e tra i 7 Hz e i 480 Hz, per rispettare il contenuto in frequenza del

segnale EMG. La stimolazione viene invece erogata grazie alla circuiteria che permette di

sviluppare alta tensione (fino a 294 V) partendo dal basso voltaggio garantito in ingresso

dalle pile.

La comunicazione via Bluetooth con smartphone/tablet è possibile grazie al modulo

Bluetooth WT12-A, il quale comunica con il microcontrollore attraverso una componente

UART (Universal Asynchronous Receiver-Transmitter). Questa modalità è utilizzata

anche per la programmazione del modulo. Un altro sistema di comunicazione utilizzato

all’interno del dispositivo è SPI (Serial Peripheral Interface), mediante la quale vengono

Page 13: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

13

trasferiti ad un DAC i valori relativi all’ampiezza della corrente di stimolazione e all’alto

voltaggio da sviluppare per la stessa. Il DAC è contenuto nel AD5592, che è formato da

convertitori su otto diversi pin. I dati trasferiti sono composti da 16 bit: i primi 4 indicano

l’indirizzo del pin corretto, mentre i restanti 12 rappresentano il valore da trasferire. Per

questo motivo è stato inserito un controllo che limita i valori a 12 bit. A causa di questo

limite il valore massimo di alto voltaggio trasferibile è 294 V, mentre l’ampiezza della

corrente raggiunge valori molto elevati, anche se difficilmente vengono richiesti più di 100

mA per una stimolazione dei tessuti muscolari umani.

Il microcontrollore contiene due timer, che sono rilevanti per l’applicazione richiesta dal

dispositivo. La tempistica delle varie operazioni è infatti molto importante, soprattutto per

quanto riguarda l’erogazione della corrente di stimolazione. Per entrambi i canali di uscita

deve essere infatti generata un’onda quadra bifasica e la durata delle due fasi deve essere

assolutamente uguale, per evitare danni ai tessuti. A questo proposito, la macchina a stati

finiti usata per la stimolazione viene chiamata nell’interrupt del Timer1, che interviene

ogni 300 μs. Questo valore può essere modificato, ma è ottimale per il tipo di stimolazione

erogata. Il Timer0 viene invece utilizzato come contatore del tempo trascorso

dall’accensione del dispositivo e una variabile viene incrementata nell’interrupt, che

interviene ogni 1 ms.

Il microcontrollore contiene 128 kB di memoria flash. Poiché la memoria utilizzata per

salvare il programma è di pochi kB, abbiamo deciso di utilizzare dello spazio non

occupato per salvare alcuni dati specifici, come i parametri di stimolazione. In questo

modo l’utente può memorizzare i parametri correntemente utilizzati (attraverso la

pressione prolungata di un tasto), senza doverli ripristinare ad ogni utilizzo del dispositivo.

Durante l’accensione, i valori salvati vengono letti e inseriti nelle variabili corrispondenti.

Oltre al tasto di accensione e spegnimento, il dispositivo contiene un ulteriore tasto con un

led a due colori incorporato. Durante l’accensione e il normale funzionamento, il led è

verde, mentre durante altre operazioni può cambiare colore. I possibili stati del led sono i

seguenti: spento, verde, rosso, arancione, lampeggiante verde e lampeggiante rosso. Il

tasto viene invece utilizzato per due diverse operazioni: reset del Bluetooth per una

Page 14: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

14

pressione singola e salvataggio dei parametri nella memoria flash per una pressione

prolungata (lunga più di due secondi). Queste tempistiche sono garantite grazie al

contatore attivati dall’interrupt del Timer0.

Nella prima parte del firmware, prima di entrare nel ciclo, avviene l’inizializzazione e la

configurazione dei pin del microcontrollore e di tutte le componenti e le funzionalità

illustrate. Questa fase ha una durata di pochi secondi e termina con l’accensione del led,

che indica l’ingresso nel ciclo e l’effettivo inizio della funzionalità principale del

dispositivo.

Come prima operazione vengono acquisiti i segnali in ingresso, tramite l’utilizzo del DMA

(Direct Access Memory). In questo modo i dati vengono salvati nella RAM mentre la CPU

può svolgere altre operazioni. La frequenza di campionamento è 1956 Hz e i sample

acquisiti vengono salvati in due array (uno per ogni canale).

Successivamente il segnale viene analizzato per determinare il livello di attivazione

muscolare. Le operazioni svolte sui dati sono le stesse per entrambi i canali. Inizialmente il

segnale viene filtrato con un filtro passa alto per eliminare gli artefatti da movimento e un

filtro a pettine in modo da eliminare il disturbo provocato dalla stimolazione. Poiché la

frequenza è 16 Hz, questo filtro elimina anche il disturbo di rete a 50 Hz. Successivamente

viene operato un blanking sui primi 20 campioni (che corrispondono a circa 10 ms) per

garantire l’assenza di disturbi durante l’estrazione delle informazioni di interesse. Il livello

di attività muscolare è calcolato tramite il root mean square (RMS) su tutta la finestra di

acquisizione di un singolo ciclo (110 campioni). Per calcolare l’ampiezza di stimolazione

a partire dal valore RMS ottenuto viene utilizzata una funzione lineare a tratti. Se il valore

è minore di una soglia, la stimolazione sarà nulla; se invece il valore è maggiore della

soglia, la differenza tra i due verrà moltiplicata per un guadagno, ottenendo così il valore

della corrente erogata. Quest’ultima, in ogni caso, non può oltrepassare un valore massimo

(per evitare di arrecare danno al paziente). In questo modo la stimolazione è proporzionale

all’attività EMG rilevata e può essere controllata con facilità.

Page 15: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

15

L’erogazione della corrente avviene attraverso lo sviluppo di una macchina a stati finiti,

che viene attivata nell’interrupt del Timer1 ogni 300 μs. Durante ogni stato, oltre alle

operazioni svolte, la variabile di interessa viene modificata in modo che alla successiva

chiamata venga attivato lo stato successivo. In questo modo i pin che controllano i relay e

l’erogazione della corrente vengono progressivamente attivati e disattivati, in modo da

formare l’onda quadra bifasica progressivamente sui due canali. La macchina a stati finiti

viene resettata una volta durante ogni ciclo, in modo che la stimolazione venga

effettivamente erogata ogni 60 ms, con una frequenza di 16 Hz (che garantisce una

produzione di forza continua, senza affaticare troppo il muscolo).

L’ultima operazione svolta nel ciclo è la comunicazione con l’App Android, che avviene

in due fasi: trasferimento dati tra microcontrollore e modulo WT12-A (tramite UART);

trasferimento dati tra modulo WT12-A e host esterno (tramite Bluetooth).

Il dispositivo è stato testato sia con EMG naturale (con elettrodi posizionati sugli estensori

del polso di un soggetto sano), che con un generatore di segnale artificiale, basato sulla

tensione prodotta da un DAC esterno al sistema. I test sono stati svolti per valutare

l’effettiva erogazione della corrente e il rispetto dei limiti massimi, l’efficacia dei filtri

digitali, il consumo della batteria e un ulteriore disturbo causato dall’attivazione dei relay.

I risultati hanno evidenziato come il livello di corrente erogato sia proporzionale e

facilmente controllabile. L’analisi dello spettro dei diversi segnali hanno indicato

l’efficacia dei filtri, rendendo il dispositivo utilizzabile per stimolare qualsiasi muscolo. Il

consumo di batteria è estremamente ridotto durante il funzionamento senza comunicazione

Bluetooth e, durante l’attivazione di quest’ultima insieme alla stimolazione, raggiunge al

massimo i 375 mW. Il disturbo causato dall’attivazione dei relay è ridotto della metà

aggiungendo in uscita, su ogni canale, due diodi zener opposti.

Il dispositivo è stato inserito in una scatola stampata in 3D ed è utilizzato per uno studio

sull’efficacia di questo tipo di trattamento presso la Fondazione Don Gnocchi (Milano). Al

momento è stato trattato un solo paziente soggetto a ictus, la cui riabilitazione è

concentrata sull’estensione del gomito. Il segnale viene quindi rilevato dallo stesso

muscolo che viene stimolato (tricipite) e, nonostante i grandi disturbi, il dispositivo si è

Page 16: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

16

dimostrato perfettamente controllabile. Sono state svolte dieci sedute da 45 minuti cadauna

e le pile non sono mai state sostituite. Infine è stato redatto anche un questionario a cui

hanno risposto dieci fisioterapisti per comprendere al meglio la potenzialità di questo tipo

di trattamento. Le risposte hanno evidenziato come buona parte degli intervistati siano

interessati alla stimolazione elettrica funzionale e credano che l’utilizzo di app per

smartphone e tablet possano contribuire alla diffusione di questa tecnologia.

Il sistema sviluppato si è dimostrato funzionale e adattabile a diversi movimenti e parti del

corpo, oltre ad essere di dimensioni ridotte e quindi indossabile. Uno sviluppo futuro del

firmware potrebbe riguardare l’estrazione di informazioni più specifiche dall’EMG, in

modo da differenziare l’attività di ogni muscolo e avere soluzioni più specifiche per ogni

tipo di movimento. Ad ogni modo, questo causerebbe un aumento nella quantità di calcoli

e quindi nelle tempistiche di esecuzione del programma. In futuro deve anche essere

realizzato un supporto per circuito ed elettrodi che può essere stampato in 3D e indossato

intorno all’avambraccio. In questo modo non ci sarebbero fili lungo il corpo del paziente,

che potrebbe avere una soluzione più comoda ed economica.

Page 17: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

17

1. INTRODUCTION

1.1 OBJECTIVE OF THE PROJECT

The goal of this project was to develop and write the firmware (a type of software that runs

in an embedded system) for a neuroprosthesis aimed at the rehabilitation of the paretic

hand. This application is based on the principle of functional electrical stimulation (FES)

controlled by the activity of properly selected muscles. The circuit for the acquisition of

the EMG signal and for producing the stimulation current is formed by different

components. The microcontroller is interfaced with different elements, so it is important to

study and to adapt every hardware component of the circuit, in order to obtain a better

result in terms of size, power consumption, current output and communication with an

external device (smartphone, tablet), called ’the host’. The firmware is divided into four

parts: acquisition of the EMG signal from the recorded muscle; digital signal processing in

order to computer the level of activation of the muscles and the stimulation current

amplitude; delivery of the current (using a finite state machine); communication with the

Android app (via a Bluetooth module). The system is powered by three 1.5 V batteries, so

it is important to limit the power consumption. The whole system has to be wearable, easy

to use for every user and cheaper than other similar devices on the market. It is based on

another existing device, which is called MeCFES (Myoelectrically Controlled Functional

Electrical Stimulator). The developed device is been used for a rehabilitation study in

Fondazione Don Gnocchi (Milano) and, at the moment, only one stroke patient has been

treated with it.

In this chapter, I will explain the field of application of the system (patients that can be

treated), the natural muscle contraction and its artificial activation and the state of the art

(with the description of existing devices). The main part of this thesis will be dedicated to

the description of the developed device, and to the explanation of its principles of

functioning.

Page 18: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

18

1.2 FIELD OF APPLICATION

Every year many people in the world are subject to neurological damages that can be

caused by different events like strokes that leads to hemiplegia or spinal cord injuries

(SCI) that leads to tetraplegia. Traumatic spinal cord lesion involves 16 persons/million

every year in Europe and 40 persons/million every year in the United States [Lee et al.,

2014], whereas stroke involves 1.1 million inhabitants of Europe and it is one of the first

causes of disability in the developed countries [Béjot et al., 2016]. The number of cases

are rising in the developing countries and for young adults and these events has also a

relevant social impact per the people involved. Neurological damages often leads to motor

disabilities that can compromise people’s wellbeing and quality of life in terms of

performing tasks and social interactions. 30% to 50% of stroke subjects are affected by

depression within the first year after the event [Béjot et al., 2016]. Treatment of motor

disabilities in neurological patients is very important to reach two goals: the regaining of

the independent body functions and the assistance to perform essential tasks during the

activities of daily living.

One of the main disabilities caused by these events is the paretic hand. The restoration of

the hand function is very important for disabled people. The grasp of the hand is useful for

a great number of tasks during the activities of daily living and functional electrical

stimulation (FES) can help the patients to restore the hand function to perform all the

essential tasks, like eating, drinking, reaching and moving object and many others. Many

studies have underlined the positive effects of a neuroprosthesis, defined as a device used

to improve the function of an impaired nervous system. Almost all the developed

neuroprosthesis are based on the functional electrical stimulation, which consists in a

paralysed muscle activation using electrical current to stimulate the undamaged nerves.

FES is technique that has been used for several years and it is in constant evolution. It is

not only effective on SCI and stroke patients, but also in cases of cerebral palsy [Wright et

al., 2000] and multiple sclerosis [Mayer et al., 2015], in order to improve balance and gait

function. FES is a rehabilitation technique that can be adapted to different damages and

Page 19: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

19

different body parts and it has a positive effect both in upper limb [de Kroon et al., 2002]

and lower limb motor control [Peng et al., 2010].

In the next paragraphs I will discuss the basics of myology and neurology applied to the

muscle contraction and the FES principles and contraction.

1.3 THE MUSCLE CONTRACTION

A controlled muscle contraction is essential to perform every task during the daily living.

Muscles are the cause of force development and also of the right movement of the

different body segments. They also prevent pressure sores with a cushioning effect. The

activity of muscle is also important for its effect on the bone remodelling that depends on

the forces acting upon the skeletal structures, which are linked to through tendons.

Skeletal muscles are composed by different parts:

● Epimysium is a membrane that covers the whole muscle and it is formed by

connective tissue. Under the epimysium different bundles of contractile cells can

be found, that are called fascicles;

● Each fascicle is enclosed in another sheath of connective tissue, called perimysium,

which contains 10 to 100 muscles fibers;

● Fibers are the muscle cells and each one is covered by the endomysium, where

blood vessels can be found.

● Each fiber contains the contractile elements of the muscle, that are called

myofibrils.

● Myofibrils are composed by different proteins (actin, myosin and tropomyosin)

forming a repeated sequence of a structure, called sarcomere.

Myosin (figure 1) molecules (forming thick filament) have parallel tales, a neck and

globular heads that bind with actin (thin filament).

Page 20: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

20

Figure 1. The structure and interaction among troponin, tropomyosin and actin molecules, which form the

thin filament.

Figure 2. The structure of the myosin molecules, that form the thick filament. It can be seen the molecules

tails and heads.

Actin (figure 2) is a globular protein composed by two filaments forming a double helix

structure. It is covered by another helical protein (tropomyosin), that covers the active

zones and is attached to troponin molecules.

The repeated structure of the sarcomere is shown in figure 3.

Page 21: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

21

Figure 3. The structure of a single sarcomere

The contraction is caused by of the sarcomere shortening, following the sliding filament

theory. The myosin heads bind to the active sites of the actin and rotate, causing a relative

movement between the two filaments. The movement is not synchronized for all the heads:

in every instant ca. half of the heads are rotating, so that there is a turnover and the

shortening is continuous. The relative movement of all the sarcomeres in every fiber

causes the noticeable contraction of the muscle. The energy for the movement of the

myosin heads is provided by adenosine triphosphate (ATP) molecules, the hydrolysis of

which is activated by ATPase (an enzyme present on myosin). The reaction produces

energy (7.13 Kcal/mol), used for the heads movement and it is the following:

ATP + H2O ➝ ADP + Pi (1)

ADP stands for adenosine diphosphate, while Pi is the inorganic phosphate group. After

the reaction, ADP and pyrophosphate go away from myosin to the sarcoplasm.

Page 22: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

22

Figure 4. ATP hydrolisis permit the binding between actin and myosin an so the muscle contraction

This mechanism (figure 4) is activated by the arrival of an action potential from a

motoneuron and so it is triggered via a synaptic input. Each motoneuron innervates more

than one fiber and the group formed by a motoneuron, its axon and the fibers that it

innervates is called motor unit. The presynaptic and postsynaptic membranes of the two

cells are called the neuromuscular junction. Under the sarcolemma (a membrane that cover

the fibers), there is the sarcoplasmic reticulum, that stores Ca2+ ions. Corresponding to the

end of each sarcomere there are some extension of sarcolemma, called transverse tubules,

which limit the Ca2+ cisternae.

When the action potential is transmitted, after the synapsis, the muscle cell can generate a

similar impulse that travels from the endplate (that is the junction between the neuron and

the muscle) to the edges of the muscle. The muscular action potential causes a variation in

the sarcoplasmic reticulum membrane permeability and so the Ca2+ ions move to the

sarcoplasm and activate the contraction mechanism explained in the sliding filament

theory. These ions bind to the troponin molecules placed on actin, changing the

tropomyosin position and allowing the binding between the myosin head and actin and so

the contraction itself. Because of the high velocity of the impulse (5 m/s [Hunter et al.,

Page 23: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

23

1987]), Ca2+ is released at the same time in the whole muscle, so that all the fibers can

work together. To stop the contraction Ca2+ ions are brought back in the cisternae through

an active pump and the energy for this operation is produced by the ATP hydrolysis. When

in the sarcoplasm a low Ca2+ concentration is reached, the binding between myosin and

actin is no more allowed and the muscle is put at rest. This contraction mechanism is

present only in the voluntary skeletal muscle.

There are three different types of muscular fiber, the definition of which is based on the

activation velocity and the used energy system (aerobic or anaerobic):

● Slow Oxidative or Red fibers (type I) produce low force twitches and they are

based on the aerobic energy system. They are characterized by a slow contraction

and an high resistance to fatigue because they are surrounded by an high number of

blood vessels that bring oxygen and other molecules and remove waste products.

This fibers and their corresponding axon have a small diameter and they are

present in muscles that are continuously used, like for example, the postural

muscles.

● Fast Oxidative-Glycolytic fibers (type II A) produce higher force twitches and are

based on both the aerobic and anaerobic energy systems. They have a medium size

and they have a good resistance to fatigue, also when developing high force level.

● Fast Glycolytic or White fibers (type II B) are surrounded by a small number of

vessels, so they are called “white fibers”. They use the anaerobic energetic system

and they can produce very high force twitches, but for a limited amount of time

because their low resistance to fatigue. They have a large diameter.

Page 24: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

24

Figure 5. Differences between slow and fast muscle fibers

Each motor unit is characterized by a very different amount of innervated fibers (of the

same type) and the innervation ratio defines how many muscular fiber are present for each

nervous fiber. Generally the type I fibers are characterized by a low innervation ratio (the

number of fibers innervated by a motor unit), whereas the II fibers have an higher ratio,

because they don’t need to modulate the force precisely (figure 5).

For this reason the different types of fibers are recruited at different times, depending on

the force needed. The muscle fiber recruitment mechanism is explained by the

Henneman’s size principle, which states that the motor units are recruited from the

smallest to the largest. In this way the type I red fibers are the first to be activated, and

later also the other types fibers begin to produce force. The fibers forming a motor unit are

not close to each other, so that, even if a small number of units are activated, there is a

contraction in the whole muscle and not only in a small part of it.

Page 25: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

25

1.4 ARTIFICIAL CONTRACTION: FUNCTIONAL

ELECTRICAL STIMULATION

Functional electrical stimulation is a technique that uses electrical stimulation in order to

partially or totally recover some motor activities that are compromised for any reason. In

any case it is very important the fact that the peripheral neural circuits and the neurons that

control the interested muscles are active and not damaged. There are many cases in which

only the central nervous system is interested in the injury, compromising the functional

motor activities even if the peripheral neurons are not damaged. In these cases, the damage

can affect the motor centers in the brain (so that no command signal can be generated) or

the spinal cord (so that the impulse transmission is stopped). If we consider a spinal cord

lesion, there are three different areas that are distinguished:

• The area above the lesion, in which the motor system is still controlled by the

motor centers.

• The lesioned area, that cannot be substituted by functional electrical stimulation

(because also its peripheral circuits are damaged).

• The area under the lesion, in which the commands cannot be transmitted, but the

nerves are still functioning, so they can be stimulated.

In some cases also the peripheral circuits of the area above lesion can be damaged, because

some neurons descending along the spinal canal can be interrupted by the lesion.

Depending on the area of the lesion we can find different situations of motor impairment,

like monoplegia, hemiplegia, paraplegia or tetraplegia.

Neurons and muscles can generate and propagate action potential naturally or with the

use of current. The neurons can be activated first, because they have a lower threshold

than the muscles. In this way we can stimulate the neurons and indirectly the muscle will

activate, with the same mechanism explained before. The current in the biological tissues

is not an electrons flux, but it results by the movement of positive and negative ions. The

cations travel to the cathode and the anions travel to the anode. The cathode is the active

electrode because the positive charges under it increase the cell internal potential, that can

Page 26: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

26

go above the threshold and activate the action potential. The cell potential under the

anode is decreased by the presence of the negative charges (figure 6). The movement of

the ions is caused by the variation of the electric field, not by the presence of it.

Figure 6. The mechanism of action potential generation with the stimulation current.

Different stimulation parameters can be identified (figure 7):

● Current Amplitude, I [mA]: usually a system is controlled in current to prevent the

exceeding of a certain threshold that could be dangerous for the user. Current is

more dangerous and if the system is controlled in voltage, current would be

unknown and depending on impedances. For neurological subjects the current used

is between 10 and 130 mA.

● Pulse Width, PW [μs]: It is the duration of a single current pulse. It is usually set

between 100 and 500 μs.

● Tension, V [V]: it supports the current delivey.

● Stimulus frequency, f [Hz]: Frequency is the inverse of the time between every

biphasic stimulation wave (T).

● Waveform: It is important to choose a biphasic waveform in order to limit the

tissue damages.

Page 27: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

27

Figure 7. Stimulation parameters in case of biphasic square wave.

It is important that the waveform of the stimulus is the best possible to activate the neurons

and the muscles. The most simple waveform that generate an action potential is a square

wave. The relationship between the amplitude (I) and the duration (D) of the current in

order to activate a cell is inversely proportional (figure 8). In any case there is no

activation if the current amplitude is lower than a defined value, called rheobase.

Viceversa an high amplitude cannot generate an activation if the duration of the wave isn’t

long enough. Chronaxie is the time required to activate the cell if the current has an

amplitude that doubles the rheobase. The transferred charge is the product of amplitude

and stimulus duration. The relationship is shown in the following graph and equations.

The function represents the minimum amplitude values that can generate an action

potential referred to different stimulus durations.

Page 28: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

28

Figure 8. Relationship between current amplitude and time required to activate a muscle contraction.

I = IR / [1 - e (-D/T)] (2)

Q = I D (3)

The important factor for the generation of the action potential is not only the transferred

charge, but also the dynamic aspects. Also, the refractory period of the cell must be taken

in consideration to reach the desired final result of the stimulation. After the action

potential there is a period, called absolute refractory period, in which the neuron cannot be

activated because of the inactivation of the Na+ channels, that remain open until the

membrane hyperpolarizes. The duration of this period is equivalent to 1-2 ms. After this

amount of time, the neuron enters the relative refractory period, in which it can be

activated, but the threshold value is higher than before. This effect is caused by the

hyperpolarization of the membrane and it lasts 10 ms, when the threshold value is

stabilized again. For these reasons, the activation frequency of a cell has a maximum

value, depending also on the amplitude of the current stimulus. For the neuron this

maximum value corresponds to ca. 100 Hz, whereas for the muscle cell the frequency limit

is lower. Anyway, it is not recommended to stimulate using a frequency too high, because

in this way the neuromuscular junction can consume all its ability to release the

Page 29: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

29

neurotransmitter in a very short amount of time, causing a block of synaptic transmission

and so the inability to activate the muscle and to generate force. In any case good results

can be reached also using a stimulation frequency lower than 50 Hz and it can be

modulated depending on the goals of the stimulation itself.

The waveform of the stimulation current can be different and it influences the activation

threshold, the electrodes corrosion and the tissue damage. A biphasic wave is highly

recommended in order to equalize the charge transfer into the tissue and the charge

transfer out of the tissue. Among the different biphasic waveform it can be choose the one

with the characteristics required by the application.

During the natural impulse transmission, the direction of the action potential along the

neuron axon is always the same (orthodromic): from the center to the periphery for

motoneurons and from the periphery to the center for sensorial neurons. This happens

because the action potential is naturally generated in the soma. In the case of artificial

stimulation, the action potential is generated in the central part of the axon, and so it

propagates along two directions (orthodromic and antidromic), with different effects:

● Orthodromic propagation along motoneurons: direct activation of the muscular

fibers and force generation (M-wave);

● Antidromic propagation along motoneurons: in some cases the signal causes the

activation of the motoneuron itself when arriving to the soma. This generates the F-

wave, that is visible a certain amount of time after the M-wave;

● Orthodromic propagation along sensorial neurons: this signal can activate different

kind of reflexes, like H-reflex or skin-muscle reflex;

● Antidromic propagation along sensorial neurons: no effect generated.

In some application it is useful to activate some reflexes, in order to synergistically

activate different muscles with a single stimulation on a specific skin area.

Page 30: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

30

It is important that the peripheral motoneurons are not damaged because the activation

threshold of the neurons is lower than the muscles one and the generated force results to be

higher.

There are also some differences between the natural muscle contraction and the

contraction caused by artificial electrical stimulation. In the latter case there is no

physiological turn-over, because all the fibers where the threshold is exceeded, are

activated at the same time. This synchronism causes the rise of the required activation

frequency needed to generate the contraction fusion, without single twitches. During the

natural contraction this frequency is lower than 10 Hz, whereas in the other case it is

higher. Another important difference consists in the muscular fiber recruitment order. As it

has been explained before, during the natural contraction the fibers are recruited from the

smallest to the bigger (following the Henneman’s size principle), but with artificial

stimulation this order is inverted, because the bigger is the fiber diameter, the lower is the

activation threshold. All these aspects and differences lead rapidly to a condition of

muscular fatigue, that is one of the main problem of functional electrical stimulation. This

phenomenon is stressed by the previous condition of the muscle, that is paretic and so it

has a reduction in the resistance to fatigue (because of the muscle atrophy and the slow

fibers conversion in fast fiber, which are less resistant to fatigue). This problem can be

reduced by stimulating with a frequency value lower than 20 Hz, in order to increase the

muscle resistance to fatigue. To increase muscle volume and force, an higher frequency

can be used (>30 Hz), but in this way the fatigue problem is stressed.

There are different studies focused on the reduction of muscle fatigue during FES [Karu et

al., 1995] [Ibitoye et al., 2016] and they use methods like fast fibers synaptic junction

block, conversion of fast fibers in slow fibers or activation of different areas of the muscle

(or activation of different muscle for synergistic movements).

Another problem caused by the difference fiber recruitment is the force modulation.

During the artificial stimulation, the generated force can be modulated only changing the

wave amplitude, the stimulus duration or the frequency (spatial and temporal integration).

In this way there is an higher charge transmission and fibers with higher threshold are

Page 31: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

31

activated. Almost in every device the stimulation frequency is fixed and the force is

modulated with the amplitude and duration modification. The relationship between this

parameters and the generated force is not linear and at a certain duration or amplitude

level, it saturates (figure 9).

Figure 9. Relationship between stimulation current amplitude or duration and produced force.

The stimulator circuit have to generate a high voltage, in the order of 100-200 V (starting

from the voltage supplied by the batteries) and deliver the current using the generated

voltage. The current amplitude can have different values, but we must take in

consideration the muscle to be stimulated. To perform a task with big muscles the needed

current can reach a value of 100 mA. Often the high voltage is generated by means of a

transformer, which is able to generate a high voltage from a low one, depending on its

coil. This is a very simple method, but the size of the transformer can limit its advantages.

Another method can also be used, which consists in charging some capacitors with a

photoflash capacitor charger. This solution allows to store high voltage values that can be

supplied (High Voltage Power Supply, HVPS) to the stimulator part of the circuit in order

to deliver the current. So, a voltage controlled current source (VCCS) is used and it

represents an alternative to the transformer coupling [Thorsen et al., 2009]. After the high

Page 32: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

32

voltage storing and transfer with the capacitors, the biphasic output can be provided by a

multiplexer in the output stage.

SYSTEM CONTROLLERS

There are different examples of FES control system with different effectiveness and

complexity.

The most simple control system is the open-loop controller (figure 10). In this case the

output depends only on the action of the user and there is no feedback (if we don’t

consider the user visual control). The device is fully controlled by the user and the

stimulation pattern and parameters are often predefined and they can’t be changed. This

system is extremely simple, but also limited because there is no disturbance compensation,

it can’t respond to unattended events and it is not adaptable to fatiguing muscles.

Figure 10. FES open-loop controller

If we consider a closed-loop controller system (figure 11), the stimulation pattern is

determined by the error between the desired movement and the effective movement. This

method is used for a rapid compensation of unexpected situation. In the most case the

controller adopted is a PID (proportional-integral-derivative) controller, that is

proportional to the current error, integrative with respect to the error history and derivative

referring to error changes. The controller function is the following:

pw(t) = Kp · e(t) + Kd · de(t)/dt + Ki · ∫e(t) dt (4)

Page 33: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

33

Each parameter refers to the present, past and future values and they can be computed with

different methods (like Ziegler–Nichols method). In any case the evaluation and the

computation of these parameters can be very difficult (also because of the non-linearity of

the system) so that the PID controller is used only in case of simple and slow movements.

For more complex movements this type of controller needs a long amount of time to adjust

himself.

Figure 11. FES closed-lood controller

An inverse model in the feed-forward controller (figure 12) could be used in order to solve

the problem concerning the phase delay. The issue about this method concerns the

complexity of this system controller because the muscular models are difficult to invert

and so they are modeled with fixed parameters (high approximation).

Figure 12. FES inverse model-PID controller

One solution could be the use of an adaptive controller (figure 13). In this case there is an

adaptive algorithm that takes into account that external system parameters can change

Page 34: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

34

during time, for example when fatigue is occurring. The parameters are not fixed anymore

and this controller system must be online.

Figure 13. Adaptive algorithm for FES inverse model controller

Also more complex methods like artificial neural networks controllers can be used (figure

14). The main problem is to build a training set that can map muscle fatigue. With this

approach the controller is really effective and adaptable and the fatigue problem is

reduced.

Figure 14. FES neural network controller

The stimulation can be activated in different ways: voluntary, if there is some remaining

myoelectric activity in the interested muscle; voluntary, by the myoelectric activity in

another muscle; by the use of sensors or button pressed by the user.

Page 35: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

35

FES CONTROLLED BY AFFERENT SIGNALS

Another idea to control the functional electrical stimulation is to use the signal coming

from the afferent neurons. This method is more suitable for an implantable system and it

could be used for both lower and upper limb. Talking about the cases of impaired hand,

the signal coming from the tactile mechanoreceptors can be used to control if there is

slipping and, in this case, to control the force for the hand grasp [Inmann et al, 2001]. In

SCI and tetraplegic patients, the mechanoreceptors are not damaged, but the afferent signal

can’t be transmitted to the central nervous system because of the injury, so the subjects

cannot perceive sensation. The receptor activity can be recorded with implanted tripolar

cuff electrode and used to trigger the stimulation and to reinforce and control the grasp

when the acquired signal shows the presence of slipping. In this case all the system is

implanted and it works with the use of a transmitting coil. The main limitation of this

technique is the difficulties to use and control an implantable device, as well as the noise

during the acquisition and the reading of data and the invasiveness of the method.

EEG CONTROLLED FES

Brain-computer interface

(BCI) is a method that uses

brain signals to control

external devices. This

technique is very useful

because it can be use to control

a FES device using only a

recorded and processed EEG

signal, without any additional

movement performed by the

subject. In the last years there are a lot of studies focused on the range of the EEG waves

frequency. The subjects can learn to change alpha (8 - 12 Hz) and beta (13 - 30 Hz)

range frequencies by imagining voluntary movements [Marquez-Chin et al,

Figure 15. Mechanism of EEG-controlled FES with the use of

BCI.

Page 36: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

36

2016]. If the power in the beta frequency range decreases below a set threshold,

stimulation is triggered and the subject can move the upper limb (figure 15). This decrease

are referred to as event-related desynchronization (ERD) and happens before the

movement onset. The presence of an ERD is linked to the activation of cortical areas

related to preparation of movement, which, after the execution, is followed by a power

increase, called event-related synchronization (ERS). ERS is linked with inhibited or idling

areas [Functional brain imaging based on ERD/ERS, G. Pfurtscheller, 2001].

This EEG technique is non-invasive, because the signal is acquired through electrodes

outside the scalp, usually placed following the 10-20 standard. There are also other

methods to extract signals from the brain:

● Invasive: the sensor is directly placed into the brain grey matter from the surgery;

● Partially-Invasive: the sensor is placed outside the grey matter, but inside the

scalp.

FES CONTROLLED BY ARTIFICIAL SENSORS

A lot of different artificial sensors are used to trigger and control the stimulation current.

Here the are some examples [Veltink et al, 1998]:

● Goniometers: Used to measure joint angles, they allow to find the position of body

segments. They are invasive respect to other sensors;

● Inertial sensors (accelerometers, gyroscopes): Inertial measurement units are

sensors with tri-axial accelerometer, gyroscope and magnetometer, so they allow to

find acceleration, angular velocity and angle of a body segments. The are also

small, light and perfectly wearable;

● Force sensors: They can be resistive or capacitive adìnd they are used in walking

aid devices. They are used for the measure of forces and pressures distribution

under the feet.

Page 37: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

37

With these sensors the stimulation is activated and controlled by the values measured by

the sensors, through the predefined threshold overcoming. In other cases, the recorded and

processed value is used to set the stimulation pattern in real-time. For this purpose inertial

sensors are used, both for upper and lower limb FES, because they are less invasive and

more practical than goniometers. Great results in the joint angle computation can be

reached also using a reduced number of accelerometers, that are smaller and lighter than

IMUs (inertial measurement units) and can be placed on every body segment. In this way

stimulation pattern to perform different functional tasks. Inertial sensor are also used in a

lot of application to promote lower limb recovery, like FES-cycling [Ruppin et al, 2016].

EMG CONTROLLED FES

Functional electrical stimulation can be controlled and modulated by the user through the

EMG signal from an unimpaired muscle, that sometimes can be in the stimulated muscular

group (depending on the needed application and on the muscle impairment grade). If the

interested muscle is not in same group there are two different possibilities: the muscle that

we read from can be involved in the movement (maybe through synergies) or it can be also

in another area, only activating the stimulation. For any case there are different pros and

cons. If EMG signal from another muscle is used, there are no problems during the

acquisition of the signal because there is no noise (caused by the stimulation), but the

patient must learn a new movement pattern in order to activate the stimulation of the

interested muscle. In the other cases, the trigger movement is more natural, but the

acquired signal is strongly disturbed by the stimulation noise. This happens because the

amplitude of the EMG signal is very low (microvolts), whereas the stimulation voltage is

very high (volts). It is important to amplify only the differential signal, using an amplifier

with an high common-mode rejection ratio and to choose the right electrode position and

amplifier in order to avoid the saturation of the amplifier, that could compromise the EMG

signal acquisition. There are some problem that can be solved with the right hardware

components and digital signal processing and in this way the patient can control and

modulated easily the stimulation, allowing natural movements. After the acquisition, the

Page 38: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

38

EMG is digitally processed and if the obtained value is higher then a set threshold, the

stimulation will be enabled, with prefixed waveform and frequency value.

This technique is very versatile and can be used in different ways and for different

movements and body districts. The limit of some devices is the fact that the stimulation

pattern (duration and current amplitude) and the threshold are fixed and can’t be changed

and adapted to different muscle or situations. A more adaptable device would be very

useful in order to get both a better rehabilitation method and better assistance to the motor

tasks during the activities of daily living.

A lot of studies have confirmed the efficacy of the EMG-controlled FES, both in tasks

performance and in rehabilitation. This technique has been described in different papers

and the reviews are positive regarding the effects of the treatment. While the use of non-

triggered FES has shown only gains in strength, EMG-controlled FES produced

improvements in the functional activities and was proved to be effective in post-stroke

hand function recovery [Young, 2013]. The use of this technique produced functional

improvement also in hand grasping in tetraplegic patients with spinal cord injuries (C6/C7)

[Thorsen et al, 2004]. EMG-controlled FES can have positive effects also in the lower

limb rehabilitation, with the use of techniques based on muscle synergies. Different studies

have been made on the drop foot stimulator (which is usually controlled by sensors like

goniometers or foot switches) and on the FES-cycling, which has been proven to have

positive effects on tetraplegic patients [Yeom et al, 2011].

Page 39: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

39

1.5 STATE OF THE ART: EXISTING DEVICES

FREEHAND SYSTEM [Keith et al., 1989]

Figure 16. Implanted Freehand System and working mechanism

This devices requires implanted electrodes and the stimulation is triggered by a position

transducer placed between the chest and the shoulder (figure 16). It is used to reinforce the

hand grasp. There is an 8-channel implanted stimulator that is supplied electro-

magnetically by an external RF transmission system. The stimulation is controlled by

shoulder movement and permit to perform hand grip tasks. It is hidden, but, for the same

reason, it results to be very invasive. The movement to control the stimulation is not

natural, so a specific training could be needed.

Page 40: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

40

BIONIC GLOVE [Prochazka A., et al. 1997]

Figure 17. Bionic Glove structure

This device controls stimulation for finger flexion and extension and it is activated and

controlled by a mechanical sensor that detects the wrist movements (figure 17). The device

consists in a glove that can be donned independently or with minimal help. The garment is

closed by velcro and the electronic circuit is in a box attached to the glove itself.

Stimulation electrodes are placed over selected muscles and the conductive areas of the

device automatically make contact with them. Stimulation is triggered when the wrist is

extended to a predefined angle, so the user needs to produce a strong wrist extension. The

output current is fixed and not proportional.

NESS HANDMASTER [Ijzerman et al., 1996]

The device consists of a splint, that can be donned independently, and a control box

connected through a wire. The electrodes are placed into the splint. There are different

stimulation modes, that are controlled by the buttons on the box: for different tasks and

exercises (grasp, key grip, etc), there is a different stimulation sequence. The control

method represents the main limit of the device: the stimulation is not controlled by a

natural movement, but by the pressing of buttons with the other hand.

Page 41: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

41

MeCFES [Thorsen et al., 1999]

The MeCFES (Myoelectrically Controlled Functional Electrical Stimulation) is a device

that uses the EMG control method applied to a neuroprosthesis. The device is used for the

rehabilitation of the upper limb, especially for the hand grasp restoration. It could also be

adapted for the rehabilitation of other body segments, including the lower limb. One of the

advantages of MeCFES is the proportional EMG control. There are a lot of devices on the

market based on the EMG controlled FES, but in these cases there is a predefined

stimulation pattern with the same parameters (amplitude, duration, etc) that is triggered by

the overcoming of a fixed threshold [Saxena et al. 1995]. In this way the user cannot fully

control the stimulation and the resulting movement will be always similar. It is very

important for the patient to modulate and control the produce force so that he can adapt it

to the different tasks and situations.

MeCFES takes advantage of the tenodesis function (figure 18). Patient with motor

disabilities that cannot properly contract the fingers flexors uses this mechanism based on

the wrist extension. The extensor carpi radialis (wrist extensor muscle), when is contracted

causes the passive flexion of the fingers, due to the counteracting forces in the tendons.

This passive flexion caused by the extension is useful to perform some tasks, but often the

strength of the grasp is still not high enough to properly perform them without any

difficulties. The stimulation, starting from this principle, could fill the gap and permit a

great grasp reinforcement. So in this device the EMG signal is read and acquired from the

wrist extensors and if they are active, the fingers flexors will be stimulated, resulting in a

strong grasp reinforcement.

Page 42: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

42

Figure 18. EMG-controlled FES mechanism based on the tenodesis function

There are a lot of muscle in the forearm that controls the hand movements and so it can be

difficult to choose the muscles to be recorded and stimulated. Wrist extension is controlled

by extensor carpi radialis longus (ECRL), extensor carpi radialis brevis (ECRB) and

extensor carpi ulnaris (ECU), but only the ECRB

provides a pure wrist extension, whereas the

others are linked also to other hand movements.

The stimulated muscle can be chosen depending

on the wanted type of grasp: it could be useful to

stimulate the thumb flexor or the forefinger and

middle finger flexor.

The whole system (figure 19) is composed by

the surface electrodes to acquire the EMG signal,

the surface stimulation electrodes and the circuit

for the signal acquisition and processing for the

stimulation generation. It is supplied by two

AA batteries (1.5 V, nominal value).

MeCFES has a two-channel input and a two-

channel output so that more the one muscle can be stimulated. The surface electrodes were

chosen because they are not invasive, without any infection risk and they are also very

easy to use, both for a physiotherapist and for the patient himself. In addition, each couple

Figure 19. MeCFES box with circuits and

batteries. The wires are then connected to the

electrodes on user's arm.

Page 43: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

43

of stimulation electrodes can be used by the same subject many times. For each input and

output channel three EMG electrodes (two for the differential input, one for the reference)

and two stimulation electrodes are used. The circuit is divided in two parts: the first for the

signal acquisition, while the second (after the microcontroller processing) for the stimulus

high voltage and current generation. There is also a Bluetooth module in order to

communicate with an external computer, used to change the stimulation parameters.

This device has two main advantages compared to the others: the EMG proportional

control of the stimulation and the possibility to change and adapt the parameters through

the software on the PC. If the recorded signal, after the processing, overcomes a threshold,

the amplitude of the output current will not be fixed, but it will change proportionally to

the level of the EMG. So, modulating the force produced by the muscle that he voluntary

contracts, the subject can also modulate and control the force produced by the stimulated

muscle. This aspect results in smoother movements that help the subject to perform

properly the needed tasks.

Page 44: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

44

1.6 CHARACTERICTS OF THE DEVELOPED SYSTEM

The developed system is based on MeCFES, but has some important differences respect to

it. It is supplied by three 1.5 V AAA batteries (smaller than the previous one) and we

changed both the hardware, using a different circuit, and the firmware. Another software

for the host has been developed and written too and this version of MeCFES can

communicate also with an Android app [Ravasio, 2017]. It offers a more flexible way to

control the device from a tablet or a cellular phone with respect to use a computer. In this

way MeCFES will become a functional portable assistive or rehabilitative device. The user

can set the parameters and use the device also when he is not at home and perform the

needed tasks in every activity of daily living. The device is turned on and off pressing a

button. Another button with a two coloured ‘led’ can be used for other operations when the

system is running (see the paragraph “Button” later).

Figure 20. The support with EMG and stimulation electrodes

Another important difference is the electrode applicator (figure 20), the realization of

which is still in progress and it will allow to have a portable device without external loose

wires along the body of the user. The support is 3D printed and so can be realised to fit

Page 45: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

45

individual user, depending on the forearm measure. A prototype of the support is being

currently made, where the electrodes are fixed onto it and so it will be also the circuit with

the battery, closed in a box that has been designed and developed (see “Result” section). In

this way all the system will be around the forearm of the patient and it will be non-

invasive, not limiting the range of motion of the arm.

Another great advantage of the new system could be the lower cost of the materials. The

support and the circuit box can be 3D printed (creation of three dimensional objects

starting from a digital model), the electrodes are available everywhere and easy to find,

while the assembled circuit can be bought at a lower price than all the other similar device,

leading to a possibility to use the device for a lot of neurological patients with motor

disabilities.

The firmware is divided into five parts (figure 21):

● Configuration: The start of the program is followed by the configuration of all the

microcontroller pin and the initialization of all the needed function. After that, the

main cycle can start.

● Data acquisition: The input signal is acquired by the microcontroller through an

analog to digital converter (ADC), after the analog amplification stage.

● Digital signal processing: The acquired signal is digitally processed (with the use

of filters and other mathematical tools) in order to compute the contraction level

and the amplitude of the stimulation current output.

● Stimulation: The output current waveform is generated with the use of a finite state

machine, that is called by the timer interrupt in order to assure all the right timings.

● Communication: All the needed stimulation parameters and the data acquired are

transmitted via Bluetooth to the host and vice versa.

Page 46: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

46

Figure 21. Firmware flowchart

Every part of the firmware contained different problems to be solved in order to reach a

proper result. This issues and the performance of the final system is obviously linked to

the hardware components, so we also did some reworks on the circuits in order to adapt it

to the wanted function and to find the right solution to the various problems, as explained

later in this dissertation.

In the next chapters I will show and explain the features of the used circuit (especially

regarding the acquisition and stimulation part), the design and the implementation of the

firmware and the test made in order to evaluate the performance of the system.

Page 47: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

47

2. MATERIAL AND METHODS

2.1 CIRCUIT FEATURES (ACQUISITION AND STIMULATION)

The circuit (figure 22) is divided in different sections which provide the needed functions

of the whole systems.

Figure 22. The circuit

● INA block: This block is used for the signal acquisition and conditioning. It is

formed by two conditioning block (containing an instrumentation amplifier and

other components) and all the resistors and capacitors used for the amplification

and the filtering of the signal.

● HVPS block: This block is used to generate the high voltage needed for the

stimulation.

● VCCS block: This block is used to generate the stimulation current after the

voltage transfer from HVPS.

● Bluetooth block: This block contains the Bluetooth module used to communicate

with the external device.

All the blocks functions are controlled by the microcontroller.

Page 48: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

48

2.1.1 AD8232 – SIGNAL CONDITIONING

Before the analog to digital conversion and the processing in the microcontroller, the

acquired signal is amplified because the recorded surface EMG has a very low amplitude

(10 - 5000 μV, as explained in the Introduction). This is one of the most critical issues in

our application, because there are different sources of noise with higher amplitude that can

affect and modify the EMG signal. The noise can be caused by the stimulation current

(which I will refer to as stimulation artefacts), the common mode, DC offset, the activation

of muscles near the ones we are interested in and other movements artefact. For this reason

is important to choose the proper instrumentation amplifier with the right components

configuration, in order to have an high signal to noise ratio. If the noise has a high

amplitude, the INA (Instrumentation amplifier) could also saturate and make the signal

unreadable for a certain amount of time. This can compromise EMG recording and

processing and so all the system main function.

Figure 23. AD8232 block diagram with all its components

The amplifier block chosen for the circuit is AD8232 , is a signal conditioning block

specific for ECG and other biopotential measuring (figure 23). We chose this block

Page 49: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

49

because of the many features useful for a signal analysis like the one we have to perform.

It consists of an instrumentation amplifier (IA), an operational amplifier (A1), a right leg

drive amplifier (A2), and a reference buffer (A3). It contains also lead off detection (LOD)

and fast restore circuitry, which will be explained later.

● The instrumentation amplifier IA is composed by two trans-conductance (so it is a

voltage controlled current source), a DC blocking amplifiers and an integrator. The

voltage divider assures an overall gain of 100 and these components allow a ±

300mV DC offset without saturation.

● The operational amplifier A1 is a rail-to-rail OpAmp that can be used to add gain

and a low pass filter.

● The right leg drive amplifier A2 is used to invert the common-mode signal at IA

input. The output current injected to the subject counteracts the common-mode

variations, thus reducing the noise.

● The reference buffer A3 is used to reference the output signal around a predefined

voltage, which is set at the reference input pin.

In our system, the reference is set to 1.65 V (half of the Vs) with the use of a voltage

divider constituted by two 1MΩ resistors. To filter and minimize the noise caused by the

high resistors value, a 100 nF capacitor has been added in parallel with the lower resistor

of the divider. The OpAmp A1 is used to build a low pass filter, using a Sallen-Key

configuration. In this way, we can obtain a two-pole filter with a gain using only one

operation amplifier, four resistors and two capacitors. The equations of the configuration

are the following:

G = 1 + 100KΩ/100KΩ= 1 + 1 = 2 (5)

fc = 1/2π(10KΩ 33nF 10KΩ 33nF)-1 = 482 Hz (6)

With this values the system does not oscillates. In this way we obtain a cut-off frequency

of

Page 50: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

50

482 Hz, that is similar to 500 Hz. As explained before, this is the maximum frequency of

the EMG signal bandwidth. An additional pole is added to the low pass filter, constituted

by another RC coupling after the block output. A third pole ensures a 60 dB per decade

roll-off.

The resistance has a value of 3.3 KΩ and the capacitance has a value of 100 nF:

fc2 = 1/(2π 3.3KΩ 100nF) = 482 Hz (7)

The high pass filter is implemented by adding a RC coupling to the instrumentation

amplifier

IA output. It is important to reject electrode offsets (explained in the Introduction) and

cancel noise at low frequency like artefacts movement in order to avoid saturation. The

components used in the circuit are a 10 MΩ resistor and a 220 nF capacitor. Considering

the feedback architecture of the IA, the cutoff is 100 times higher than typically expected:

fc1 = 100/(2π 10MΩ 220nF) = 7 Hz (8)

It can be added a second pole to the filter and its cut-off frequency is set to 7 Hz too in

order to get a total roll-off of 40 dB per decade.

fc2 = 100/(2π 100KΩ 220nF) = 7 Hz (9)

The overall gain of the block is 200 (which allows to properly visualize and process the

signal) and the bandwidth is 7 - 482 Hz that is the bandwidth of the EMG.

Lead off detection function allows to detect if the electrodes are disconnected. If this

happens, the pins LOD+ and LOD- are set high and these signals are read by the

microcontroller, using two analog inputs.

Page 51: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

51

The fast restore function is internally implemented and can be activated by the setting of

the FR microcontroller pin. It is used to detect a saturation and reduce the duration of

settling tails of the high pass filter. If an abrupt change occurs, with this function, AD8232

adjusts automatically to a higher cut-off frequency, in order to recover quickly. The FR pin

is controlled by the microcontroller and it activates the fast restore function through an

AND port (figure 24). The function activates only if both the electrodes are connected

(LOD+ and LOD- are low) and a saturation condition is detected. This happens when the

instrumentation amplifier output approaches 50 mV from either supply rail, with the use of

the comparators. The coexistence of these conditions leads to the trigger of a circuit that

closes S1 and S2, with timing as in figure 25.

Figure 24. Fast Restore function activation circuit.

Figure 25. Timing of S1 and S2 closing during Fast Restore function.

S1 and S2 enable two 10kΩ resistor paths, the first one between HPSENSE and IAOUT

and the second one between SW and REFOUT (figure 26). These two resistors are now in

parallel with the external ones and so the cut off frequency of the corresponding high-pass

Page 52: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

52

filter is increasing (the pole is shifting). The result is that we should have a quicker settling

time after a saturation is detected.

Figure 26. Circuit and cut-off frequency shift related to the action of S1.

When S1 is closed (figure 26) there is a parallel between the 10MΩ and the 10kΩ (which,

with a little approximation, results in a 10kΩ) and the frequency shifts to 7000Hz.

fS1,AFTER = 100/(2π*10kΩ*220nF) ≃ 7kHz (10)

Page 53: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

53

Figure 27. Circuit and cut-off frequency shift related to the action of S2.

When S2 is closed (figure 27) the difference between the two configurations is not so high.

With S2 opened the second pole frequency is 7Hz (R=100 KΩ and C=220 nF), but when

the switch is closed the parallel between 100 KΩ and 10 KΩ results in a 9 KΩ resistance:

fS2,AFTER = 1/(2π*9kΩ*220nF) ≃ 70 Hz (11)

The cycle repeats if, by the end of timing, the saturation persists.

2.1.2 HVPS AND VCCS

For the stimulator part of the circuit, a voltage controlled current source (VCCS) has been

preferred to the used of a transformer, because of its low dimensions and high

performance. The high voltage power supply (HVPS) part of the circuit is used to charge

the voltage controlled current source (VCCS) part and it generates bipolar high voltage

directly from batteries. The produced high voltage is used for the stimulation current

delivery that needs to reach high values up to 100 mA, in order to activate all the muscle

in the body. In this way, from the 3 to 4.5 V supplied by the batteries, we can generate a

voltage rail (-160 to +160 V). This operation is done charging two 4.4uF capacitors to

±160V in the first 10 ms of the cycle (that will last 60 ms). To charge the capacitors we

Page 54: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

54

chose the photoflash capacitor charger LT3484-2 because of its reduced size and its

capacity to charge until 320 V. In figure 28 it can be seen the charging curve of the

capacitors. In this particular case, we charged then until 180 V (± 90 V) and at the power

on, the charging time has a value of 43 ms. Charging is accomplished and controlled by a

logic output of the microcontroller.

Figure 28. Charging of the 4.4 uF capacitors measured with the oscilloscope. Channel 1 correspond to the

positive voltage capacitor, channel 2 corresponds to the negative one. The charging time at the power on is

43 ms and the voltage goes from -90 V to 90 V.

The digital signal VPP_CHARGE is controlled and set high to enable charging. The low to

high transition that activates the charging is controlled by a feedback network. The

charged capacitors store high voltage until the needed voltage reaches 320 V (which

corresponds to its maximum limit) or the value set by HVREGLVL. This value is

generated in the microcontroller and sent to the DAC through SPI, so it can be adjusted by

the user also while the program is running (see “SPI” paragraph). HVREGLVL determines

the Vpp voltage through an isolated feedback loop.

Page 55: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

55

Figure 29. Charging circuits of the capacitors in the VCCS part of the whole circuit.

After the first charging, the VCCS storage capacitors are charged by setting

CHRGVCCS_DRIVE_ISO (digital signal) high from the microcontroller. This will let

current flow from VPP to VPPCHG and respectively from VNN to VNNCHG (figure 29).

In this way, energy required for the stimulation is transferred from HVPS to VCCS

capacitors (C46, C51, C69, C70). NPLS and PPLS are the current output of VCCS. For each

channel they need the possibility to generate a biphasic wave (as explained, a net charge

transmission would damage the tissues). This is accomplished by a multiplexer

arrangement of four solid state relays (controlled by the microcontroller) for the first

channel and similar arrangement for second channel.

Page 56: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

56

Figure 30. Interaction between the two signals related to the current amplitude (PULSE_AMPLI_CTRL) and

to the stimulation activation (PLS_CTRL_ISO).

The amplitude of the current and the start and stop of the stimulation are controlled by the

microcontroller, too (figure 30). The first one is computed in the program main cycle, sent

via SPI to the DAC and then converted into an analog value (PULSE_AMPLI_CTRL); the

second one is a digital signal (PLS_CTRL_ISO). It is important to have control over the

timing of the two impulses, which must be exactly equal (300 us). If they are not, there

will be a net charge on the electrodes different from zero.

All the timing and activation analysis will be explained in the “Stimulation Finite State

Machine” paragraph.

2.2 MICROCONTROLLER, FUNCTION, METHODS

2.2.1 MICROCONTROLLER

The microcontroller used for this system is ADuCM360 (figure 31), which is a chip with

many useful features, like two 24-bit data acquisition systems, multichannel ADCs, ARM

Cortex-M3 processor, a 8 kB SRAM and a 128 kB flash memory. There also other

peripherals integrated that can be configured by the microcontroller: UART, two SPI, I2C,

19-pin GPIO (general-purpose input/output) ports and two general-purpose timers. There

are also a 12-bit internal DAC and 11 analog inputs, selected with a multiplexer. The 11-

channel DMA controller can support SPI, UART, ADC and DAC.

Page 57: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

57

Figure 31. Block diagram of the used microcontroller (ADuCM360).

The firmware is written in C language using Keil uVision 4 and downloaded on the chip

through a 2-pin JTAG system (figure 32), which is a serial wire interface.

Figure 32. Firmware download through the use of a JTAG

In Appendix C it can be found the table that shows all the signal to/from the

microcontroller pins used for the functioning of the system. Their function will be better

explained in the next paragraphs.

Page 58: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

58

2.2.2 FIXED-POINT ARITHMETIC

During the firmware execution and running, calculations with integers can cause

under/overflow. To deal with this we can employ floating point processors. Otherwise, we

need to implement floating point in the software (with a significant amount of overhead)

or use fixed-point arithmetic.

If we use and integer type, the fractional point is assumed to be to the right of the least

significant bit. If we want to represent a number with a fractional part, we can imagine that

the fractional point is located somewhere at the left of the LSB. In this way we split the

binary code (number) in one integer part (located at the left of the assumed fractional

point) and one fractional part (at the right of the assumed fractional point), and we will see

the numbers as fractional values. The weight of each bit at the right will be always powers

of 2, with negative exponents. For example:

1011 - We assume that the fractional point is located at the left of the most significant bit.

The dec value will be: 1*2-1 + 0*2-2 + 1*2-3 + 1*2-4 = 0.5 + 0 + 0.125 + 0.0625 = 0.6875

If we move the fractional point the dynamic range and the resolution will change. Moving

the point one bit at left the dynamic range and the resolution will be divided by two;

moving it one bit at right, they will be doubled. The CPU considers this number as normal

integers, they are fractional values only in the head of the programmer. For this reason is

important to treat them all the same, each operand has to have the assumed fractional in

the same position. For this purpose we use the quick notation as explained in the

following.

To describe fractional notation we use a Qm.n naming convention: Q indicates that we are

using a fractional notation; m indicates the number of bits at the left of the fractional point

(integer part of the number); n indicates the number of bits at the right of the fractional

point (fractional part of the number).

Page 59: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

59

If we are using a signed int, this notation does not take in account the sign bit (MSB). The

dynamic range goes from -2m to 2m and the resolution is 2-n. So, for example if we consider

the following notation: Q10.5, we have a 16 bit value: one sign bit (MSB), 10 integer bits

and 5 fractional bits. The dynamic range goes from -1024 (-210) to 1024 (210) and the

resolution is 0.03125 (2-5).

Other example: Q0.31 - From -0.999 to 0.999, with resolution 2-31. In this case it is also

used the notation Q31.

If we are dealing with unsigned integers data we can compute the number of integer bits

required (m) solving the following equation:

m = floor (log2(a)+1) (12)

Where a is the floating-point number and floor rounds towards -∞. For example, if a =

4.7581:

m = floor (log2(4.7581)+1) = floor (2.250+1) = 3 (13)

If we are dealing with signed integers, we have two different equations depending on the

sign of the number, which we are interested in:

if a < 0 m = ceiling (log2(-a)+1) (14)

if a > 0 m = ceiling ((log2(a+1))+1) (15)

In this case, taking the same number used before, the result is 4 instead of 3:

m = ceiling ((log2(4.7581+1))+1) = 4 (16)

Page 60: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

60

This happens because, having a signed integer, the sign of the number is determined by the

most significant bit.

If we multiplicate two Qm.n numbers we must consider that the result will have a double

number of bits. If we want to keep the same notation we must shift the result to right. Then

if we have signed variables, the result will have two sign bits, but we need only one of

those.

The number of bits needed for the fractional part of the number (n) can be found starting

from the resolution (r). The equation is the following:

n = ceiling (log2(1 /r)) (17)

If our number is 4.7581, the resolution is r = 0.0001 and so n can be computed in this way:

n = ceiling (log2(1 /0.0001)) = 14 (18)

In every case the sum of m and n must be equal to the word length of the variable. So if we

need to use floating points numbers with high range and resolution, 32-bit integers

variables can be used for our algorithms.

When doing operations with fixed-point variables, we must be careful to shift and align the

decimal places. Overflow is another issue we must take in consideration. In this case, we

could save the result in variable with a greater word length and then check to see if it

exceeds the total number of bits that we want. This problem is more relevant when we

multiplicate two fixed-point variables. With a multiplication the number of bits of the

result (both m and n) is equal to the sum of m and n of the operands. Then, if we want to

maintain the same Q format, we need to adequately shift the result.

Page 61: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

61

This method in very useful during the digital signal processing, when Infinite Impulse

Response filter are used. The filter coefficient are floating point numbers lower than one

and using the fixed-point arithmetic we can do the right calculation shifting the variables

in the right way.

2.2.3 UART

In our system UART communication (see Appendix B for a technical explanation) is used

to transfer data from the microcontroller to the Bluetooth module. We set a baud rate equal

to 115200 bps, an 8-bit data packet and no parity bit (with only one stop bit). This is a very

important task, because it allows the communication between the device and the host

(Android app). The communication is obviously used also to configure and program the

Bluetooth (setting the name, reset, etc). In every cycle there is a polling on a variable or on

the button and this functions can be activated. First of all, to enter the command mode we

have to write to the UART transmission register a “+++” string and then, we can send the

commands to do the operations we want to. Bluetooth needs to be reset if there is an

absence of communication with the host. While we are in command mode, we must

remember to pause the program and disable all the interrupts.

2.2.4 SPI INITIALIZATION AND USE

In our system SPI (see Appendix B for a technical explanation) is used to transfer the

values corresponding to the stimulation current amplitude and to the high voltage power

supply from the microcontroller to the Digital to Analog Converter (AD5592 ADC/DAC).

We decided to use SPI for this kind of communication because we needed a simple and

synchronous communication between two elements placed at short distance. First of all,

we needed to initialize and configure SPI0, because the microprocessor that we used has

two different SPI buses, but we needed only the first one. For our communication we set

two-byte Rx and Tx registers size, because the words received and elaborated by the

peripheral used were composed by 16 bits. In this way the Tx interrupt occurred when two

bytes had been transferred and the Rx interrupt occurred when two bytes had been

Page 62: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

62

received. The transfer began automatically with a write on the Tx register on the Master

side and new received data were always overwritten in the Rx register. Continuous mode

was enabled, so that the transfer was stopped only when there was no valid data in the Tx

register. CPOL was set low and CPHA was set high (so that serial clock pulsed at the start

of the first data bit). Finally we set a 1 MHz rate clock.

Before each write on the Tx register it was important to flush the FIFOs (First In First Out

registers) and after the transfer we had to wait at least 200 us before we could write again.

In the implemented functions we always did two different 8-bit writes or reads, in order to

activate the Tx interrupt after the second byte was transferred. As previously described,

with this configuration we received data in Rx register every time we sent something with

a write in Tx register. For this reason when we needed to read data from the peripheral, we

sent to it a NOP command (“0x00” value) so that no operation was done, but we received

the data that we were interested in.

AD5592

AD5592 (figure 33) is a 8-channel configurable 12-bit ADC/DAC. It has 8 I/O pins that

can also be configured as general purpose input or output digital pins. It can be configured

and controlled using serial peripheral interface (SPI).

Page 63: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

63

Figure 33. AD5592 block diagram with all its components.

The input shift register has a 16-bit size. Depending on the received MSB, there will be a

write operation to the control registers (if MSB=0) or on the DAC channel. The address of

the register or the channel are selected depending on the value of the next three bits. The

remaining bits will determine the operation to be done or the value to be converted by the

DAC on the selected channel.

During the initialization of the system, after a reset of AD5592, we configured two pins as

DAC outputs (IO0 for the high voltage level and IO4 for the stimulation current

amplitude) and three pins as ADC inputs (IO2, IO5, and IO6, used to have a feedback on

the high voltage values). We preferred setting a continuous ADC sequence repetition

(figure 34), including the three pins that we were interested on. In this way with every

write operation (even with a No Operation command), the analog values read from the

previous selected three pins and converted by the ADC, are sent to microcontroller via the

SPI MISO line. It is important to notice that it takes 16 clock oscillations (corresponding

to the 16 bits of the received command) for the conversion. The digital converted value

will be sent to the microcontroller during the next write operation. For this reason is very

important to coordinate the write operations in order to receive the converted data only

when they are needed.

Page 64: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

64

Figure 34. Continous ADC conversion from different channels.

When the result from an ADC conversion is received by the microcontroller it’s very

important to split the value: the four most significant bits identify the channel that we are

reading from, while the remaining 12 bits represent the real digital value resulting from the

conversion.

After the configuration and the pin setting, the microcontroller sends data to AD5592 to

control the values corresponding to high voltage power supply and stimulation current.

This data are sent through a function, whom inputs are the value to be sent and the address

of the AD5592 DAC output we want to write on. Before writing the data to the Tx register

it is important to verify if the input variable is a 12-bit value higher than zero. For this

reason we implemented also a control function that sets the value equal to zero if it is

negative and sets the value equal to 0xFFF (highest 12-bit value) if it has more than 12

bits. In these cases an error flag in the error variable is set. After this control the value to

be sent and the address are combined in a 16-bit data (with the address bits placed in the

position of the four most significant bits) and can be written in the Tx register. The written

value is combined in this way:

Page 65: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

65

• D15: 1 (DAC write mode);

• D14-D12: 100 or 000 (3-bit pin address);

• D11-D0: 12-bit value to be

sent.

When the function is called, the right variable is selected by the analysis of the first four

most significant bits, which contain the information about the address. If we want to

change the high voltage power supply value, the user will set the HVValue variable in

Volts. This value is then converted (figure 35) before the 12-bit control, with a gain

(14.2857143) and an offset (-114) computed through a linear regression. The gain is a

floating point number, so we used fixed-point arithmetic and we chose a bigger value

(468114) and then shifting it to right (>>15). This shift operation is equivalent to divide

the number by 215 = 32768. The value is computed in the following way: 468114/32768 =

14.2857143. In this way after the multiplication the final result corresponds to the right

value, without using floating point variables. We must remember that there is the 12-bit

limit and the maximum allowed input is 4095. This value corresponds to 294 V.

Figure 35. Relationship between the uC value and the Volt value regarding the high voltage power supply.

The black line corresponds to the limit HVPS value of 294 V.

If we want to change the stimulation current value, the aIAmp variable must be set in tens

of mA. In this way, the user can better adapt and control the current value, avoiding great

“jumps” of one mA. The conversion (figure 36) gain is 0.9091 (so we multiplicate the

Page 66: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

66

value by 931 and the shift the result right by 10 bits), while the offset is 158. This time,

before the conversion, there is another control, that limits the maximum value of the

current. This limit (IMaxLimit) is initialized to 50 mA, but it can be eventually changed

(not by the user himself). It is important to notice that this is not the IMax value set in the

piecewise linear function during the digital signal processing, but it is another control to

avoid the dispense of high current values to the user.

Figure 36. Relationship between the uC value and the mA value regarding the stimulation current amplitude.

2.2.5 TIMERS AND TIMERS INTERRUPTS

In our application timing is very important, because we want the stimulation pulses to have

a predefined and fixed duration. ADuCM360 contains two identical general purpose timers

and they are referred as Timer0 and Timer1. They are 16-bit count-up or count-down

timers and they can be clocked from four different clock sources (system clock UCLK,

peripheral clock PCLK, internal oscillator LFOSC or external crystal LFXTAL) and

scaled down using a prescaler of 1, 16, 256 or 32.768 (figure 37).

Page 67: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

67

Figure 37. ADuCM360 timers block diagram.

The value of a counter can be read at any time by accessing its value register (TxVAL).

Timers can be used in two different modes. In Free Running Mode, the timer increments

from zero to full-scale value or decrements from full-scale value to zero (depending on the

counting mode). We have 16-bit timers, so the full-scale value corresponds to 65535 (216 -

1). In Periodic Mode we can choose a value that must be written in the load register and,

depending on the counting mode, the timer increments from this value to full-scale or

decrements from the value to zero (and then begin again from that value). The timer is

started by setting the enable bit to 1.

Every time the counter reaches maximum or minimum value, an interrupt is generated,

which can be cleared setting the time clear interrupt register to 1. After that, the timer will

begin to count again depending on the configuration values written in his registers.

In our system we used both timers: Timer0 was used to count the time (in milliseconds)

passed from the activation of the device; Timer1 was used to regulate the timing of the

different stimulation pulses.

For Timer0 we used the 16 MHz internal clock with a prescaler of 16. In this way we had a

1 MHz counter and periodic count-up mode was set, so that we could load it with the

needed value in microseconds. The loaded value correspond to 1000, so that an interrupt

generated every millisecond. In the interrupt function, after the interrupt flag is cleared, we

increased the millisecond counter and other counters related to the functions of the device

led and button. Timer0 is started during the main initial setup of the program.

Page 68: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

68

For Timer1 we used the 16 MHz internal clock with a prescaler of 16 too, but this time we

also enabled the reloading of the counter from the reload register. This is important

because we want to choose every time the reload value of this timer and it could be

different depending on the duration of the stimulation pulses that we wanted. In the

interrupt function (see in “Finite State Machine” paragraph) and so the time after which

the next interrupt generated could be different for every state called during previous

interrupt function. The values were always taken from an array of predefined values and

loaded in every state to set the duration of the next one. Timer1 is started every time we

reset the finite state machine (after the initialization of the system and during every main

cycle).

2.2.6 FLASH MEMORY

While the device is running, it may be useful to save some data on the microcontroller

flash memory, such as the stimulation parameters so that the user has not to change all the

variables every time he turns the device on.

The ADuCM360 contains 128 kB of flash memory, 2 kB of information space and a flash

controller to do all the operation on the memory (figure 38).

Figure 38. Organization of the flash memory.

Page 69: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

69

The top 20 Bytes of the flash are not available for writing and reading; if the user tries to

read from and write to there an error is returned.

A write to the flash is enabled by setting high the WREN pin in the Flash Memory Control

Register. In this way flash protection is disabled and the processor is disconnected from

the flash until the operation is done. It is important to clear the WREN pin after the write

operation. A single location can be written only two times without an erase and a write of

a page takes 3.04 ms. The erase operation can be done in two ways: a mass erase erases all

the user flash memory; a page erase erases the 512-byte page selected in the Page Address

0 registers. To start the operation we need to set high the page or mass erase bit in the

Controller Commands register. An erase operation takes 21 ms to be completed.

In our system a predefined number of values are saved into the flash memory and they

correspond to the stimulation parameters (threshold, gain, maximum and minimum current

values and blanking intervals). The saved values are read from the flash memory during

the initialization of the system and saved automatically in the right array variables. When

the microcontroller is programmed for the first time it is important to remember not to

read these values, because there are no data saved on the flash memory. We can enable

this command only after the first write. The write operation can be done by pressing the

led button for more than two seconds. The led will become orange and after the write

operation will be done it will change its colour back to green. The whole operation

consists in a memory page erase (to erase the old values saved before) and then in a write

to the same address. The microcontroller writes to the memory the actual values of the

predefined variables, so that when the device will be turned on next time, it will be

initialized with those values that will be read from the memory and saved in the right

arrays. In this way the user can choose a favourite set of stimulation parameters value and

change them whenever he wants to.

The write, read and erase operation are done always to the same address (0x8000). We

chose this value because it is included in the flash memory space (from 0x00000 to

Page 70: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

70

0x1FFFF) and it is more than sufficient to save the program (from 0x0000 to 0x3F00) and

other data. We can do this because the flash memory can be erased and rewritten again

thousands times without creating problems. During any operation it is important to disable

all the interrupts to avoid the abort of the flash write/read/erase commands. The interrupts

are enabled again at the end of the operation after a short (half second) wait cycle.

After some tests, we decided to save in the flash memory also the counters that contains

the information about the amount of time passed since the device has been turned on and

while it is stimulating. Each counter is increased during each cycle if the stimulation

current is within a certain interval. Every five minutes the new values are overwritten to

the flash memory at the predefined address 0xA000. This values can be reset and allow us

to know precisely the duration of the batteries and how long the device has been used.

Before writing the new values, the page is always erased, so for a little amount of time

(between the erase and the new writing) the values on flash corresponds to the default

ones, which are 0xFFFF. If the whole device is switched off after the erase and before the

writing, when we switch it on again, the read and saved parameters value will be 0xFFFF,

that leads to a negative number (because we are dealing with integers and the MSB

corresponds to the sign bit). This is a very critic aspect, because it would generate a fixed

stimulation current equal to the maximum limit imposed (that is 50 mA) without any

activation and control from the patient. This happens because IMIN is equal to 0xFFFF, so

the output current increase to the maximum value.

We solved this problem controlling the values after the reading from flash. If one of the

values is negative, we know that something went wrong during the last writing, and the

stimulation parameters are set equal to some default values. After that, these values can be

saved again on flash by pressing the button for more than two seconds, without switching

off the device until the led has become green again.

Page 71: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

71

2.2.7 LED

Besides the on/off button, the device has also another button with a led. The led (figure 39)

is directly controlled by a digital pin of the microcontroller and it is a two-colour led

(green and red).

Figure 39. Structure and working principle of a two colour led.

The different states are implemented in the following ways:

● Off state: the controlling pin is configured as input.

● Green state: the controlling pin is configured as output and it is cleared.

● Red state: the controlling pin is configured as output and it is set.

● Orange state: the controlling pin is configured as output and, by the setting of a flag

variable, it is toggled in the Timer0 interrupt. In this way the led changes state from

red to green and vice versa every millisecond and the human eye sees it as orange.

● Blinking Green: we increment a counter every cycle. When it is lower than a

threshold, controlling pin is configured as input (led turned off); when it is higher

than the threshold the pin is configured as output and cleared (green). At the

reaching of another threshold, counter is reset and the led cycle can begin again. In

this way the led will blink, changing state with a frequency chosen by the

threshold.

Page 72: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

72

● Blinking Red: we increment a counter every cycle. When it is lower than a

threshold, controlling pin is configured as input (led turned off); when it is higher

than the threshold the pin is configured as output and set (red). At the reaching of

another threshold, counter is reset and the led cycle can begin again. In this way the

led will blink, changing state with a frequency chosen by the threshold.

These states can be selected with an enumerated variable and their name can be: Off,

Green, Red, Orange, BlinkGreen, BlinkRed. Thresholds for the blinking states are 40 and

50, so that, during this states, the led will be turned off for 2.4 seconds and turned on for

0.6 seconds.

During the normal functioning of the device led is turned on in green state. The colour

changes when button is pressed for operations like flash memory writing (orange state)

and Bluetooth reset (red state). After the end of this operation the led becomes green

again.

2.2.8 BUTTON

In the main while cycle there is a function to check if the button has been pressed. The

button is linked directly to a digital input of the microcontroller and if it has been pressed

the program waits until it has been released. Meanwhile, by the setting of a flag variable in

this wait cycle, a counter in the Timer0 interrupt (called every millisecond) is increased, so

that the system knows the time passed between the press and the release of the button.

After that, there are different operations that can be done depending on the time passed

and saved in the counter variable. If the button has been pressed for more than two

seconds, the new stimulation parameters are written (the led becomes orange during this

operation) to flash memory; otherwise, Bluetooth is reset (the led becomes red). At the end

of all the operations caused by the press of the button, the led colour changes back to

green.

Page 73: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

73

2.3 FIRMWARE AND CYCLE

2.3.1 MAIN PROGRAM CONFIGURATION

The first operation performed by the program after the start of the system is the

configuration of the digital pins. The ADuCM360 has two ports (Port0 and Port1)

containing eight general-purpose bidirectional input/output (GPIO) pins and one port

(Port2) containing 3 GPIO pins. Each one of them can have multiple functions, all

configurable by the user (figure 40).

Figure 40. General Purpose Input/Output (GPIO) pin block diagram.

Each GPIO can be configured as input, output or open circuit and they are functional over

the supply range (IOVDD = 1.8 - 3.6 V). GPIO pins have an internal pull-up resistor that

can drive 1 mA. These pull-ups are disabled if GPIOs are configured as output and open

circuit and can be enabled or disabled by the user when they are configured as input.

The pins are configured through a write to the GPCON register. In our case they are all

configured as digital I/O, with the exception of two pins in the Port0 (configured as

UART) and four pins in the Port1 (configured as SPI0). After this first step, digital I/O

pins have to be set as input or output. To make this operation, a write to the GPOEN

register is needed (if a bit is set high, the corresponding pin will be set as output). The only

Page 74: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

74

pin set as input is the one linked to the button (P0.5), while all the other ones are set as

output. The configuration of all the three ports is shown in tables 1-3.

PORT 0

GP0CON register value: 0x403C

GP0OEN register value: 0xDD

Signal CHRGVCCS

DRIVE

CMD

MLDP

SW

CTRL

EN2

CH0

WAKE

SW

UART

TX

UART

RX

PLS

CTRL

Pins P0.7 P0.6 P0.5 P0.4 P0.3 P0.2 P0.1 P0.0

Configur. I/O

Out

I/O

Out

I/O

In

I/O

Out

I/O

Out

UART

_TX

UART

_RX

I/O

Out

GP0CON 0b01 0b00 0b00 0b00 0b00 0b11 0b11 0b00

GP0OEN 0b1 0b1 0b0 0b1 0b1 0b1 0b0 0b1

Table 1. Port 0 configuration

Page 75: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

75

PORT 1

GP1CON register value: 0xAA00

GP1OEN register value: 0xEF

Signal SPI

CE

SPI

MOSI

SPI

CK

SPI

MISO

LED

CTRL

EN2

CH1

EN

CH0

EN

CH1

Pins P1.7 P1.6 P1.5 P1.4 P1.3 P1.2 P1.1 P1.0

Configur. SPI SPI SPI SPI I/O out I/O out I/O out I/O out

GP1CON 0b10 0b10 0b10 0b10 0b00 0b00 0b00 0b00

GP1OEN 0b1 0b1 0b1 0b0 0b1 0b1 0b1 0b1

Table 2. Port 1 configuration.

Page 76: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

76

PORT 2

GP2CON register value: 0x0000

GP2OEN register value: 0x07

Signal ///// ///// ///// SWD SWCLK EN ST EN INA

SUPPLY

VPP

CHARGE

Pins ///// ///// ///// P2.4 P2.3 P2.2 P2.1 P2.0

Configur. ///// ///// ///// SWD SWCLK I/O out I/O out I/O out

GP2CON 0b00 0b00 0b00 0b00 0b00 0b00 0b00 0b00

GP2OEN 0b0 0b0 0b0 0b0 0b0 0b1 0b1 0b1

Table 3. Port 2 configuration

After the GPIO configuration it is important to set some of them (and clear the others) to

power on only the right parts of the circuit. We set EN_ST that powers the stimulator

analog circuits on VCCS and EN_INA_SUPPLY that powers the conditioning analog

circuits.

After that we initialize the protocol communication with host and disable the clock to

unused peripherals (because they would cause the performing of unnecessary operations),

leaving enabled only Timer0, Timer1 and SPI0 clocks. Also UART is initialized at this

point. The baud rate is set to 115200 bps, the data length is 8 bits and we set only one stop

bit. After UART, we start Timer0 (with a 1 ms count) and we enable all the needed

interrupts (ADC, DMA, Timer0, UART). Timer1 is started during the reset of the Finite

State Machine, which will be explained later. We need also to initialize the internal DAC

that is used to set INA fast restore: we use AVDD reference in order to have a 0 - 1.8 V

Page 77: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

77

output range and a 12-bit mode. In this way, the signal can reach 1.8V and INA FR pin

needs a 1.35 V input to be activated. ADC0 and ADC1 are both ground-referenced and

referred to the pins AIN10 and AIN4, which correspond to the two INA output. DMA are

set in order to transfer data read from ADC0 and ADC1.

Figure 41. Flowchart of the main configurations and initializations.

SPI0, used to communicate with external ADC/DAC AD5592, is initialized with the

configuration explained in the SPI paragraph, as also AD5592 itself, with its inputs,

outputs and ADC continuous sequence. The last operations before the main cycle starts are

dedicated to the Finite State Machine Reset (in order to start Timer1 and the stimulation

cycle itself), the setting of the operation mode and the lighting of the green led, which

indicates that the device is on and working.

2.3.2 MAIN CYCLE

Figure 42. Flowchart of the main cycle.

Page 78: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

78

ACQUISITION

After the analog conditioning (amplification and filtering operations), the EMG signal is

acquired by the microcontroller through two ADCs (one for each input channel). For this

operation, Direct Memory Access (DMA) is used. DMA is a method used to speed up the

operations, which does not involve the CPU. In this way, an input/output device can send

or receive data directly to or from the Random Access Memory (RAM). DMA allows the

CPU to perform other operation while the data are being acquired (figure 43). This is a

very important feature that allowed us to save a great amount of time.

Figure 43. DMA working principle. Thanks to the DMA controller, the data from a peripheral are

transferred directly to the RAM.

The ADCs have been configured during the main initialization and during every cycle,

EMG sampling is started by the call of a function, which first performs a re-configuration

of the ADCs control registers and the DMA setup up. In this way, we refer DMA to ADC0

Page 79: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

79

and ADC1 and we choose the number of values to be transferred and the destination

address. In our case, during every cycle, 110 samples are acquired and transferred to two

predefined arrays (one for each channel). The sampling frequency is 1956 Hz, which is

more than the highest frequency in the acquired signal. After the setup, the continuous

conversion is started. When the data transfer is complete, there is a DMA interrupt for

each ADC (ADC0 and ADC1) that re-configures ADC control registers and disables DMA

requests from peripherals, stopping DMA.

DIGITAL SIGNAL PROCESSING

Digital signal processing is one of the central and more important part of the firmware.

After the analog conditioning (filtering and amplification), the acquired signal is processed

and analysed, in order to measure the activation level of the interested muscle. The value

resulting from the processing is used to set the current amplitude of the stimulation, so it is

very important to cancel all the noise that could still affect the recorded signal once that he

has been acquired. These artefacts are caused by the very high stimulation current, the f-

wave, the activity from other muscles and the movement artefacts. The goal of the signal

processing is to obtain one single value from the 110 samples acquired during every cycle

and saved in the array and so it is divided in different filtering (both low pass and high

pass) and analysis steps.

HIGH PASS FILTER

The first noise we want to cancel is caused by the low frequency movement artefacts

(figure 44). We saw that, when the user was moving body segments not interested in the

hand functions (for example the lower limb), the signal was affected by great amplitude

offset, that caused the activation of the stimulation. After recording and analyzing it, we

could differentiate this noise from the EMG because it has low frequency (<40 Hz), while

the EMG has high energy at higher frequencies (>100 Hz).

Page 80: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

80

Figure 44. The EMG signal recorded while the subject was moving also his legs (blue) presents some offsets

and it has a greater amplitude (because of movement artefact); the red signal represents the EMG signal

recorded without any other movements.

To solve this problem we implemented an Infinite Impulse Response (IIR) high pass filter.

IIR filters are LTI (linear time invariant) systems and its impulse response continues

indefinitely, without becoming zero after a certain point. It is composed by two blocks: the

first one recalls the FIR filter structure with the delays, while, in the second one, the output

signal is delayed, weighted and used again as input. The two blocks function are the

following:

N

v(t) = ∑ ci x(t − i) (19) i=0

M

y(t) = − ∑ bi y(t − i) + v(t) (20) i=1

Considering the fact the we implemented the filter in C programming language and that

the microprocessor could not perform too many operations (to save time), we decided to

implement a first order high pass IIR filter with a single coefficient, based on this equation

(where sn are the input and x n the output values):

Page 81: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

81

xn = α (xn-1 + sn - sn-1) (21)

The filter coefficient has been computed starting from the values of the sample and cut-off

frequency. In our case fs is equal to 1956 Hz, while fc can be chosen between 30 and 80

Hz. We chose fc equal to 70 Hz because we have seen that, with this value, all the low

frequency artefacts are cancelled and the EMG signal is well visible and it can be

processed:

α = fs / (2π f c + fs) = 0.816 (22)

During the firmware implementation, we did not use floating point variables, so, in order

to realize a filter with a coefficient lower than 1, we used fixed-point arithmetic principles,

shifting the obtained value to divide it and get the right result.

Figure 45. Effect of the IIR HP filter on the raw signal.

During the program running, this high pass filter can be enabled or disabled through the

change of the operation mode (using the mode variable that will be explained later). In

order to fully understand the efficacy of this filter we did some tests where we recorded

the EMG signal in presence of other movements and we processed it with and without the

filter.

COMB FILTER AND BLANKING

Page 82: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

82

The recorded EMG presents also the signal from the stimulated muscles in addition to the

activity of the muscles we are interested in. For this reason is important to remove the high

stimulation noise itself, applying a linear filter. Adaptive filters can be used, but it was

found that signal to noise ratio (SNR) improvement is comparable using an adaptive filter

and a Finite Impulse Response (FIR) filter [Sennels et al. 1997]. We decided to use a first

order FIR filter considering that requires minimal computation and it is easy to implement

through C language. We must remember that every cycle lasts 60 ms, resulting in a 16.6

Hz frequency. In this way, the implemented comb leads to two advantages: the

suppression of both stimulation (and other physiological noise) and 50 Hz hum (16.6 Hz is

a third of the main frequency). For the implementation, the 120 samples saved during

every cycle are subtracted from the values of the samples of the following cycle (bl is the

number of samples acquired during every cycle):

yn = x n - xn-bl (23)

Figure 46. Effect of the FIR comb filter on the signal.

Using this filter we are able to cancel stimulation artefacts (both m and h wave) and the 50

Hz hum, but other variable noise is not cancelled. For this reason we had to implement

also a blanking of some samples. This may be useful to cancel the f wave, which is not

always equal and other variable artefacts, like the noise caused by the functioning

(opening and closing) during every cycle of the solid state relays in the VCCS part of the

circuit. For this reason, at every cycle, there are two intervals of the acquired samples that

are set equal to zero. Depending on the stimulated muscle, the second interval could also

not be blanked. The intervals can be chosen by the user, but in the default case,

Page 83: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

83

considering that the stimulation lasts less than 1 ms, the first 20 samples (10 ms) are

blanked:

yn = 0 if (t0 < t < t1) or (t2 < t < t3) (24)

Figure 47. Effect of the blaking on the signal.

RMS VALUE COMPUTATION

After the applied filters and the blanking, we need to estimate the MUAP activity. Like

explained in the “Introduction”, both RMS and AVR are proper indexes to measure

MUAP activity. We decide to use RMS because it emphasizes samples with high

amplitude. There are also more complex methods, like autoregressive models or neural

networks, but their advantages does not match the need for computation. The block of

samples used are the samples between two consecutive stimulation pulses. RMS

computation has been done implementing two different functions: the first one calculates

the dot product between the same sample values in the array (that is like) and the second

one makes a 64-bit square root of the obtained value. The RMS is computed over each

block, so from the 110 samples of the array, we get a single value that estimates the

MUAP activity.

z = RMS(y) (25)

Finally, a first order Infinite Impulse Response (IIR) low pass filter is applied to the

obtained RMS values. The input of the filter is the new RMS value and the previous

output is taken back as an input, too. The implemented IIR filter has one coefficient and

the equation is the following:

Page 84: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

84

mn = α*(z -m n-1) + mn-1 (26)

Where mn is the new output, mn-1 is the old output, z is the value obtained from the RMS

calculation and α is the filter coefficient. Once again, the needed α would be a floating

point number lower than 1, so we used fixed-point arithmetic theory to implement the

filter. The defined coefficient has a very high value (it is in Q31 form) and after the first

multiplication, the result is shifted right in order to get the real value using only integer

values. α is very high for the first five seconds after the device is powered, because during

the first iteration xn-bl is equal to 0, so y is very high. This leads to a great RMS value when

we start the program and, because of the filter, it takes some seconds to reach the standard

values. For this reason, if z (RMS value) is much higher than the values we expect during

the muscle contraction, α coefficient is reduced, so that no big variation (caused by an

error) is introduced in the signal. After five seconds the values are all settled, so α is set

higher, in order to have fast variation in the computed RMS and stimulation current, when

the muscle is contracting and the EMG amplitude is higher.

PIECEWISE LINEAR FUNCTION

The obtained m value is used to determine the stimulation current amplitude through the

use of a piecewise linear function (figure 48). If the value is lower than a threshold, the

stimulation current will correspond to IMIN that is usually equal to zero. We can increase

this parameter if we want to stimulate the muscle also without EMG activation. If m is

higher than the threshold, the current amplitude will increase with a defined gain. For

safety reasons, the amplitude is limited by IMAX, so the equations of the function are the

following:

IAMP = 0 if m < threshold

IAMP = G*(m - threshold) if m > threshold (27)

IAMP = IMAX if m: I > IMAX

Page 85: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

85

In this way, we obtain the proportional control and the user can change these parameters

using the app, to adapt the stimulation to his needs and perform every task. Between the

changeable parameters, the most critical for safety reasons is IMAX, that could be

inadvertently set to a very high value. This could be very dangerous for the user, so in the

function that converts the current amplitude, there is another control that limits the

maximum value of the current. This variable is set to 50 mA and it can be changed by the

programmer, but not by the user, so that there are no damages to him/her while the device

is working.

Figure 48. Piecewise linear function: relationship between the computed value m and the current amplitude.

The explained process is done separately on the data acquired from both the input channels

and, during normal operation mode, the current amplitude computed with data from the

first input channel is delivered from the first output channel (as the other channel,

respectively). But if we want to stimulate a single muscle as consequence of the

contraction of more than one muscle, we can change operation mode and sum up the

computed current amplitude from both the input channels, delivering it from only one

input channel (the first one). This different operation mode can be set by the user changing

a mode variable (its functioning is explained later).

Page 86: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

86

In figure 49 are represented all the steps that form the digital signal processing.

Figure 49. Schematic representation of the whole digital signal processing.

Page 87: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

87

STIMULATION FINITE STATE MACHINE

After the signal processing and the computation of the current amplitude value, the

stimulation must be delivered to the tissues through the electrodes. This is the main

function of the device and it is critical for many reasons. First of all, the waveform and the

timing of the stimulation must be correct, in order not to damage the user’s tissues. The

stimulus consists in a biphasic square wave, where every part lasts exactly 300 μs (figure

50). The operation must be done for both the channels, so the total duration will be 2.1 ms.

Figure 50. Waveform and timing of the stimulation for the two channels.

In order to reach this result, we implemented a Finite State Machine (FSM), which is an

abstract machine always present in one of a finite number of states. Every time the FSM is

called, it will have a transition to the next state, performing different operations until its

reset. In this way we could start and stop the stimulation with a high timing accuracy and

set the channel and the direction of the current, activating in different ways the solid state

relays. The other states of the FSM are used to set or reset the digital signals needed to

control the charging of the capacitors in the HVPS and VCCS part of the circuit and to

acquire and read the feedback data from AD5592 ADC via SPI.

In order to assure an accurate timing, the FSM is called during the Timer1 interrupt. In

every state the timer is reloaded for the next one, so that each state could last more (or

less) than the others. The reloading values are saved in an array and they obviously cannot

be modified by the user. By default, the reload value is 300 μs for all the states, but it is

Page 88: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

88

really important to have this fixed value only in the states related to the stimulation

delivery.

The FSM is divided in 15 states

(figure 51) and it is reset after

the configurations at the power

on and during every cycle (60

ms). In this way, the stimulation

frequency is equal to 16.6 Hz,

which allows to produce a

continuous force without

leading rapidly to muscle

fatigue. The implemented

function presents one input

parameter, which determines the

operations to be done: if we

decide to reset it, the variable

referred to the state is set equal

to the first state; in the other

case, the operations done

depend on the state saved during

the previous call. In every state,

the variable is set equal to the name of the next one, so that there is an increasing

succession of the state number, until the last one. In the last state, the variable is not

changed anymore. So, a reset call of the function is needed to restart the FSM. In this way,

we are sure that the stimulation wave is delivered only once in every cycle, because if the

function is called after the achievement of the last state, it will repeat the operation in it

(the variable is not changed anymore), which is a simple reset of a digital signal, as it will

be explained.

In the first states we deliver the stimulation current. Each state is used to set the amplitude

value, the channel and the current verse and the start/stop of the stimulation. The amplitude

value, after the computation at the end of the digital signal processing, is sent to AD5592

Figure 51. Evolution (in the Timer1 interrupt) and reset (in the

main module) of the finite state machine used to deliver the

stimulation.

Page 89: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

89

DAC via SPI and, after the conversion, it corresponds to the signal

PULSE_AMPLI_CTRL. The channel and the current verse are controlled by the eight

solid state relays (four for each channel) the digital signals, which are activated by the

microcontroller digital signals EN_CH0, EN_CH1, EN2_CH0 and EN2_CH1. Finally, the

start and stop of the stimulation is controlled by the microcontroller digital signal

PLS_CTRL. In the first state we set the current amplitude for the first channel and the mux

to have a positive wave. In the next states we start the stimulation, stop it, change the mux

to have a negative wave, then start and stop the stimulation again. These operations are

done again for the second channel (figure 52).

Figure 52. Timing of the different signals used for the output current delivering at every state.

After the stimulation stops, the last states are dedicated to the acquisition and reading of

the feedback data from AD5592 ADC via SPI. As explained before, during the main

configurations we choose the sequence of ADC channels to be read continuously. After a

delay of 2 SPI write operations (which are made in the initialization), every SPI write will

cause an ADC conversion which can be read or not. At the end of each stimulation, data

Page 90: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

90

are read from AD5592 AD conversion. First of all we do a dummy read to clear the SPI

Rx register (state 10) and then we do a three consecutive NOP write and read to be sure to

read from each channel (states 11-12-13). The obtained data are put in the right variable of

an array with a function, which compares the address of the received data with the saved

constant of the three channel address. The four MSBs of the received value indicate the

pin address of the converted value, whereas the last 12 bits represent the data itself.

In the FSM we control also the digital signals related to the charging of the HVPS

(VPP_CHARGE) and VCCS (CHRGVCCS_DRIVE) capacitors (figure 53). They need to

be charged at the right time in order to make the high voltage available during the

stimulation phase. VPP_CHARGE is set high after we stop the stimulation (state 10) and

set low before its start (state 0). CHRGVCCS_DRIVE is set high after VPP_CHARGE

(state 11) and set low before it (state 14).

Figure 53. Timing of the signal used to charge the capacitors in the HVPS and VCCS parts of the circuit

during the different states.

In table 4 all the states are indicated with their name, timing and different operations. In

each state (without considering the last one), we also reload the timer and change the state

variable name, to go to the next one.

Page 91: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

91

STATE NAME TIME (us) OPERATIONS

SetMUXseBseA (0) 0 (t0) Disable VPP_CHARGE

Set channel 1, positive wave

Set channel 1 current amplitude

Dummy1 (1) 300 (t1)

Nothing, time passes

StimONseBseA (2) 600 (t2)

Stimulation on

SetMUXseAseB (3) 900 (t3) Stimulation off

Set channel 1, negative wave

StimONseAseB (4) 1200 (t4) Stimulation on

SetMUXseDseC (5) 1500 (t5) Stimulation off

Set channel 2, positive wave

Set channel 2 current amplitude

StimONseDseC (6) 1800 (t6) Stimulation on

SetMUXseCseD (7) 2100 (t7) Stimulation off

Set channel 2, negative wave

StimONseCseD (8) 2400 (t8) Stimulation on

Page 92: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

92

StimOFF (9) 2700 (t9) Stimulation off

DummyADCRead (10) 3000 (t10) Enable VPP_CHARGE

SPI NOP + Dummy Read (to clear RX register)

ADC_CH1 (11) 3300 (t11) Enable CHRGVCCS_DRIVE

SPI NOP + Read and saving of first ADC value

ADC_CH2 (12) 3600 (t12)

SPI NOP + Read and saving of second ADC value

ADC_CH3 (13) 3900 (t13)

SPI NOP + Read and saving of third ADC value

CHRGVCCS_DIS (14) 4200 (t14)

Disable CHRGVCCS_DRIVE

Table 4. Operations done in each state of the FSM

Page 93: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

93

COMMUNICATION WITH HOST

Figure 54. Schematic principle of the communication between the device and the host

(tablet/smartphone or computer)

The last operation of the main cycle consists in the communication with the host. A

computer app (used for test purposes) and an Android app, which can be run on a tablet,

were been developed (figure 54). Both the apps can be used to control the stimulation

parameters and to display the acquired EMG signal. The device communicates with the

host via Bluetooth V3.0, using the module WT12-A (figure 55). The data transfer between

the microcontroller and the module is based on UART communication. First of all the

module has been initialized and configured (as explained in the “UART” paragraph). After

that, at the end of each cycle, first we send the new values changed during the cycle,

writing them on the UART Tx buffer, and then we read from the Rx buffer and save in the

interested variables the new values that have been changed from the app.

Figure 55. UART communication between the microcontroller and the WT12-A Bluetooth module and

Bluetooth communication between the module and the host.

Page 94: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

94

The transmitted parameters related to the stimulation are the current level, the threshold,

the gain, the maximum and minimum current value. The current level needs as visual

feedback that allows to know what the amplitude value is at the moment. The user can

change the other values in order to adapt them to personal specific tasks. In this way the

same circuit is suitable for all the subjects, which can regulate and adapt the stimulation to

themselves. There are also other variables that are transmitted for test purposes or to

change directly from the app some operation modes. The app has different functioning

modalities (depending on who is using it at the moment) and some variables can be seen

and changed only if it is running in “Programmer mode”. In this way, some important

modifications can be done only by an expert (for example the programmer), while the

stimulation parameters and the acquired EMG can be seen also by the subjects. In table 5

are showed the transmitted variables with a description.

Page 95: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

95

VARIABLE DESCRIPTION

Threshold Threshold of the piecewise linear function

Gain Gain of the piecewise linear function

IMax Maximum value of the current

IMin Minimum value of the current

aIAmp Current stimulation amplitude

TimerInMs Time passed since the device has been switched on

RMSshift RMS value of the current block

xData Acquired EMG, first channel

yData Comb filtered EMG, first channel

xData1 Acquired EMG, second channel

yData1 Comb filtered EMG, second channel

nMode Variable to set the different operation modes

BlankInterval Samples blanked in each block

HVValue Values of the high voltage generated by the HVPS capacitors

StimCount Counting of the total cycle performed (saved each time on flash

memory)

Table 5. Transmitted variable between the device and the host

2.4 TESTS

During and after the implementation of the firmware we did some tests in order to verify

the functioning of the device and to understand and reach a better solution in terms of

acquisition of the signal, performance of the device, the stimulation control and displaying

of the EMG.

Page 96: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

96

2.4.1 OPERATION MODES

During the firmware implementation and testing it has been useful to have a variable

defining different operation mode. We used a 32-bit integer variable and bound an

operation mode to each bit of it. This resulted to be a very useful and easy to use way to

control the functioning of the system during testing and debugging session.

The variable type is defined as a union of an integer and a struct. The integer represents the

value of the whole variable (without differentiate each single bit), while the struct contains

all the 32 bits that are linked to different operations. Each element in the struct

(corresponding to one bit) can be named differently and it can be use to enable (if its value

is equal to 1) or disable (if it is equal to 0) a certain operation mode. In this way, it has

been easy and fast to enable or disable function during testing, in order to reach the

working conditions that we needed. During the main configurations, the variable is set to a

predefined value, which allows the functioning of the standard operation. During the

functioning, we could change each single bit or the whole variable values. The operation

modes can be the enable/disable of microcontroller digital signals, filtering options or

processing modalities. The table 6 show the different modes.

MODE DESCRIPTION

PIECEWISE

LINEAR

FUNCTION

Enable/Disable computation of current amplitude using piecewise

linear function. If disabled, current is set by the user

CHARGE VCCS Enable/Disable the charge of VCCS capacitors

MUX RELAYS Enable/Disable the functioning of solid state relays to change

channel/verse of the current

Page 97: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

97

HIGH VOLTAGE

VALUE

Enable/Disable the high voltage value setting (via SPI)

FAST RESTORE Enable/Disable the INA fast restore function

STIMULATION

CONTROL CH 1

Enable/Disable the activation of stimulation on the first channel

STIMULATION

CONTROL CH 2

Enable/Disable the activation of stimulation on the second channel

CHARGE HVPS Enable/Disable the charge of VCCS capacitors

BLANKING Enable/Disable blanking during signal processing

HP FILTER Enable/Disable IIR HP filter to cancel movement artefacts

SUM UP

CURRENT

Sum up the values of current computed from the two different input

channels and deliver it using only one output channel

SAVE COUNT Write to flash the values related to the amount of time passed while

the device is on and working

RESET COUNT Reset the values related to the amount of time passed while the device is

on and working

Table 6. Different modalities used during the tests

2.4.2 TEST SETUP AND ARTIFICIAL EMG

Some tests has been done on a healthy 24-year-old male, while for the others we used an

artificial EMG signal produced by an evaluation board DAC and a setup that replicated the

human tissues and the electrodes positioning on it. During the tests with a real subject, the

Page 98: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

98

EMG electrodes were placed on the wrist extensor, while the stimulation electrodes were

placed on the finger flexors, replicating the main use of the device. For the other tests, we

used a conductive black foam in a box as conductive material and the signal were

transmitted at the corners (figure 56). Using this electrodes configuration we analysed also

the worst case in term of stimulation noise on the signal acquired by the EMG electrodes.

The stimulation current is between the differential EMG electrodes. A similar situation

could happen if we decide to read EMG from the same muscle that we stimulate.

Figure 56. Test setup and electrode positioning in the box with the conductive foam.

The artificial signal has been produced programming the DAC pin of a ADuCM360

evaluation board and it is formed (figure 57) by a fixed DC value, a large signal (that

stands for the offset causing saturation) and a small signal (that stands for the EMG itself).

The large signal is a square wave with amplitude and period that can be changed for the

tests, whereas the small signal is a square wave with random amplitude (the gain can be

changed by the user). The value is updated every 1ms in the timer interrupt, summing to

the set DC and offset, a random value multiplied by the variable gain. The parameters can

be changed also from a host and the used communication protocol is the same used for the

Page 99: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

99

device. This signal can represent well the EMG with some offsets that can be caused by

other phenomena (movement artefacts, etc).

Figure 57. Representation of the artificial EMG signal used for the tests and generated by the internal DAC

of a ADuCM360 evaluation board.

As it can be seen (figure 58), the waveform of the recorded artificial signal is similar to the

real EMG, so we could adapt it well changing period and amplitude gain to perform the

needed tests.

Figure 58. Differences between the real EMG signal recorded on an healthy 24-year-old male and the

artificial EMG signal generated by the DAC.

Page 100: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

100

2.4.3 STIMULATION AND BATTERY CONSUMPTION

In order to test the delivering of the stimulation current with used the configuration in

figure 59, measuring the voltage across the resistor through a digital oscilloscope. We also

tested the proper functioning of the maximum limits imposed to the current.

Figure 59. Scheme of the circuit use to measure the stimulation current amplitude

We also tested the battery consumption, because it is important that the batteries have a

long duration during the functioning of the device. In order to perform this measurement

we used a power supply, an amperometer (to measure the absorbed current) and a

voltmeter (figure 60).

The value of the power has been computed with the following formula:

P [mW] = VC [V] * I [mA] (28)

Where VC and I are the ones measured by the amperometer and the voltmeter.

Page 101: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

101

Figure 60. Scheme of the circuit used to measure the consumption

2.4.4 FAST RESTORE

As explained before, in the AD8232 conditioning block there is also implemented a fast

restore function, which allows to adjust automatically to an higher cut-off frequency, in

order to recover quickly after an abrupt change. The fast restore function can be activated

by the microcontroller, using its internal DAC to generate a 1.8 V voltage level. In order to

activate AD8232 FR pin, a 1.35 V voltage level is needed. Because of the short timing of

our system (every cycle lasts 60 ms), we tested the fast restore function using an artificial

signal in order to understand its real effectiveness for this system.

We used the test setup with conductive foam giving a signal with different amplitude

offsets and different periods and looking for differences between the AD8232 output

signal with and without fast restore activated. In the test, we used a 100 mV large signal

with a 100 ms period and a small signal amplitude limited to 2 mV.

The used circuits has only one channel mounted, so we decided to test the differences

between the conditioning block AD8232 and the instrumentation amplifier AD623, which

has been used also in the MeCFES old version. We analysed the pros and cons of the two

blocks, regarding the performance, amplification, filtering and the measures of all the

needed components.

Page 102: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

102

2.4.5 COMB AND HIGH PASS FILTER

The comb filter is an important part of the signal processing, in order to make the signal

readable and to cancel the noise caused by the stimulation. For this reason, we performed a

spectral analysis (power spectral density) in order to evaluate its effectiveness.

During the first implementation we did not consider the artefact caused by the movement

of other body segments not involved in the muscle EMG recording. This movement

created great offsets that led to the threshold overcoming and to the activation of the

stimulation. For this reason, we made a spectral analysis of the acquired EMG before and

after the implementation of the high pass filter, in order to understand and prove its

efficacy in cancelling the noise.

2.4.6 SOLID STATE RELAYS NOISE

At the beginning of every acquired block, there is always a variable artefact that can also

be visualized in the app. We found that this noise is caused by the enabling and disabling,

during every cycle, of the solid state relays used for the phase reversing of the output

current. This happens because they are activated even if the current amplitude is zero, so

that we have a variable signal at the beginning of every cycle even if the recorded muscle

and the stimulation are not active. The artefact is caused by a low current flowing at the

relays opening, because of the potential difference between the ground and the user

reference voltage level, which is 1.65 V (reference value of the INA).

We know that this noise is caused by the activation of the relays because if we

permanently disable them, it disappears, as it can be seen in the figure 61. The signal

corresponds to the AD8232 block output, analysed with the use of an oscilloscope.

Page 103: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

103

Figure 61. The artefact is visible on the analog conditioning circuit output only if the opening/closing of the

relays is enabled. When they are not enabled, (right) there is no artefact.

In order to cancel or at least reduce the artefact, we added two back-to-back coupled 3.3 V

Zener diodes (BZX84C3V3VGS08) in the following configuration (figure 62).

Figure 62. The scheme of the circuit to cancel the noise caused by the relays. The 3.3 V Zener diodes are

placed between the circuit output and the stimulation electrodes.

After that, we made some tests using the conductive foam with electrodes setup to see the

differences in the artefact with and without the output Zener diodes. We analysed both the

AD8232 block output (signal after analog conditioning, amplification and filtering) and

the signal acquired by the microcontroller and visualized using the app.

2.4.7 PHYSIOTHERAPISTS SURVEY

Beside the development of the system, we decide to make a survey to be compiled by

some physiotherapists (anonymously) in order to understand how much they know

Page 104: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

104

functional electrical stimulation and how much they are open-minded to a neuroprosthesis

controlled by a smartphone/tablet app. The asked question were the following:

1. Do you know what FES (Functional Electrical Stimulation) is?

2. Have you ever heard about MeCFES (Myoelectrically Controlled Functional

Electrical Stimulation)?

3. If you were taught and provided with all necessary instruments, would you use

MeCFES for patient treatment?

4. If you could control a neuroprosthesis with an app for smartphone/tablet, would

you use it?

5. Would you agree with the patients using an assistive device like this one by

themselves?

6. Do you think that controlling a neuroprosthesis with a tablet/smartphone can

contribute to increase the diffusion of this kind treatment?

For each question, the possible answers were YES or NO. After the second question, the

survey included a short description of MeCFES, in order to explain to the interviewed

physiotherapist that did not know it, what kind of device is. The survey has been compiled

by ten physiotherapists working in Fondazione Don Gnocchi (Milano).

Page 105: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

105

3. RESULTS

Figure 63. The box containing the circuit, the batteries and the on/off and led buttons.

The device has been put in a 3D printed box (figure 63), which has been expressly

designed for the circuit, with the space for the three AAA batteries, the on/off button and

the two colour led-button. The rest of support for the electrode and the circuit itself has not

been developed and realized yet. The circuit has one full working input/output channel,

while the second one has been realized only as output. The values relative to the

consumption are shown in the table 7.

Page 106: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

106

OPERATION MODE P [mW]

Circuit on, stimulation off, Bluetooth

communication off

137

Circuit on (with led off), stimulation off,

Bluetooth communication off

120

Circuit on, stimulation off, Bluetooth

communication on

304

Circuit on, stimulation on (20 mA), Bluetooth

communication off

190

Circuit on, stimulation on (20 mA), Bluetooth

communication on

375

HVPS and VCCS off, stimulation off, Bluetooth

communication off

128

Table 7. Consumption of the device in the different modalities

The device is being used as rehabilitation tool in a study on stroke patients rehabilitation

and it has resulted to be effective also when we need to stimulate the same muscle that we

read from. At the moment only one subject has been tested and in his case, the muscle

recorded and stimulated has been the triceps in order to assist an elbow extension, which is

triggered by a low activity of the same muscles (figure 64). Also in this electrodes

configuration, where the noise caused by the stimulation is even greater, the device had a

proper functioning, stimulating only after the elbow extension began and stopping when

the triceps was at rest.

Page 107: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

107

Figure 64. Rehabilitation session. The EMG and stimulation electrodes are placed on the same muscle

(triceps). It can be seen also the MeCFES in the 3D printed box and the tablet (host) used to control the

device.

3.1 FAST RESTORE

We needed to evaluate the effectiveness of the INA fast restore function in order to

understand if it could be useful in our system in order to cancel the offsets. To do this, we

used the artificial EMG signal and the conductive foam test setup. As explained in the

“Tests” section, we used a 2 mV amplitude signal, with a 100 mV offset that changed

every 100 ms with and without the fast restore function enabled. We evaluated, using a

digital oscilloscope, the output of the AD8232 conditioning block.

As it can be seen (figure 65), when the fast restore is active (right), the settling duration is

reduced, but only a little amount of time before the new offset (that leads to another

saturation). When FR is disabled (left), the block cannot recover before the new offset and

the small signal is completely unreadable.

Page 108: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

108

Figure 65. The output of the conditioning block when the input is a 2 mV amplitude signal with a 100 mV

offset every 100 ms. In the figure at left the fast restore function is not enabled, at right it is enabled.

In our case there are a lot of offset caused by movement artefacts or other factors and in

this way (also using FR) the majority of the acquired signal would not be the EMG signal,

but the high saturation signals caused by artefacts. The timing of our system is very short

and offset or saturations can happen many times in a short amount of time (more than in

the test). For this reason we can assume that if the signal is changing (and saturating) so

fast, the fast restore function is not able to resettle the signal before another saturation is

detected.

To solve this problem and cancel low frequency noise we implemented the digital high

pass filter, which is the first operation done during the digital signal processing.

3.2 STIMULATION AND CONTROL

To test the right delivering of the stimulation current and the controls to limit it, we linked

the output to a 1 KΩ resistor and we measured the voltage across it (figure 66). In this

configuration the value of the measured voltage in volts corresponds to the value of the

current in milliamperes.

Page 109: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

109

Figure 66. The configuration used to measure the output stimulation current.

Figure 67. Delivery of a 20 mA stimulation current (left) and delivery of a 50 mA stimulation current (right).

First output channel has been used.

Figure 67 shows the voltage across the 1KΩ resistor with a fixed 20 mA stimulation

current. The single waves have a 20 V amplitude and their duration is 300 us. Each block

corresponds to 250 us and 20 V. As shown the stimulation current can be obviously

changed.

In this case we have a 50 mA current, with a 50 V voltage amplitude across the resistor.

Page 110: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

110

Figure 68. Delivery of a 65 mA stimulation current, with a maximum limit of 50 mA (first channel).

In this case (figure 68) we tested the second control variable (IMaxLimit), which is fixed

and cannot be changed by the user. Its value is 50 mA and, even if now the current is set to

65 mA, it is limited to 50 mA. This is an important control in order to avoid the delivery of

dangerous value of current to the user.

Figure 69. Delivery of the current from both the first and the second channel (left). At right, the amplitude of

the stimulation current can be different for each channel.

After that we tested the stimulation on both the channels, adding a the same testing

configuration (figure 69) to the second output channel. In the figure is shown the case with

the same current amplitude (20 mA). The duration of each event is 300 us, thanks to the

finite state machine called in the Timer1 interrupt. The output of the channels can be also

Page 111: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

111

different. In this case the first channel has a 40 mA output, while the second one has a 20

mA output.

The amplitude of the waves related to the same channel cannot be different, in order not to

have a net charge (that leads to tissue damages). This results are the consequence of the

proper functioning of the HVPS and of the VCCS, delivering current with different (high)

amplitude values.

The signal acquired EMG is shown in the app. It is important to notice that the shown

signal does not correspond to the raw EMG, but it is the high pass filtered signal. In this

representation, if we acquire a sine with a 100 Hz frequency and a 9 mV peak-to-peak

amplitude, the shown filtered signal will be included between MAX (50000000) and MIN

(-50000000). The shown signal is update at every cycle (60 ms), because of the data

transfer between the firmware (where the signal is acquired and updated during each

cycle) and the host.

Figure 70. The signal displayed in the Android app, after the first high pass filter to cancel movement

artefacts. MAX and MIN correspond to a 9 mV peak-to-peak amplitude signal. In the left figure, there is no

muscle contraction and no stimulation. In the right figure, there is the display of the EMG signal (wrist

extensors).

As shown in figure 70, the difference between a rest condition and a contraction is visible.

In the figure relative to the contraction there is no stimulation, but the peak at the

beginning is an artefact caused by the enable of the solid state relays (see “Output Zener

Diodes” paragraph). Considering the limit value of 9 mV peak-to-peak previously

Page 112: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

112

computed, the maximum amplitude of the signal is lower than 1 mV, which is a proper

value as explained in the “Introduction”.

Figure 71. Display of the EMG signal during a contraction and stimulation.

In figure 71 is shown the same high pass filtered EMG in presence of a 15 mA stimulation.

The noise caused by the stimulation is visible in the first period of each cycle, but only the

first 15-20 samples are disturbed by the high current (and voltage) developed by the

stimulation delivery. Its total duration is lower than 1 ms and the artefact is not visible

after 10 ms from the beginning. In this way, the EMG of the muscle we are interested in is

visible also while the device is stimulating.

Page 113: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

113

3.3 MOVEMENT ARTEFACTS AND HP FILTER

Figure 72. EMG signal without (red) and with (blue) movement of other body segments (lower limb),

recorded for 20 cycles (1.2 seconds).

As explained before, the acquired signal can be disturbed by the movement of other body

segments, even if the recorded muscle is not involved. This noise produces large offsets

(figure 72) that can affect the signal and the processing, so that the stimulation is triggered

also without a contraction of the recorded muscle. As it can be see in figure 73, analysing

the power spectral density of an acquired signal disturbed by movement artefacts and

comparing it with an EMG signal, the energy noise is relevant only for low frequencies.

Page 114: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

114

Figure 73. PSD of EMG signal recorded for 1.2 seconds (left) and PSD of EMG signal with movement of

other body segments (lower limb) recorded for 1.2 seconds (right)..

For this reason, we decided to implement and apply to the raw acquired signal an IIR high

pass filter, in order to cancel the movement artefacts (“Digital Signal Processing”

paragraph). Repeating the same analysis on the high pass filtered signal, it can be seen

(figure 74) that the low frequency noise is reduced. In this case, we had a 35 Hz cut-off

frequency and so the 50 Hz hum did not change.

Figure 74. Power Spectral Density of the HP filtered noisy EMG signal.

Page 115: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

115

3.4 FIR FILTER

As explained in “Digital Signal Processing”, after the high pass filter, we also used a FIR

comb filter, in order to cancel the noise introduced by the stimulation and the 50 Hz hum.

The result of this operation can be shown in the app.

Figure 75. Comb filtered signal of EMG without (left) and with (right) the stimulation.

Figure 75 shows the representation of the array resulting from the FIR comb filtering in

case of muscle contraction (first image) and muscle contraction with stimulation on

(second image). As it can be seen, the noise caused by the stimulation is cancelled and the

signal is very similar to the one without stimulation.

The efficacy of the filter is shown (figure 76) also by the power spectral density analysis

(using MATLAB) of the signal before (red) and after (blue) the comb filter. The analysis

has been done on a signal acquired during 20 consecutive cycles. As it can be seen, the

peaks caused by the repeated stimulation are cancelled and PSD is reduced by 30 times

(the maximum value in the first graph is 9*1015, while in second one it is 3*1014). Most of

the energy is included between 50 and 500 Hz, which is the proper bandwidth of an EMG

signal recorded using surface electrodes.

Page 116: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

116

Figure 76. Power Spectral Density of EMG signal with stimulation noise recorded for 1.2 ms before (left)

and after (right) the comb filter.

3.5 OUTPUT ZENER DIODES

For this test we used the artificial EMG signal and the test setup with the conductive foam.

As explained in “Tests” paragraph, in order to reduce the noise caused by the solid state

relays enabling, we designed a simple circuit formed by two couples of zener diodes for

each output channel.

Through an oscilloscope, we measured the output of the analog amplification and

conditioning block, in order to understand if the artefact has been reduced. We used an

oscilloscope because it allowed us to measure with accuracy the reduction of the noise.

Figure 77. The artefact caused by the relays activation, measured at the conditioning block output without

(left) and with (right) the Zener output circuit

Page 117: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

117

In these two cases (figure 77) on channel 1 of the oscilloscope is indicated the output of the

block conditioning, while on channel 2 there is the signal related to the stimulation output,

which is always zero. In the first figure it can be seen a great artefact that has a 3 V peak-

to-peak amplitude (every square represents 1 V), while in the second image, with the use

of the zener diodes, the artefact is reduced and its amplitude is similar to the one of the

EMG (3.5 mV in this case). As shown, in the second figure, the peak-to-peak amplitude of

the artefact is 1.5 V. So this solution can halve the noise amplitude.

Figure 78. If the stimulation is on the artefact is covered by the stimulation noise in every configuration.

In this case (figure 78) the configuration is not changed, but the stimulation is on. As

shown in the two figures, the zener diodes configuration (right) does not change the

acquired signal because the noise caused by the stimulation completely covers the one

caused by relays activation.

3.6 PHYSIOTHERAPISTS SURVEY RESULTS

The results of the survey addressed to the physiotherapists are shown in the table 8. For

each question, we decided to analyse the number of positive and negative answers. The

questions can be seen in the “Physiotherapists survey” paragraph.

Page 118: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

118

QUESTION YES NO

1) FES knowledge 9 1

2) MeCFES knowledge 7 3

3) MeCFES use to treat

patients

9 1

4) Use of an Android app to

control the device

5 5

5) Agree with patients using

the device themselves

5 5

6) Diffusion of this kind of

treatment

8 2

Table 8. The answers to the survey addressed to the physiotherapist (questions are listed in the

“Physiotherapists Survey” paragraph)

As it can be seen, most of the interviewed physiotherapists knew functional electrical

stimulation, but a lower percentage of them heard previously about MeCFES device

(which has been also developed in Fondazione Don Gnocchi). Nine out of ten would use

the device to treat the patient, but they are less willing to control the device with a

smartphone/tablet and to let the patient use the device by him/herself. Finally, most of the

interviewed physiotherapists believe that the use of an app would increase the diffusion of

this kind of treatment.

Page 119: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

119

4. DISCUSSION

4.1 PROS OF THE DEVICE

The described project has led to the development and writing of the firmware of the new

MeCFES version and to the realization of a first prototype of the system. The firmware has

been adapted to the circuit and to its electronic components and, during the realization,

also some additions on the hardware has been done, like the mounting of the second output

channel (resistors and four solid state relays). The firmware has been designed in order to

make the device safe, economic, portable, easy to use and adaptable to different situations.

The innovative features of the system are the improved adjustable proportional EMG

control and the communication with an Android app. During the development, the system

has been tested for its main function that is the restoration of the grasp of the paretic hand

in neurological patients. The EMG signal is recorded from the wrist extensors, while the

stimulation electrodes are placed on the finger flexors (figures 79-80).

Figure 79. Positioning of the EMG electrodes during the tests (wrist extensor).

The one in the middle is the reference electrode.

Page 120: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

120

Figure 80. Positioning of the stimulation electrodes during the tests (fingers flexor).

This kind of control results to be very intuitive, because it is based on the tenodesis grasp

and so the stimulation leads to an enhancement of this natural characteristic of the hand

movement. The stimulation is proportional to the EMG amplitude and this feature allows

the user to easily start/stop the stimulation with a wrist extension/flexion and to perform

grasp with different force intensity, depending on the task. In this way, the produced force

and the movement are not fixed and stereotyped, but completely controllable by the user

himself.

The digital signal processing implemented in the device is able to distinguish the real

EMG signal from the noise caused by the stimulation or the movement artefacts. This

result is reached with the use of the comb filter (that cancel the noise related to the

stimulation and the 50 Hz hum) and the high pass filter (that cancel the offsets caused by

the movement of the user). The coefficient of the last one can be changed depending on

the wanted cut-off frequency. Looking at the power spectral density of the EMG signal

(figure 81), it can be seen that most of the energy is contained between 80 and 150 Hz, so

it is preferable not to choose a cut-off frequency higher than 70 Hz. This value allows to

cancel all the movement artefacts (that has a lower bandwidth) and to keep the information

about the muscle contraction.

Page 121: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

121

Figure 81. Power Spectral Density of the EMG signal.

From the analysis of the results, we can understand that the artefact caused by the relays

enable is reduced with the implementation of the output Zener circuit. So, the next circuit

version they can be added to the output. Anyway, from a processing point of view, this

artefact causes no issues because it is cancelled by the blanking operation.

After the computation of the RMS value, an IIR low pass filter is performed. In this case

the chosen coefficient must not be too high because this would compromise the capacity to

control the stimulation, resulting in a very variable stimulation current value. At the same

time, a low value of the coefficient would not allow to change the variable in a short time,

resulting in a time difference between the muscle contraction and the supply of the current.

For this reason, this is a critical parameter that needs to be evaluated as explained.

The final computation of the current amplitude is performed by a piecewise linear

function, so that the stimulation is proportional to the recorded EMG. This method results

to be effective, but there are other methods that could be used, using the same principle of

the tenodesis grasp.

Page 122: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

122

The communication with the Android app (figure 82) allows to change the stimulation

parameters and to adapt the device to different situation and tasks during the activities of

daily living. This is an important innovative feature that makes the device portable and

controllable in every situation. The previous version allowed the device to communicate

only with a computer, making the system difficult to be used for many tasks (for example

it could be used only at home or in spaces with computers) and limiting the potentiality of

the adjustable parameters. Now the user can decide and set the value of the maximum and

minimum delivered current, the threshold and the gain (that makes proportional the

stimulation).

Figure 82. The new MeCFES version in the 3D printed box and the tablet with the app to control the device.

The device, thanks to the proper conditioning block and digital signal processing, is able to

process only the EMG of the muscle that we are interested in, without considering noise

like the one created by the stimulation delivery. During the development, we did not test

the simultaneous recording and stimulation from both the channels, but with the

characteristics of the comb filter and the blanking (applied independently to the data

coming from each channel) the noise should be cancelled also when using the two

channels simultaneously.

Page 123: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

123

Thanks to its adaptability in terms of different tasks or different muscle and body

segments, the device can be used also to record and stimulate other muscles. The

amplitude of the stimulation current can be increased up to 100 mA, so we could activate

properly all the skeletal muscles, in order to rehabilitate different parts of the body,

including the lower limb. Moreover, the level of the threshold and the gain can be

regulated depending on the recorded muscle. If it is a small or damaged muscle, the user

can decrease the threshold in order to reach the activation with a smaller EMG amplitude.

This is the case of the only stroke patient treated with the device, which assisted the elbow

extension. The recorded muscle was the same that was stimulated, in order to assist and

rehabilitate an almost compromised function. The subject could activate the stimulation

starting the extension movement and stop it going back to the rest position of the arm. The

initial contraction needed to activate the stimulation can be change, acting on the

threshold. This is a demonstration of the adaptability of the device to different users and

tasks.

4.2 CONSIDERATIONS ON CONSUMPTION

Battery consumption is a critical aspect regarding the portability and the usability of the

system. The device is supplied by three 1.5 V AAA batteries, which must guarantee an

adequate battery life in order to allow an extended use without the need to change them.

As shown in table 7, most of the consumption is related to the Bluetooth connection with

the host and to the data transmission. The stimulation cause also a large battery

consumption, but the value of the power is lower than the one associated to the Bluetooth

connection. In addition, the stimulation is not continuous while wearing and using the

device, but it is active only when performing the needed task. On the contrary, if we want

to change the parameters or see the acquired signal, we need to remain connected with the

app, causing a continuous relatively large amount of battery consumption (304 mW). To

solve this problem and limit the consumption, the user could connect and use the app only

when he/she needs to change some parameters and disconnect it during the normal use of

Page 124: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

124

the device, which will work with the last parameters values imposed by the app. This will

allow saving energy and to extend the battery life.

All the ten 45-minute sessions with the stroke patient treated have been completed without

changing the batteries, assuring a battery life higher than 7 hours while stimulating and

transmitting data, which is the condition of maximum consumption.

4.3 CONDITIONING BLOCK DISCUSSION

The conditioning block of the circuit has a proper functioning, thanks to the features of

AD8232. As explained before, we chose this block because of his multiple components

and features. It is very important to have a high adjustable gain (that can be changed with

the external resistors) and a driven right leg circuit in order to cancel the common-mode

noise. Moreover, the block allowed the implementation of multiple-pole high pass and low

pass RC filters, in order to obtain only the bandwidth of the EMG signal. The results have

underlined the proper amplification and filtering of the EMG. Only the movement

artefacts caused some issues, but the problem has been solved by implementing a digital

high pass filter.

One of AD8232 features, the fast restore function, has been analysed and we came to the

conclusion that in our system it is not useful, because, after an offset, the signal is not

recovering fast enough to make all the signal readable. This happens because this block is

optimized for ECG recording and not for EMG. Moreover, lead off detection (LOD) is a

feature that we do not use, because the detection of the connectivity of the electrodes in

our system can be done also by the display of the acquired signal. In the case of not

connected electrode, the shown signal is characterized by the saturation of the amplifier

(figure 83).

Page 125: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

125

Figure 83. Visualized signal in case of INA saturation.

For the reasons we took in consideration the possibility to use a simple instrumentation

amplifier, like AD623, which has been used in the old MeCFES version. This solution,

completed with the proper conditioning circuit could assure the amplification of the signal

with a high gain (1 to 1000), having the whole acquisition circuit with low dimensions. In

this case, the analog filters (with the same number of poles) should be obviously

implemented outside the block, because AD623 contains only an INA, without all the

others components and features. This could increase that needed size of the circuit to

perform a proper filtering. Moreover, in this case there is no driven right leg circuit, which

is an important feature.

Finally, we can assert that, despite the greater size of the circuit and the not usage of some

features like fast restore or lead off detection, AD8232 block is preferable to AD623

because of all its components and functions that are not featured in a simple INA (like, for

example, the driven right leg circuit).

Page 126: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

126

4.4 FUTURE DEVELOPMENTS

4.4.1 FIRMWARE

The implemented firmware can be developed in order to have a better control, with the use

of hardware components (sensors) or a more complex digital signal process.

A sensor on the wrist could be used to measure the movement of the hand and trigger the

stimulation proportionally to the wrist angle. This is a simpler method than the EMG-

controlled device, but it could not be adaptable to other muscle and body segments, it

would be usable only for the paretic hand. A more complex solution would be the feature

extraction from the recorded EMG signal in order to differentiate each movement that

involves the activation of the same muscles. This could lead to a better control, but the

processing would be very complex in terms and computation.

Because of the adaptability of the firmware to the analysis and stimulation of different

muscles and body segments, it could be useful to implement different feature extraction

algorithms for each segment to be read. The right muscle algorithm could be selected by the

user depending on the needed use of the device or on the type of treatment. This approach

would be very selective, because different muscles have different activation patterns that

can be analysed in a more specific way. This analysis could lead to a specific type of

stimulation for different muscle. The device has two channels, so, in this way, the digital

signal process could be different for each channel in order to have a better and more

specific performance.

4.4.2 CIRCUIT: BATTERY LEVEL

One of the problem of the implemented system concerns the excessive use of the batteries.

It is not beneficial for a 1.5 V rechargeable battery to discharge it under 0.8 V. For this

reason, in the next version, a boost converter with adjustable undervoltage lockout could

be used. With the use of the boost converter, if it is enabled, we can have a fixed output

voltage (3.3 V in our case), starting from the input batteries voltage. The output voltage is

delivered until the input is higher than a fixed value, called undervoltage lockout (UVLO).

Page 127: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

127

For this reason, it could be used TPS61201 boost converter, where the UVLO can be

adjusted with the use of a voltage divider. As it can be seen in figure 84, the main output is

prevented from being supplied if the voltage at the UVLO pin drops below 0.25 V. So,

changing the resistors in the voltage divider, we can disable the device at different voltage

input. In the example, this input voltage corresponds to 3 V, in order to prevent the

complete discharge of the three batteries.

Figure 84. Use of the boost converter TPS61201 with UVLO in the circuit to switch off

the system from the microcontroller.

In the figure, in addition to the adjustable UVLO, is also proposed a circuit that allows

switching off the whole system directly using a microcontroller digital pin. This feature

could be useful in case of come errors or emergencies (for example a high current

amplitude that could damage the user) and it could automatically stop the whole device.

The system is switched on by pressing the button and setting the enable pin of the boost

converter. This button can be released when the microcontroller is active and, with the

uPWR pin, TPS61201 is still enabled. At this stage, when uPWR is put low (and the

button is still not pressed), the boost converter will be disabled, and the whole system will

be switched off (figure 85).

Page 128: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

128

Figure 85. Switching on/off of the system (the signal are referred to the previous figure).

4.4.3 SUPPORT OF THE SYSTEM

The prototype of the support for the circuit and the electrodes placement has not been

realized yet, but a future development of it could lead to many advantages. The whole

system would be completely around the forearm of the user, without loose wires along the

body because the box with the circuit would not be attached to the waist of the patient, but

on the support, near the electrodes. In this way, the device could be completely portable.

The support would be lockable and unlockable by the user himself with the use of only

one hand, so without needing help from other people (figure 86).

Figure 86. The 3D printed support can be lock and unlock by the user him/herself.

Page 129: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

129

The electrode will be fixed with some velcro strips around the support, the will be covered

in order to result comfortable for the user.

As explained before, the support would be completely 3D printed. Thinking about a future

development of the system, also in terms of distribution, this technique offers many

advantages. First of all it is a very simple and cheap solution that everybody could

approach. The digital model can be adapted to each different arm, designing a

personalized solution for each patient, which is more flexible and adaptable. With this

solution the user could 3D print by himself (in some specialized centres) the electrodes

support and the circuit box so that he/she should only buy the assembled circuit to have the

functioning device. This idea could be extended also to supports for neuroprosthesis in

another body segments, because of the adaptability of the circuit to different districts.

4.5 CONSIDERATIONS ON THE PHYSIOTHERAPISTS SURVEY

The results obtained by the answers to the survey allows us to understand the opinion of

the physiotherapists about neuroprosthesis, MeCFES and smartphone/tablet control. It is

known that one of the reasons of the small diffusion and use of this kind of devices is the

limited access to resources (like training and equipment) and modalities of use

[Auchstaetter et al.,2015]. As shown in the results, almost all the interviewed

physiotherapists heard about functional electrical stimulation as a treatment technique, but

a lower percentage knew an existing device, previously developed in the same place, like

MeCFES. After the explanation, nine persons out of ten would be interested in using it to

treat stroke patients. This answer allow us to understand that with proper knowledge and

information about the device, it could be used to treat many patients, leading to a great

diffusion of this technique. Hale of the physiotherapists (5/10) stated that they would not

use smartphone/tablet to control a neuroprosthesis, but they also believe that the use of this

kind of tools (like apps) would contribute to increase the diffusion of functional electrical

stimulation and neuroprosthesis. This result emphasizes a sort of diffidence towards

smartphone/tablet control, but there is also confidence about the future diffusion of this

Page 130: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

130

kind of technology. Finally, half of the interviewed persons would not let a patient use this

kind of device by him/herself, probably because they believe that the patients could not

properly control the device.

Page 131: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

131

APPENDIX A: ELECTRODES AND ELECTROMYOGRAPHY

ELECTRODES

Electrodes are transducers (a device that can convert one form of energy to another) which

can transform the ionic current in the tissue in electronic current that flows in the

conductors. They can be used to measure the electric activity of the different tissues in the

human body (heart, muscle, etc) or to stimulate the tissue. They need to be biocompatible,

non-toxic and they have not to easily corrode. Depending on the positioning, the

electrodes can be divided in surface, percutaneous and implanted electrodes.

Surface electrodes are placed on the skin. In some cases, they need the presence of a

conductive electrolytic gel, which is often used to reduce the skin impedance. They are

non-invasive and easy to use, but the contact is often unstable and the skin-electrode

interface is a source of noise that changes of the skin conductivity. The transformation is

given by means of oxidation-reduction chemical reactions at the interface between the

physiological system and the electrode itself. Once it is attached to the body skin, over the

electrolytic gel surface, a double charge layer is created at the interface between the

electrode and the gel, due to the oxidation-reduction reactions. Such charges concentration

difference creates a potential difference that is called contact potential. The contact

potential is fixed for each electrode material - electrolytic solution, but it can be unstable,

because of motion artefacts, temperature or other factors. The model of the interface can

be seen in figure 87. Surface electrodes does not allow to record the activity from deep

muscles with the needed accuracy (or to stimulate them) and using them, some muscles

that we are not interested in can be involved in the recording/stimulation process.

Page 132: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

132

Figure 87. Model of the skin-electrode interface. Ehc: electrode half cell potential; Ese: potential due to

ionic differences between gen and stratum corneum; Ep: potential due to skin pores.

Percutaneous electrodes are placed through an hypodermic needle. The working volume is

more selective and they can reach deep muscles and be used also for several days. The

recording/stimulation noise is lower, but they are invasive and cause the risk of infections.

Implanted electrodes are in direct contact with the nerves and the muscles. They are very

selective and subject to less noise. The main disadvantage is the invasiveness, that leads to

damages to the tissue.

ELECTROMYOGRAPHY

In research and in diagnostic is very useful to record and analyse the electrical signal

resulting from muscle contractions. In this way it can be studied how and when the

muscles involved in different tasks are active and the information coming from that

processing of EMG can be used for many objectives in different field of application, like

medical research, ergonomics and rehabilitation. The signal can be recorded with the use

of different type of electrodes, that can be placed on the skin or inside the muscle,

depending on the purposes of the analysis [Cavalcanti Garcia et al, 2011].

Page 133: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

133

The myoelectric activity is

characterized by the action of motor

units. As explained before, when an

impulse is transmitted from a

motoneuron, all the muscle fiber of

that single motor unit are activated.

The summation of all these potential

is called motor unit action potential

(MUAP). The force produced by the

muscle depends by the spatial and

temporal summation of MUAPs

(figure 88). For this reason, if we are

using surface electrodes, the recorded signal will be not indicative of the single action

potential or of the single motor unit activity. For this purposes, that usually are relevant in

the diagnostic field, implanted electrodes can be used, to study the shape of an action

potential. In the other fields, what really matters is to understand the contraction level of

the muscle, so that surface electrodes can be useful even if the recorded signal is not

accurate. The potential, resulting from a MUAP, will be recorded by the electrodes at

different times from each active fibers, because they obviously are in a fixed position,

whereas each endplate is in a different position. The recorded signal is so influenced by

the instant of activation and by the mutual position of the endplates of the active fibers and

the obtained will be the summation of action potential at different times and polarity,

resulting in a less accurate signal. In addition to this aspect, during a muscle contraction

there are always a lot of different active motor units, so that the recorded signal will be the

spatial and temporal summation of all the different impulses. The signal resulting from the

repeated recruitment of each single motor unit is called MUAP train and it is obtained in

this way:

MUAPT (t) = ∑MUAP · (t − T k) (29) k

Figure 88. The generation and recording of MUAP,

starting from difference fibers of the same motor unit.

Page 134: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

134

The shape of the raw EMG signal will be the summation of all the MUAPTs and it is

represented in figure 89 [De Luca et al, 1997].

Figure 89. The generation of the acquired raw EMG signal from differents MUAPT.

After the recording, the EMG signal must be analysed in order to extract the needed

informations. The signal amplitude is low (10 uV - 5 mV) and the bandwidth in case of

surface electrodes is between 10 Hz and 500 Hz, so the obtained signal must be amplified

and filtered. The electrodes placement can be monopolar or bipolar. In the first

configuration a single electrode is placed on the muscle bulk, with a reference electrode

placed far from the other. In this way all the physiological noise (like other muscles or

ECG activity) are amplified. The bipolar configuration offers the possibility to cancel part

this noise, because the amplified signal is the difference between the potential recorded by

two electrodes placed in the working volume, with a reference placed far from it. The

remaining part of the noise can compromise the signal analysis, so it is important to use an

instrumentation amplifier (INA) with an high common mode rejection ratio (CMRR), in

order to amplify only the real EMG signal without considering the common mode. In this

configuration electrodes are usually placed along the direction of the muscle insertion, but

it is important not to placed them on the endplate, to have a biphasic differential signal.

The differences between monopolar and bipolar configurations can be seen in figure 90.

Page 135: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

135

Figure 60. Monopolar and bipolar electrodes configurations.

There are different sources of noise; they can be endogenous (signal from other muscle,

cross-talking) or exogenous (movement artefacts, skin-electrode interface, common

mode). Some of this sources cause noise at different frequency from the EMG bandwidth

and so they can be cancelled using low pass and high pass filter. If the bandwidth is

similar, it must be used an INA with an high CMRR and an high input impedance [De

Luca et al, 2010]. Most of the EMG frequency power is between 15 and 250 Hz, with the

peak corresponding to 100 Hz ca.

After the recording, amplification and analog to digital conversion, different indexes can

be computed and used to estimate the amplitude of the EMG, the muscle force or the

fatigue. The peak-to-peak measure is not a robust descriptor, because of the low accuracy

of the measured potential. For this reason often the average rectified value (ARV) and the

root mean square (RMS) amplitude are used as an estimate of the EMG amplitude.

[Cavalcanti Garcia et al., 2011].

Page 136: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

136

ARV= Σ |EMG(n)| (30)

RMS = 1/N Σ EMG(n)2 (31)

Using this methods, the amplitude value is computed across short epochs (50 ms - 500 ms,

depending on the timing of the activity that we want to analyse). The indexes provide

different results because the RMS descriptor emphasizes the samples with an high

amplitude, so it may be preferred if we want to detect the activation of the muscle.

Page 137: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

137

APPENDIX B: COMMUNICATION INTERFACES (UART AND

SPI)

The microcontroller used in the system needs to control and communicate with many

peripherals. Among all the interfaces used, the most used are UART and SPI.

UART

UART (Universal Asynchronous Receiver/Transmitter) is a subcircuit that transmits and

receives serial data. In UART communication, two UARTs communicates directly, using

only two wires. The device converts parallel data into serial data that are transmitted,

received and converted again into parallel byte by the other device. The two wires link the

Rx and Tx pin of each UART. The communication is asynchronous, because there is no

clock line to synchronize the output bits from one UART to the input bits by the other one

(figure 91).

Figure 91. UART communication functioning principle.

In order to synchronize the transferred bits, start and stop bits are added to the sent data, to

define the beginning and the end of the data packet. In this way, the receiver knows when

to start reading. When the start bit is read, UART 2 begins to read data at a predefined

frequency that is called baud rate. It measure the speed of data transfer and it is expressed

in bits per second (bps). Obviously the baud rate of the two UARTs must be the same,

Page 138: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

138

with an high accuracy (at least 90%), in order not to have errors in the transfer and in the

reading. The devices are re-synchronized after the transfer of every word, using every time

the start and stop bits. In this way, the possible error caused by a difference in the baud

rate is reset at every word transfer and there is no error integration.

The packets of data transferred are composed by one start bit, the data bits, one parity bit

(that can also not exist) and one or two stop bits (figure 92). Usually the start bit is 0,

because with no transmission the voltage level of the line is high. When the receiver

detects an high to low transition lasting one clock cycle, then it begins to read at the

predefined baud rate (usually 9600, but it can be higher). During the data transfer, LSB is

usually sent first and a word can be 9-bits long if there is no parity bit. The parity bit is

used to detect error in the transmission or changes in the data frame (because of baud rate

mismatches or electromagnetic radiation). It express the oddness or evenness of the

number of bits with a value of 1 in the data frame. If this number is odd, the parity bit will

be equal to 1; if the number is even, the parity bit will be equal to 0. In this way, the

receiving UART can compare the evenness or oddness of the read bits with a value of 1

with the parity bit and, if they are different, it can know that it has been an error during the

transfer. The stop bits consist in driving the line to a high voltage for at least two clock

cycles; this indicates the end of the transmission. At this point, the receiver can reconvert

the data bits (without the start, parity and stop bits) into parallel data and the can be

utilized for the needed functions. It is important to remember that this type of

communication does not support multiple master or slave systems.

Page 139: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

139

Figure 92. Transfer of one 8-bit word (with start, parity and stop bit) between UARTs.

SPI

Serial Peripheral Interface (SPI) is an interface bus, which permits the microcontroller to

communicate with registers, sensors, ADC/DAC converters and other peripherals. It is

different from other interface buses (like for example UART), because it uses separate

clock and lines. Using a common serial port we can’t be sure if the sender and the receiver

are running at the same rate, so we call it asynchronous. This can be a problem, so

additional bits are used to synchronize. This leads to the transmit of a lot of unuseful bits

(overhead) and in addition, the two sides have to be set at the same speed.

To solve these problems SPI can be used. It is a synchronous communication interface

because it works on separate lines and it uses a clock to perfectly synchronize sender and

receiver. The clock tells the receiver when to look at the data (rising or falling edge) and

so it is not important to specify the speed. Another positive aspect of SPI is that it can be

used also a simple shift register as receiving hardware (UART is more complicated).

Page 140: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

140

At one side there is the Master and at the other one there is the Slave (figure 93). The

Master side is where the clock is always generated. There can be only one Master (in our

case it is the microcontroller), but more than one Slave can be present. There are two data

lines between Master and Slave because the data goes in two direction; if the Master needs

an answer from the Slave it will continue to generate a prearranged number of clock

cycles. Data from Master to Slave are sent with the line MOSI (Master Out/Slave In) and

data from Slave to Master are sent with the line MISO (Master In/Slave Out). Having two

lines, data can be transmitted and read at the same time. In the most simple case, a full

duplex data transmission occurs. The two shift registers have the same word size (that can

be 8, 12 or 16 bits) and while the Master sends the most significant bit, the Slave reads it

and sends its least significant bit, forming an inter-chip circular buffer.

Figure 93. SPI communication: circular buffer principle

Besides the clock and data lines, there is a fourth line (Chip Select or Chip Enable) that

wakes the Slave when the Master needs to communicate (figure 94).

Figure 94. SPI data transfer from master to slave.

Page 141: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

141

Sometimes there can be more than one Slave. In this case the Chip Select line will be

called Slave Select (SS) and the number of SS lines will be the same of the Slaves number.

In this way, the Master can select the Slave that it wants to communicate with. If the

Master needs an answer from the Slave after the data transmission, chip select will remain

enabled (low) and it will continue to give the clock (figure 95).

Figure 95. SPI data transfer from master to slave, with an answer from slave to master.

The Master must also configure the clock polarity and phase. Clock polarity (CPOL)

represents the state of the clock line at the moment of the activation (active low) of the

Chip Select Line and so it can be high (1) or low (0). At this point, the clock phase

(CPHA) will select the edge of the clock (which correspond to the moment when data

should be read). If CPHA is low, the data are read on the first edge; if CPHA is high, the

data are read on the second edge. Depending on these two values, the Master and the Slave

know if they must read data on the rising or on the falling edge. In the previous example

rising edge was used.

Page 142: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

142

APPENDIX C: MICROCONTROLLER SIGNALS TABLE

SIGNAL PIN NAME DESCRIPTION

LOD+2 AIN2 INA2 Lead Off Detection

LOD-2 AIN3 INA2 Lead Off Detection

INA_OUT2 AIN4 INA2 Output

TP1 AIN5 TestPoint

TP2 AIN7 TestPoint

LOD- AIN8 INA1 Lead Off Detection

LOD+ AIN9 INA1 Lead Off Detection

INA_OUT AIN10 INA1 Output

FR DAC INA Fast Restore activation

PLS_CTR P0.0 Stimulation on/off

UART_RX P0.1 UART receive

UART_TX P0.2 UART transmit

EN2_CH0 P0.4 Stimulation MUX (Channel

1, first pulse)

Page 143: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

143

SW_CTRL P0.5 Button

CHRGVCCS_DRIVE P0.7 VCCS capacitors charge

activation

EN_CH1 P1.0 Stimulation MUX (Channel

0, second pulse)

EN_CH0 P1.1 Stimulation MUX (Channel

0, first pulse)

EN2_CH1 P1.2 Stimulation MUX (Channel

1, second pulse)

LED_CTRL P1.3 Led control

SPI_MISO P1.4 SPI master in - slave out

SPI_CK P1.5 SPI clock

SPI_MOSI P1.6 SPI master out - slave in

SPI_CE P1.7 SPI chip enable

VPP_CHARGE P2.0 HVPS capacitors charge

activation

EN_INA_SUPPLY P2.1 Power analog circuits

EN_ST P2.2 Power analog circuits

Page 144: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

144

RESET RESET Reset (internal pull up)

SWCLK SWCLK Serial Wire Debug

SWDIO SWDIO Serial Wire Debug

Table 9. Signal to/from all the pins of the microcontroller

Page 145: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

145

LITERATURE

• Lee BB, Cripps RA, Fitzharris M. The global map for traumatic spinal cord injury

epidemiology: update 2011, global incidence rate. Spinal Cord. 2014; 52: 110–116.

• Béjot Y, Delpont B, Giroud M. Rising Stroke Incidence in Young Adults: More

Epidemiological Evidence, More Questions to Be Answered. Journal of the

American Heart Association. 2016; 5:e003661

• Wright PA, Granat MH. Therapeutic effects of functional electrical stimulation of

the upper limb of eight children with cerebral palsy. Dev Med Child Neurol. 2000

Nov; 42(11): 724-727.

• Mayer L, Warring T, Agrella S, Rogers HL, Fox EJ. Effects of Functional

Electrical Stimulation on Gait Function and Quality of Life for People with

Multiple Sclerosis Taking Dalfampridine. Int J MS Care. 2015 Jan-Feb; 17(1): 35–

41.

• de Kroon JR, van der Lee JH, Ijzerman MJ, Lankhorst GJ. Therapeutic electrical

stimulation to improve motor control and functional abilities of the upper extremity

after stroke: A systematic review. Clinical Rehabilitation 2002; 16: 350-360.

• Peng CW, Chen SC, Lai CH, Chen CJ, Chen CC, Mizrahi J, Handa Y. Review:

Clinical Benefits of Functional Electrical Stimulation Cycling Exercise for

Subjects with Central Neurological Impairments. Journal of Medical and

Biological Engineering 2010; 31(1): 1-11.

Page 146: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

146

• Hunter IW, Kearney RE, Jones LA. Estimation of the conduction velocity of

muscle action potentials using phase and impulse response function techniques.

Med. Biol. Eng. Comput. 1987; 25: 121-126.

• Karu ZZ, Durfee WK, Barzilai AM. Reducing muscle fatigue in FES applications

by stimulating with N-let pulse trains. IEEE Trans Biomed Eng. 1995 Aug; 42(8):

809-817.

• Ibitoye MO, Hamzaid NA, Hasnan N, Abdul Wahab AK, Davis GM. Strategies for

Rapid Muscle Fatigue Reduction during FES Exercise in Individuals with Spinal

Cord Injury: A Systematic Review. Lucia A, ed. PLoS ONE. 2016; 11(2):

e0149024.

• Thorsen R, Ferrarin M. Battery powered neuromuscular stimulator circuit for use

during simultaneous recording of myoelectric signals. Med Eng Phys. 2009 Oct;

31(8): 1032-1037.

• Inmann A, Haugland M. Implementation of Natural Sensory Feedback in a

Portable Control System for a Hand Grasp Neuroprosthesis. Med Eng Phys. 2004;

26 (6): 449-458.

• Marquez-Chin C, Marquis A, Popovic MR. EEG-Triggered Functional Electrical

Stimulation Therapy for Restoring Upper Limb Function in Chronic Stroke with

Severe Hemiplegia. Case Reports in Neurological Medicine. 2016; Article ID

9146213, 11 pages.

• Pfurtscheller G. Functional brain imaging based on ERD/ERS. Vision Res. 2001;

41(10-11): 1257-60.

Page 147: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

147

• Veltink PH, Sinkjaer T, Baten CTM, Bergveld P, van der Spek J, Haugland M.

Artificial and natural sensors in FES-assisted human movement control., Proc. 20th

Annu. Int. Conf. IEEE Engineering in Medicine and Biology Society (EMBS).

1998; vol. 5: 2247-2250.

• Ruppin S, Wiesener C, Schauer T. Inertial Sensor-Based Control of Functional

Electrical Stimulation in Paraplegic Cycling. IFESS 2016; La Grande Motte,

France.

• Young K. The effects of EMG-triggered functional electrical stimulation on upper

extremity function in stroke patients. Phys Ther Rehabil Sci. 2013; 2 (1): 1-6

• Thorsen R, Occhi E, Boccardi S, Ferrarin M. Tenodesis grip augmented by EMG

controlled FES. 9th Annual Conference of the International FES Society.

September 2004; Bournemouth, UK.

• Yeom H, Chang Y-H. Autogenic EMG-Controlled Functional Electrical

Stimulation for Ankle Dorsiflexion Control. Journal of neuroscience methods.

2010; 193(1): 118-125.

• Keith MW, Peckham PH, and Thrope B. Implantable functional neuromuscular

stimulation in the tetraplegic hand. The Journal of Hand Surgery. 1989; Volume

14, Issue 3, May: 524-530.

• Prochazka A, Gauthier M, Wieler M, Kenwell Z. The bionic glove: an electrical

stimulator garment that provides controlled grasp and hand opening in

quadriplegia. Arch Phys Med Rehabil. 1997 Jun; 78(6): 608-614.

• IJzerman MJ, Stoffers TS, Groen FACG, Klatte MAP, Snoek GJ, Vorsteveld JHC,

Nathan RH, and Hermens HJ, “The NESS Handmaster orthosis: restoration of hand

Page 148: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

148

function in C5 and stroke patients by means of electrical stimulation. Journal of

rehabilitation sciences. 1996; vol. 9: 86-89.

• Thorsen R, Ferrarin M, Spadone R, Frigo C. Functional Control of the Hand in

Tetraplegics Based on Residual Synergistic EMG Activity. Artifical Organs. 1999;

Volume 23, Issue 5: 470–473

• Saxena S, Nikolić S, Popović D. An EMG-controlled grasping system for

tetraplegics. J Rehabil Res Dev. 1995; 32: 17–24.

• Sennels S, Biering-Sørensen F, Andersen OT, Hansen SD. Functional

Neuromuscular Stimulation Controlled by Surface Electromyographic Signals

Produced by Volitional Activation of the Same Muscle: Adaptive Removal of the

Muscle Response from the Recorded EMG-Signal. IEEE Transactions on

Rehabilitation Engineering. 1997; vol. 5: 195-206.

• Auchstaetter N, Luc J, Lukye S, Lynd K, Schemenauer S, Whittaker M,

Musselman KE. Physical Therapists' Use of Functional Electrical Stimulation for

Clients With Stroke: Frequency, Barriers, and Facilitators. Phys Ther. 2016; 96 (7):

995-1005.

• Cavalcanti Garcia MA, Vieira TMM. Surface electromyography: Why, when and

how to use it. Rev Andal Med Deporte. 2011; 4(1): 17-28.

• De Luca CJ. The use of surface electromyography in biomechanics. J Appl

Biomech. 1997;13:135-63.

• De Luca CJ, Gilmore LD, Kuznetsov M, Roy SH. Filtering the surface EMG

signal: Movement artifact and baseline noise contamination. Journal of

Biomechanics. 2010; Volume 43 , Issue 8:1573 – 1579.

Page 149: DESIGN AND IMPLEMENTATION OF THE FIRMWARE OF A ... · The microcontroller contains a 128 kB flash memory. Since the memory used to save the program corresponds to few kB, we decided

149