mbed-os github

Dependencies:   ADS1015 Faulhaber HTU21D_mod MS5837_potless Sensor_Head_RevB_3 USBDevice_dfu Utilsdfu beep

Fork of ARNSRS_testDFU by POTLESS

main.cpp

Committer:
POTLESS_2
Date:
2018-05-17
Revision:
47:89a088bc8866
Parent:
46:28298df0ac55
Child:
48:9ceb095f397a

File content as of revision 47:89a088bc8866:

#include "mbed.h"
#include <string>
#include "Sensor_head_revB.h"
#include "HTU21D.h"
#include "PID.h"
#include "Faulhaber.h"
#include "Utils.h"
#include "beep.h"
#include "USBSerial.h"

//Commandes  des servos

DigitalOut E5V (PA_4);
#define PWM_SERVO_POUMON PB_15
#define nSleep_SERVO_POUMON PC_6
#define FWD_SERVO_POUMON PB_14
#define REV_SERVO_POUMON PB_13
#define Channel_A_SERVO_POUMON PB_2
#define Channel_B_SERVO_POUMON PB_1
#define HOME_SERVO_POUMON 0

#define PWM_SERVO_FUITE PB_10
#define nSleep_SERVO_FUITE PB_0
#define FWD_SERVO_FUITE PB_4
#define REV_SERVO_FUITE PB_5
#define Channel_A_SERVO_FUITE PC_9
#define Channel_B_SERVO_FUITE PA_8
#define HOME_SERVO_FUITE 90

//Pin de test des alims
#define PIN_V_PILES_ANALOG PA_1
#define PIN_V_PILES_DIGI PC_3
#define PIN_V_USB_DIGI PA_0

//#define OUTPUT(...) { NVIC_DisableIRQ(USART3_IRQn); serialMonit.printf(__VA_ARGS__); fflush(stdout);NVIC_EnableIRQ(USART3_IRQn);}
#define OUTPUT(...) { NVIC_DisableIRQ(USART2_IRQn); serialMonit.printf(__VA_ARGS__); fflush(stdout);NVIC_EnableIRQ(USART2_IRQn);}
#define IHM(...) { NVIC_DisableIRQ(USART3_IRQn); display.printf(__VA_ARGS__); fflush(stdout);NVIC_EnableIRQ(USART3_IRQn);}

//PinName pwm, PinName nSleep, PinName fwd, PinName rev, PinName channelA, PinName channelB, int pulsesPerRev, int Rapport, Encoding encoding = X2_ENCODING
Faulhaber Servo_Poumon("Servo_Poumon", PWM_SERVO_POUMON, nSleep_SERVO_POUMON, FWD_SERVO_POUMON, REV_SERVO_POUMON, Channel_A_SERVO_POUMON, Channel_B_SERVO_POUMON, 16, 207, Faulhaber::X2_ENCODING);
Faulhaber Servo_Fuite("Servo_Fuite", PWM_SERVO_FUITE, nSleep_SERVO_FUITE, FWD_SERVO_FUITE, REV_SERVO_FUITE, Channel_A_SERVO_FUITE, Channel_B_SERVO_FUITE, 16, 207, Faulhaber::X2_ENCODING);

//Moniteur série, Serial 2
//Serial serialMonit(PC_10, PC_11, 115200); // UART 3 pour windev nucleo - version définitive sur uart3 pour carte ARNSRS
//Serial serialMonit(PA_2, PA_3,115200); // UART2 à décommenter pour carte ARNSRS

USBSerial serialMonit;

//Communication avec l'IHM
Serial display(PC_4, PC_5, 115200);

//Moniteur pour le debug avec une nucleo, a commenter avec la carte definitive
//Serial serial(USBTX, USBRX, 115200);

//Init de la lib ARNSRS;
SENSOR_HEAD_REV_B sensors;

//pour Param Venant du PV
const int sizeParam = 50;
char  param[sizeParam];
volatile int indexParam = 0;
bool newParamFlag = false;

//Flag PID ON / OFF
int FLAG_PID = 0;

//Flag pour interrompre l'affichage si on veut...
bool FLAG_AFF = false;

//Flag pour envoyer à l'app windev...
bool FLAG_WINDEV = false;

