fast-feedback virtual target task code on STM Nucleo

Dependencies:   mbed

states.cpp

Committer:
gwappa
Date:
2018-05-24
Revision:
5:849446d19406
Parent:
4:fcf597f82632
Child:
7:6744ec9ccc25

File content as of revision 5:849446d19406:

#include "states.h"
#include "rig.h"
#include "automaton.h"
#include "IO.h"

#define STATE_IS_LOGGED

#ifdef STATE_IS_LOGGED
#define LOGSTATE(S) IO::info(#S);
#else
#define LOGSTATE(S)
#endif

inline us_timestamp_t ms_to_us(const uint16_t& ms)
{
    return ((us_timestamp_t)ms)*1000;
}

void (*whiskhandler)() = 0;
void (*lickhandler)() = 0;
bool logged = false;

void whiskcallback() {
    if (logged) {
        trial.whisking_events.add(timer.read_ms());
    }
    if (whiskhandler != 0) {
        whiskhandler();
    }
}

void lickcallback() {
    if (logged) {
        trial.licking_events.add(timer.read_ms());
    }
    if (lickhandler != 0) {
        lickhandler();
    }
}

void finalize() {
    taskOut.write(0);
    trial.writeToSerial();
    timer.stop();
    timer.reset();
}

void Delay::setup() {
    LOGSTATE(Delay)
    
    // initialize the trial-related params
    trial.reset(task);
    
    // configure the flags
    taskOut.write(1);
    cueOut.write(0);
    enableOut.write(1); // for Pair
    rewardOut.write(0);
    
    // configure the interrupts
    whiskIn.rise(&whiskcallback);
    lickIn.rise(&lickcallback);
    // no whisk handler, no lick handler
    // only to be logged
    logged = true;
    
    // sets the timeout for the next state
    stateTimeout.attach_us(&automaton::jump<Delay,Cued>, ms_to_us(trial.delay_dur_ms)); // for Pair
    
    // update the timestamp
    trial.starting = timer.read_ms();
    timer.start();
}

void Delay::teardown() {
    // do nothing
}

void Cued::setup() {
    LOGSTATE(Cued)
    
    // configure the interrupts
    whiskhandler = &automaton::jump<Cued,WithResp>;
    // no lick handler
    // remains to be logged
    
    // sets the timeout for the next state
    stateTimeout.attach_us(&automaton::jump<Cued,NoResp>, ms_to_us(task.cue_dur_ms.value)); // for Pair
    
    // update the timestamp
    trial.cuestarting = timer.read_ms();
    trial.waiting     = trial.cuestarting - trial.starting;
}

void Cued::teardown() {
    whiskhandler = 0;
    stateTimeout.detach();
}

void WithResp::setup() {
    LOGSTATE(WithResp)
    
    trial.response |= TrialFlags::Responded;
    
    // TODO: open/close the valve
    
    stateTimeout.attach_us(&automaton::done<WithResp>, ms_to_us(task.post_dur_ms.value));
}

void WithResp::teardown() {
    finalize();
}

void NoResp::setup() {
    LOGSTATE(NoResp)
    
    trial.response &= ~TrialFlags::Responded;
    
    stateTimeout.attach_us(&automaton::done<NoResp>, ms_to_us(task.post_dur_ms.value));
}
void NoResp::teardown() {
    finalize();
}