//Flag pour envoyer à l'IHM...
bool FLAG_DISPLAY = true;

//Flag pour interrompre l'enregistrement si on veut...
bool FLAG_REC = true;

//Flag pour interrompre les demandes O2 en cours ed calibration...
bool FLAG_O2 = true;

//Variables de stockage des infos capteurs
int co2 = 0;
float pression = 0;
float Temp1 = 0;
int ppO2 = 0;
int CellO2_1 = 0;
int CellO2_2 = 0;

//Variables et constantes OTU
float OTU = 0;
float COEF_OTU = 0.83;

//Mesure du temps d'éxecution du loop
Timer REAL_RATE;
float RATE = 0;
float RATE_TRUE = 0;
float Ref_Time = 2.0; //La durée de la boucle désirée...

//HTU21D sur l'I2C
HTU21D temphumid(PB_9, PB_8); //Temp humid sensor || SDA, SCL
float Temp2;
int Humid;

//Data LOG
char to_store[50];
time_t seconds;
char Log_File_Name[] = "                           ";
int count = 0;
int Max_Log_Size = 1800;//1 heure, 1800 lignes donc à multiplier par la fréquence d'enregistrement, Ref_Time, pour voir combien de temps représente un Log...

//Contrôle des servos
float Consigne_poumon = 0;
float volet_poumon_Position = 0;
float Consigne_fuite = 0;
float volet_fuite_Position = 0;
float Volets_Speed = 1;
float Volet_DeadBand = 5;

//Paramètre du PID
float Kc = 40;
float Ti = 0;
float Td = 0;
float RATE_PID = Ref_Time;
float Commande_PID;
int consigne = 210;
float Max_Input = 1000;
float Min_Input = 80;
float Max_Output = 85;//Vérifier la valeur pour angle à laisser ouvert...
float Min_Output = 5;

//Init PID
PID control_Servo(Kc, Ti, Td, RATE_PID);

//Boolean du status de l'appareil, en mode SECU ou nominal
bool EN_MODE_SECU = false;

//Test des alim
//DigitalIn V_PILES_DIGI(PIN_V_PILES_DIGI);

//Test voltage piles
AnalogIn V_PILES_ANALOG(PIN_V_PILES_ANALOG);

int Vusb = 1;
int VPiles = 1;
float VPiles_val = 1;

//Interruption pin
InterruptIn vpile_off_on(PIN_V_PILES_DIGI);
InterruptIn vusb_off_on(PIN_V_USB_DIGI);

//Buzzer
Beep buzzer(PC_8);


void Affichage()
{
    //serialMonit.printf("\r\n");
    serialMonit.printf("  CO2             = %d ppm\r\n"  , co2);
    serialMonit.printf("  PPO2            = %d mb\r\n", ppO2);
    serialMonit.printf("  OTU             = %d \r\n", (int)OTU);
    serialMonit.printf("  Pression        = %f msw\r\n", pression);
    serialMonit.printf("  Temp MS5837     = %f C\r\n", Temp1);
    serialMonit.printf("  Temp HTU21D     = %f C\n\r", Temp2);
    serialMonit.printf("  Humidity        = %d %%\n\r", Humid);
    //serialMonit.printf("\n\r");
    serialMonit.printf("  Cell O2 n 1     = %d\r\n"  , CellO2_1);
    serialMonit.printf("  Cell O2 n 2     = %d\r\n"  , CellO2_2);
    //serialMonit.printf("\r\n");
    serialMonit.printf("  Volet Poumon    = %f\r\n"  , volet_poumon_Position);
    serialMonit.printf("  Volet Fuite     = %f\r\n"  , volet_fuite_Position);
    //serialMonit.printf("\r\n");
    serialMonit.printf("  Temps d execution de la boucle = %f seconde(s)\r\n", (RATE + RATE_TRUE / 1000));
    //serialMonit.printf("\r\n");
    if (FLAG_REC) serialMonit.printf("  Chaine enregistrée = %s\r\n", to_store);
    else serialMonit.printf("  Pas d'enregistrement en cours.");
    //serialMonit.printf("\r\n");
    serialMonit.printf("  V_USB = %f\r\n", Vusb);
    //serialMonit.printf("\r\n\r\n");
    fflush(stdout);
}


//Passage en mode SECU
void Mode_SECU()
{

    //Mise du PID en mode manuel (desactivation...)
    control_Servo.setMode(MANUAL_MODE);

    Consigne_poumon = HOME_SERVO_POUMON;
    Consigne_fuite = HOME_SERVO_FUITE;

    Volets_Speed = 0.1;
    Volet_DeadBand = 10;

/*
    while(1) {
        wait_ms(100);
        if (Servo_Poumon.Pos_OK() == true) break;
        if (Servo_Fuite.Pos_OK() == true) break;
    }
*/

    OUTPUT("  Appareil en mode SECU\r\n");

    wait_ms(100);

    EN_MODE_SECU = true;

    wait_ms(100);
    int Pos_P = Servo_Poumon.getPulses();
    UTILS::Store_A_Val((float)Pos_P, "Servo_Poumon.sys");
    DEBUG("  position volet poumon sauvegardée = %d pulse(s)\r\n", Pos_P);
    OUTPUT("  Volet poumon en sécu\r\n");
    
    int Pos_F = Servo_Fuite.getPulses();
    UTILS::Store_A_Val((float)Pos_F, "Servo_Fuite.sys");
    DEBUG("  position volet fuite sauvegardée = %d pulse(s)\r\n", Pos_F);
    OUTPUT("  Volet fuite en sécu\r\n");
    
    Servo_Poumon.Sleep();
    Servo_Fuite.Sleep();
}

//Sequence d'arrêt
void Stop_Sequence()
{
    OUTPUT("  Mise en veille de l'appareil.\r\n");

    wait(1);

    Mode_SECU();
    
    wait(1);
    //ejection de la flash pour pas crasher le system de fichiers
    UTILS::UnMount_Flash();
    
    OUTPUT("  Ejection de la Flash\r\n");
    wait(1);
    buzzer.beep(1000,0.5);
    wait(1);
    // préparation deepsleep

    /*
    //première méthode mais je ne sais pas ce que ça consomme et il faut normalement reduire le frequence d'horloge avant
    //il est possible que ça génère un plantage et la rtc ne fonctionnera pas?
    HAL_PWREx_EnableLowPowerRunMode();
    DEBUG("----------------LOW POWER RUN MODE--------------------\r\n");

    bool isDSallowed;
    isDSallowed =  sleep_manager_can_deep_sleep();
    DEBUG("  Deep sleep autorisé ? %i\r\n", isDSallowed);
    wait(1.0);

    DEBUG("\n\r Deepsleep tentative normale !(bouton bleu pour ressortir)\n");
    wait(0.1);

    sleep_manager_sleep_auto(); // ne marche pas, je ne sais pas pk
    */
    
    /*
    HAL_PWR_DisableWakeUpPin(PWR_WAKEUP_PIN2); // pour PC_13
    // Clear wake up Flag
    __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WUF2);
    // Enable wakeup pin WKUP2
    HAL_PWR_EnableWakeUpPin(PWR_WAKEUP_PIN2_LOW); // low parce qu'on veut que ça redémarre avec le user button TODO à passer sur High pour que ça redémarrage avec l'arrivée du hus sur l'USB
    */
    
    HAL_PWREx_EnablePullUpPullDownConfig() ;
    HAL_PWREx_EnableGPIOPullDown(PWR_GPIO_A, PWR_GPIO_BIT_0);

    HAL_PWR_DisableWakeUpPin(PWR_WAKEUP_PIN1); // pour PA_0
    // Clear wake up Flag
    __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WUF1);
    // Enable wakeup pin WKUP2
    HAL_PWR_EnableWakeUpPin(PWR_WAKEUP_PIN1); // high est la valeur par défaut

    // Set RTC back-up register RTC_BKP31R to indicate
    //later on that system has entered shutdown mode
    WRITE_REG( RTC->BKP31R, 0x1 );
    //Enter shutdown mode
    DEBUG("\n\r Attention c'est du brutal !  bouton bleu pour ressort.... ZZZZZZZ ZZZZZ !!!\n");

    HAL_PWREx_EnterSHUTDOWNMode();
}

//Fonction test de valeur d'entrée digitale
int Power_Test(DigitalIn& pin)
{
    pin.mode(PullDown);

    if(!pin) {
        Stop_Sequence();
        return 0;
    } else {
        return 1;
    }
}

//Fonction test de valeur d'entrée analogique
float Power_Test(AnalogIn& pin)
{
    float Val = pin.read();
    return Val;
}

//Contrôle du status de l'appareil / des constantes
bool Check()
{
    if (ppO2 > 100)
        return true;//Situation OK
    else
        return false;//Situation dégradée
}

//Calcul des OTU
float Calcul_OTU()
{
    /*
    La formule suivante permet de calculer la quantité d' OTU accumulée
    OTU = T * (2* PpO2 -1)0,83
    avec :
    T = temps de plongée en minutes
    PpO2 = pression partielle d’ oxygène en bars
    */

    if (ppO2 > 500) {
        float val = (2 * (float)ppO2/1000 - 1);//je divise par 1000 car la PP est en mb...
        OTU += Ref_Time * pow(val, COEF_OTU);
    }
}

//Thread d'intérogation des capteurs, positions servo
void SENSORS_thread()
{
    while (true) {
        //DEEP_DEBUG("  SENSORS_thread\r\n");

        //CO2 sur Cozir
        co2 = sensors.requestCO2();
        //P / T sur MS5837
        pression = sensors.requestPress();
        Temp1 =  sensors.requestTemp();
        //PPO2 sur ADS1015
        if (FLAG_O2) ppO2 = sensors.requestPpO2();
        //Cell O2 en mV
        if (FLAG_O2) CellO2_1 = sensors.requestCellO2_1();
        if (FLAG_O2) CellO2_2 = sensors.requestCellO2_2();

        //HTU21D
        Temp2 = temphumid.sample_ctemp();
        Humid = temphumid.sample_humid();

        //Retour position des servos
        volet_poumon_Position = Servo_Poumon.Get_Position();
        volet_fuite_Position = Servo_Fuite.Get_Position();

        //Calcul des OTU
        Calcul_OTU();

    }
}

void GO_TO_thread()
{
    while (true) {
        //DEEP_DEBUG("  GO_TO_Thread\r\n");

        //Servo_Poumon.Go_To_Prop(Consigne_poumon);
        //Servo_Poumon.Go_To_PID(Consigne_poumon, Volet_DeadBand);
        Servo_Poumon.Go_To(Consigne_poumon, Volets_Speed, Volet_DeadBand);

        //Servo_Fuite.Go_To_Prop(Consigne_fuite);
        //Servo_Fuite.Go_To_PID(Consigne_fuite, Volet_DeadBand);
        Servo_Fuite.Go_To(Consigne_fuite, Volets_Speed, Volet_DeadBand );
    }
}

void SECU_thread()
{
    while (true) {

    }
}

//Callback de l'intérruption des envois de commandes depuis le terminal
void callbackParam()
{


    while(serialMonit.readable()) {
        if ((indexParam  == sizeParam) || newParamFlag  == true) { //éviter la saturation du buffer
            NVIC_DisableIRQ(USART2_IRQn);  // USART 2 pour carte ARNSRS
            char char_flush = serialMonit.getc();
            NVIC_EnableIRQ(USART2_IRQn); // USART 2 pour carte ARNSRS
        } else {
            NVIC_DisableIRQ(USART2_IRQn); // USART 2 pour carte ARNSRS
            param [indexParam ++] = serialMonit.getc();//chargement du buffer dans le message
            if ((indexParam == sizeParam) || (param[indexParam - 1] == '\n')) {//le message est complet ou nouvelle ligne ou autre si on veut...
                param[indexParam] = 0;
                newParamFlag  = true;
            }
            NVIC_EnableIRQ(USART2_IRQn); // USART 2 pour carte ARNSRS
        }
    }
}

void Decoding_Message(char message [])
{

    char com[20] = "";
    char numb[30] = "";

    sscanf(message,"%s %s",&com , &numb);

    DEEP_DEBUG("\r\n  Commande = %s       Valeur = %s \r\n\r\n", com, numb);
    //serialMonit.printf("\r\n  Commande = %s       Valeur = %s \r\n\r\n", com, numb);

    OUTPUT("?\r\n");

    if (0 == strcmp(com, "secu")) {
        Mode_SECU();
    } else if (0 == strcmp(com, "PING")) {
        FLAG_PID = 0;
        FLAG_AFF = false;
        FLAG_WINDEV = false;
        control_Servo.setMode(MANUAL_MODE);
    } else if (0 == strcmp(com, "ARNSRS_ID")) {
        OUTPUT("Changement de l'ID de l'appareil pour le N°: %s?\r\n", numb);
        UTILS::Store_A_Val(atoi(numb), "ARNSRS_ID");
    } else if (0 == strcmp(com, "monit")) {
        FLAG_AFF = false;
        FLAG_WINDEV = true;
    } else if (0 == strcmp(com, "debug")) {
        FLAG_AFF = false;
        FLAG_WINDEV = false;
    } else if (0 == strcmp(com, "Head_ID")) {
        //On l'enregistre dans l'eeprom
        OUTPUT("Changement de l'ID de la tête capteur pour le N°: %s\r\n", numb);
        UTILS::write_EEPROM(numb, HEAD_ID);
    } else if (0 == strcmp(com, "O2_1_ID")) {
        //On l'enregistre dans l'eeprom
        UTILS::write_EEPROM(numb, CELL_O2_1_ID);
    } else if (0 == strcmp(com, "O2_2_ID")) {
        //On l'enregistre dans l'eeprom
        UTILS::write_EEPROM(numb, CELL_O2_2_ID);
    } else if (0 == strcmp(com, "CO2_ID")) {
        //On l'enregistre dans l'eeprom
        UTILS::write_EEPROM(numb, CO2_ID);
    } else if (0 == strcmp(com, "calib_O2")) {
        FLAG_O2 = false;
        wait_ms(100);
        float Val =  sensors.Calibrate_O2(atoi(numb));
        OUTPUT("  Calibration O2 dans l'air = %f\r\n", Val);
        wait_ms(100);
        FLAG_O2 = true;
    } else if (0 == strcmp(com, "calib_CO2_A")) {
        int Val = sensors.Calibrate_CO2();
        OUTPUT("  Calibration CO2 dans l'air = %d\r\n", Val);
    } else if (0 == strcmp(com, "flash_i")) {
        UTILS::Flash_Infos(&serialMonit);
    } else if (0 == strcmp(com, "flash_u")) {
        OUTPUT("  Démontage de la Flash.\r\n");
        FLAG_REC = false;
        UTILS::UnMount_Flash();
    } else if (0 == strcmp(com, "flash_m")) {
        OUTPUT("  Montage de la Flash.\r\n");
        UTILS::Mount_Flash();
    } else if (0 == strcmp(com, "check_F")) {
        OUTPUT("  ARNSRS_ID.sys   = %d\r\n", (int)UTILS::Read_A_Val("ARNSRS_ID.sys"));
        OUTPUT("  Servo_Poumon.sys   = %d\r\n", (int)UTILS::Read_A_Val("Servo_Poumon.sys"));
        OUTPUT("  Servo_Fuite.sys    = %d\r\n", (int)UTILS::Read_A_Val("Servo_Fuite.sys"));
    } else if (0 == strcmp(com, "check_E")) {
        sensors.Sensor_head_check(&serialMonit);
    } else if (0 == strcmp(com, "rec")) {
        if (FLAG_REC) {
            FLAG_REC = false;
            OUTPUT("  Arrêt du Data Logging.\r\n");
        } else {
            FLAG_REC = true;
            OUTPUT("  Démarrage Data Logging dans %s\r\n", Log_File_Name);
        }
    } else if (0 == strcmp(com, "help")) {
        FLAG_AFF = false;
        UTILS::Help(&serialMonit);
    } else if (0 == strcmp(com, "start")) {
        FLAG_AFF = true;
    } else if (0 == strcmp(com, "stop")) {
        FLAG_AFF = false;
        //UTILS::Help();
    } else if (0 == strcmp(com, "flash_c")) {
        FLAG_REC = false;
        UTILS::Clean_Flash();
    } else if (0 == strcmp(com, "flash_f")) {
        FLAG_REC = false;
        UTILS::Clean_Flash_All();
    } else if (0 == strcmp(com, "dir")) {
        FLAG_WINDEV = false;
        OUTPUT("$\r\n");
        wait(0.5);
        UTILS::Dir_Flash(&serialMonit);
    } else if (0 == strcmp(com, "get")) {
        wait_ms(100);
        char filename[20];
        UTILS::Read_Flash_File(&serialMonit, numb);
        wait_ms(100);
    } else if (0 == strcmp(com, "del")) {
        FLAG_REC = false;
        char filename[20];
        UTILS::Delete_Flash_File(numb);
        OUTPUT("$\r\n");
        wait(0.5);
        UTILS::Dir_Flash(&serialMonit);
        FLAG_REC = true;
    } else if (0 == strcmp(com, "file_s")) {
        char filename[20];
        UTILS::Get_File_Size(&serialMonit, numb);
    } else if (0 == strcmp(com, "calib_p")) {
        Consigne_poumon = 0;
        volet_poumon_Position = 0;
        Servo_Poumon.reset();
        OUTPUT("  Volet poumon Calibré.\r\n");
    } else if (0 == strcmp(com, "calib_f")) {
        Consigne_fuite = 0;
        volet_fuite_Position = 0;
        Servo_Fuite.reset();
        OUTPUT("  Volet fuite Calibré.\r\n");
    } else if (0 == strcmp(com, "sleep")) {
        Stop_Sequence();
    } else if (0 == strcmp(com, "time")) {//Depuis terminal MAC taper : " date +%s "
        set_time(atoi(numb));
        OUTPUT("  La RTC a été mise à l'heure.\r\n");
    } else if (0 == strcmp(com, "c_pou")) {
        Consigne_poumon = atof(numb);
        DEBUG("  Servo Poumon    = %f\r\n", Consigne_poumon);
    } else if (0 == strcmp(com, "c_fui")) {
        Consigne_fuite = atof(numb);
        DEBUG("  Servo Fuite     =  %f\r\n", Consigne_fuite);
    } else if (0 == strcmp(com, "mp_pou")) {
        Consigne_poumon += atof(numb);
        DEBUG("  Servo Poumon    = %f\r\n", Consigne_poumon);
    } else if (0 == strcmp(com, "mp_fui")) {
        Consigne_fuite += atof(numb);
        DEBUG("  Servo Fuite     =  %f\r\n", Consigne_fuite);
    } else if (0 == strcmp(com, "reset")) {
        FLAG_REC = false;
        UTILS::UnMount_Flash();
        OUTPUT("  Reset de l'appareil.\r\n");
        wait(1);
        NVIC_SystemReset();
    } else if (0 == strcmp(com, "Kc")) {
        Kc = atof(numb);
        control_Servo.reset();
        control_Servo.setTunings(Kc, Ti, Td);
        OUTPUT("  MAJ PID -->  Kc = %f   Ti = %f   Td = %f?\r\n", Kc, Ti, Td);
    } else if (0 == strcmp(com, "Ti")) {
        Ti = atof(numb);
        control_Servo.reset();
        control_Servo.setTunings(Kc, Ti, Td);
        OUTPUT("  MAJ PID -->  Kc = %f   Ti = %f   Td = %f?\r\n", Kc, Ti, Td);
    } else if (0 == strcmp(com, "Td")) {
        Td = atof(numb);
        control_Servo.reset();
        control_Servo.setTunings(Kc, Ti, Td);
        OUTPUT("  MAJ PID -->  Kc = %f   Ti = %f   Td = %f?\r\n", Kc, Ti, Td);
    } else if (0 == strcmp(com, "Cons")) {
        consigne = atoi(numb);
        control_Servo.setSetPoint(consigne);
        OUTPUT("  MAJ CONSIGNE PID -->  Consigne = %d?\r\n", consigne);
    } else if (0 == strcmp(com, "PID")) {
        if (FLAG_PID == 1) {
            control_Servo.setMode(MANUAL_MODE);
            OUTPUT("  PID OFF?\r\n");
            FLAG_PID = 0;
        } else if (FLAG_PID == 0) {
            control_Servo.setMode(AUTO_MODE);
            OUTPUT("  PID ON?\r\n");
            FLAG_PID = 1;
        }
    } else {

        sensors.cozirSend(message);
    }

    strcpy(param," ");
    indexParam = 0;
    newParamFlag = false;
}

void Create_File_Name_Date()
{
    //Du nom du fichier Date / heure
    seconds = time(NULL);
    char Time[40];
    strftime(Time, 40, "%a_%d_%m_%Y_%H%M", localtime(&seconds));
    sprintf(Log_File_Name, "%s_LOG.csv", Time);
    DEBUG("  Nouveau fichier LOG = %s \r\n", Log_File_Name);
}

void Create_File_Name_Index()
{
    //Du nom du fichier par Index
    sprintf(Log_File_Name, "LOG_%d.csv", UTILS::File_Index());
    DEBUG("  Nouveau fichier LOG = %s \r\n", Log_File_Name);
}

int main()
{
    
    HAL_Init();

    __HAL_RCC_PWR_CLK_ENABLE();
    HAL_PWR_EnableBkUpAccess();

    //Ci-dessous commande pour formater une nouvelle carte
    //UTILS::Format_Flash();

    //Montage Flash
    UTILS::Mount_Flash();

    //Liste des fichiers sur la Flash
    //UTILS::Dir_Flash(&serialMonit);

    if (UTILS::File_Exist("ARNSRS_ID.sys") == false) {
        UTILS::Store_A_Val(000, "ARNSRS_ID.sys");
        DEBUG("ARNSRS ID forcée à 000\r\n");
    }
    /*
while(1){
    OUTPUT("\r\n\r\n  Démarrage de l'appareil, veuillez patienter...\r\n\r\n");}
    */

    //Vérification RTC, si on est le 01/01/70, c'est qu'il y a un problème...
    seconds = time(NULL);
    char YEAR[10];
    strftime(YEAR, 10, "%D", localtime(&seconds));
    if (0 == strcmp(YEAR, "01/01/70")); //OUTPUT("  Vous devez régler la RTC...\r\n\r\n");

    bool calib_O2 = false;
    bool calib_CO2 = false;

    /*
    Par défaut les valeur en cas de calibration sur true sont les suivant

       nbCalibO2 = 5
       Mode = SPOOLING
       Filtre = DIGI_FILTER32
       CalibrationCO2 = "CALIB_AIR"

       Parfois la calibration du Cozir coince...faire reset et relancer...

       Pour calibrer avec ces paramètres :

       sensors.Sensors_INIT(true, true);

       Pour changer utiliser la syntaxe suivante :

       sensors.Sensors_INIT(true, true, true, 5, SPOOLING, DIGI_FILTER32, CALIB_AIR);

    */

    sensors.Sensors_INIT(calib_O2, calib_CO2);

    wait(1);

    //Création du nouveau fichier LOG par index / par date.
    //Create_File_Name_Index();
    Create_File_Name_Date();

    //Création et écriture du header du fichier LOG
    sensors.Create_Header(Log_File_Name);

    Servo_Poumon.Init("Servo_Poumon.sys");
    Servo_Fuite.Init("Servo_Fuite.sys");

    //OUTPUT("  Demarrage des threads...\r\n\r\n");

    /*

    Pour mémoire, les réglage de priorité des thread

          osPriorityIdle          = -3,          ///< priority: idle (lowest)
          osPriorityLow           = -2,          ///< priority: low
          osPriorityBelowNormal   = -1,          ///< priority: below normal
          osPriorityNormal        =  0,          ///< priority: normal (default)
          osPriorityAboveNormal   = +1,          ///< priority: above normal
          osPriorityHigh          = +2,          ///< priority: high
          osPriorityRealtime      = +3,          ///< priority: realtime (highest)
          osPriorityError         =  0x84        ///< system cannot determine priority or thread has illegal priority
    */

    wait(1);

    Thread thread_Volets(osPriorityNormal);

    thread_Volets.start(callback(GO_TO_thread));

    //OUTPUT("  Contrôle des volets démarré\r\n\r\n");

    wait(1);

    Thread thread_Secu(osPriorityNormal);

    thread_Secu.start(callback(SECU_thread));

    //OUTPUT("  Contrôle des paramètres de sécu démarré\r\n\r\n");

    wait(1);

    Thread thread_Head(osPriorityNormal);

    thread_Head.start(callback(SENSORS_thread));

    //OUTPUT("  Tête capteurs démarrée\r\n\r\n");

    wait(1);

    //Init PID
    //Entrée PPO2 entre 100 et 1000 mb
    control_Servo.setInputLimits(Min_Input, Max_Input);
    //Sortie servo entre 0 et 100 %
    control_Servo.setOutputLimits(Min_Output, Max_Output);
    //Mode auto au démarrage
    control_Servo.setMode(MANUAL_MODE);
    //Consigne à x mb
    control_Servo.setSetPoint(consigne);

    //OUTPUT("  Cliquez sur le bouton help pour voir la liste des \r\n  commandes administrateur disponibles.\r\n");

    
    OUTPUT("$\r\n");
    wait(0.5);
    UTILS::Dir_Flash(&serialMonit);

    serialMonit.attach(&callbackParam);
    
    vusb_off_on.fall(&Stop_Sequence);
    
    E5V = 1;

    buzzer.beep(1000,0.5);
    
    while (true) {

        //Démarrage du Timer mesurant le temps d'éxecution du code
        REAL_RATE.start();

        if (newParamFlag) {
            DEEP_DEBUG("  From PC = %s\r\n", param);
            Decoding_Message(param);
        }

        //Fabrication de la chaine Date / heure
        seconds = time(NULL);
        char Time_buf[32];
        strftime(Time_buf, 32, "%D %I-%M-%S ", localtime(&seconds));

        //Fabrication de la chaine à enregistrer
        sprintf(to_store,"<%s;%d;%d;%.2f;%d;%.2f;%.2f;%d;%d;%d;%.2f;%.2f;%d;%.3f;%.3f;%.3f;%d>",
                Time_buf,
                co2,
                ppO2,
                pression,
                (int)OTU,
                Temp1,
                Temp2,
                Humid,
                CellO2_1,
                CellO2_2,
                volet_poumon_Position,
                volet_fuite_Position,
                FLAG_PID,
                Kc,
                Ti,
                Td,
                consigne
               );


        //Pour windev
        if (FLAG_WINDEV) {
            OUTPUT("%s\r\n", to_store);
        }
        
        //Pour l'IHM
        if (FLAG_DISPLAY) {
            IHM("%s\r\n", to_store);
        }
       
        //Vers le moniteur série
        if (FLAG_AFF) {
            NVIC_DisableIRQ(USART3_IRQn); // USART 2 si ARNSRS mais plus utilisé
            Affichage();
            NVIC_EnableIRQ(USART3_IRQn); // USART 2 si ARNSRS mais plus utilisé
        }

        //Enregistrement de la chaine
        if (FLAG_REC) {
            UTILS::Write_Flash_File(to_store, Log_File_Name);
            count ++;
            if (count > Max_Log_Size) {
                Create_File_Name_Date();
                sensors.Create_Header(Log_File_Name);
                count = 0;
                OUTPUT("$\r\n");
                wait(0.5);
                UTILS::Dir_Flash(&serialMonit);
            }
        }

        //Update du PID
        control_Servo.setProcessValue(ppO2);
        //Nouvelle sortie servo fuite si on est pas en mode SECU
        //if(!EN_MODE_SECU) Consigne_fuite = control_Servo.compute();

        //Arrêt du Timer mesurant le temps d'éxecution du code
        REAL_RATE.stop();
        //Définition de la nouvelle valeur du temps d'échantillonage du PID.
        RATE = REAL_RATE.read();
        //Reset du Timer
        REAL_RATE.reset();

        //Pour ralentir le code à Ref_Time seconde fixe quelque soit les intéruptions du loop....
        if (Ref_Time > RATE) {
            RATE_TRUE = (Ref_Time - RATE) * 1000;
        } else {
            RATE_TRUE = 0;

            //control_Servo.setInterval(RATE);

            DEEP_DEBUG("Pour ralentir le code, Ref_Time doit être supérieur à %f seconde(s)\r\n\n", RATE);
        }

        wait_ms(RATE_TRUE);
    }
}