Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Objective

The objective of this tutorial is to explore an easy way to write visually logic code for the CrcDuino
that repeats the loop() part of the code as fast as possible (scan time minimization), all while
allowing to perform actions in a sequential, orderly and predictable manner.

2 coding methods are shown. Both accomplish the same thing, using the same wiring.

  • Using IF statements: the easiest, most visual way to go for beginners.

  • Using a Switch-Case statement: a more compact and efficient way to go, to use once you’re comfortable with the why’s and how’s of the IF statement method.

Tip

Tutorial 11 gives a walkthrough of a similar program structure.

...

Objectif

L’objectif de ce tutoriel est d’explorer une façon facile d'écrire un programme visuellement logique pour le CRCduino qui répète la section loop() en boucle aussi vite que possible, tout en permettant d’exécuter des actions dans une séquence ordonnée et prévisible.

2 styles sont présentés ci-dessous. Ils accomplissent tous deux la même chose, avec le même circuit.

  • En utilisant des « if »: la façon la moins complexe pour des débutants

  • En utilisant des « switch-case »: une façon un peu plus compacte et efficace, à utiliser pour passer au prochain nouveau.

Tip

Le Tutoriel 11 démontre un processus basé sur cette même structure.

Schéma électrique et présentation complète

View file
nameCrcDuino_Tuto5_PlansElectriques_20201119.pdf

Code -

...

avec des « IF »

Téléchargez le code de démonstration:

View file
nameTutorial05_1_SequentialProgramStructure_IF.ino

This is a transcript of the codeQui est ici retranscrit:

Code Block
languagecpp
//***************************************************************************
// Tutoriel CrcDuinoCRCduino Tutorial055.1 - exemple exampled'une ofstructure ade sequentialprogramme programséquentiel structurepour forrobot autonomousautonome, robots; using if statementsà l'aide de « if »
// NOTE: Incontrairement contraryaux toautres thetutoriels, otherle tutorials, the Normally Closed contact of the buttons and limit switch is used herecontact Normalement Fermé des boutons et de la « limit switch » est ici utilisé.
//       Cela Thisveut meansdire thatque, when the button or switch is not press, "LOW" will be read since an electrical continuity to GND
//      is established. When they are pressed, the pin will therefore readlorsque le bouton ou la « switch » ne sont pas appuyés, la valeur lue sera "LOW", puisqu'il y
//        aura un chemin direct vers le GND. À l'inverse, lorsqu'appuyés, la valeur lue sera "HIGH".
//      Why doPourquoi wechanger, doalors thatque here,tous insteadles ofautres thetutoriels methodutilisent usingdes theboutons NO contact? JustPour tovous showmontrez youque thattous allles pathschemins leadmènent toà Rome :)
//***************************************************************************
#include <CrcLib.h>

//Renaming pins with significant names C'est pratique d'avoir un nom pour chaque port de contrôle
#define NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE CRC_DIG_1
#define NEXTPROCHAINE_STEPETAPE_EVENPAIRE CRC_DIG_2

//Variable declaration Déclaration des variables
//Step management variablesÉtapes
bool stepSleepdodo = LOWfalse;
bool step1etape1 = LOWfalse;
bool step2etape2 = LOWfalse;
bool step3etape3 = LOWfalse;

//***************************************************************************

void setup() {
  CrcLib::Initialize();
  
  Serial.begin(2000000);  //Start theÉtablir Serial Monitor communication for on computer screen display, at a high baud rate for faster code executionla connection à la console

  CrcLib::SetDigitalPinMode(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE, INPUT); //Digital portsInitialiser needles toports be tell wether they are used as inputs or outputs
  comme entrées
  CrcLib::SetDigitalPinMode(NEXTPROCHAINE_STEPETAPE_EVENPAIRE, INPUT);
  
  //We want to be in sleep mode upon startup
  stepSleep = HIGH; step1 = LOW; step2 = LOW; step3 = LOW;
   Au début du programme, nous souhaitons être en train de dormir
  dodo = true; etape1 = false; etape2 = false; etape3 = false;
}

//***************************************************************************

void loop() {
  CrcLib::Update();
  //We continuously want to print on serial
monitor
thevoid stateloop() of{
our program (what step it's in)CrcLib::Update();

  //So weAfficher willen printcontinu atsur everyla programconsole scanl'état (du aprogramme scan beingquelle anétape exectuionnous ofsommes "loop(rendus)"
  //Remember: LOWvrai means "0", and HIGH means "anything but "0"sera affiché comme 1 et faux comme 0
  Serial.print("stepSleep  dodo: "); Serial.print(stepSleepdodo);
  Serial.print(" step1etape1: "); Serial.print(step1etape1);
  Serial.print(" step2etape2: "); Serial.print(step2etape2);
  Serial.print(" step3etape3: "); Serial.print(step3etape3);
  Serial.print(" durée scande la timeboucle: "); Serial.println( CrcLib::GetDeltaTimeMicros() ); //Print the value returned by GetDeltaTime, which is the scan time  // Affiche la durée de la dernière boucle

//------------------
  if (stepSleepdodo)
  {

    //The Le code you'dà wantexécuter tolors executedu during stepSleep would go heremode repos
     //When theQuand steples exitingactions conditionsuivantes issont metexécutées (weon pressappuie thesur button/switchun andbouton themais other one is not pressed)...pas l'autre), quitter l'état repos…
    if( CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE) == HIGH && CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_EVENPAIRE) == LOW)       {
      //...we change the steps configuration to take another branch ( if() statement ) during the next scans… on change de configuration pour être à une autre étape la prochaine fois
      stepSleepdodo = LOWfalse; step1etape1 = HIGHtrue; step2etape2 = LOWfalse; step3etape3 = LOWfalse;
    }
  }
//------------------
  if (step1etape1)
  {
     //The Le code you'dà want to execute during step1 would go here
exécuter durant la première étape irait ici
    //When theQuand steples exitingactions conditionsuivantes issont metexécutées (weon pressappuie thesur button/switchun andbouton themais other one is not pressed)...pas l'autre), quitter l'étape 1…
    if( CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_EVENPAIRE) == HIGH && CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE) == LOW )
    {
      //...we … on change the stepsde configuration topour takeêtre anotherà branchune (autre if()étape statementla )prochaine during thefois
next scans     dodo  stepSleep = LOWfalse; step1etape1 = LOWfalse; step2etape2 = HIGHtrue; step3etape3 = LOWfalse;
    }  
  }
//------------------
  if (step2etape2)
  {
    //The Le code you'dà wantexécuter todurant executela during2e step2étape would go here
irait ici
    //When theQuand steples exitingactions conditionsuivantes issont metexécutées (weon appuie presssur theun button/switchbouton andmais the other one is not pressed)...pas l'autre), quitter l'étape 2…
    if( CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE) == HIGH && CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_EVENPAIRE) == LOW )
    {) {
      // … on change de configuration pour être à une autre étape la prochaine fois
      stepSleepdodo = LOWfalse; step1etape1 = LOWfalse; step2etape2 = LOWfalse; step3etape3 = HIGHtrue;
    }
  }
//------------------
  if(step3etape3)
  {
    //The Le code you'd want to execute during step3 would go here

    //When the step exiting condition is metà exécuter durant la 3e étape irait ici
    // Quand les actions suivantes sont exécutées (on appuie sur un bouton mais pas l'autre), quitter l'étape 2…met (we press the button/switch and the other one is not pressed)...
    if ( CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_EVENPAIRE) == HIGH && CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE) == LOW )
    {
      //...we change the steps configuration to take another branch ( if() statement ) during the next scanson change de configuration pour être à une autre étape la prochaine fois
      stepSleepdodo = HIGHtrue; step1etape1 = LOWfalse; step2etape2 = LOWfalse; step3etape3 = LOWfalse;
    }
  }
//------------------

}

Code -

...

Avec un « switch-case »

Téléchargez le code de démonstration:

View file
nameTutorial05Tutoriel05_2_SequentialProgramStructureStructureProgrammeSequentiel_Switch.ino

This is a transcript of the codeQui est ici retranscrit:

Code Block
languagecpp
//***************************************************************************
// Tutoriel CrcDuinoCRCduino Tutorial055.2 - exemple exampled'une ofstructure ade sequentialprogramme programséquentiel structurepour forrobot autonomousautonome, robots; using a Switch-Case statementà l'aide d'un « switch-case »
//NOTE: In contrary to the other tutorials, the Normally Closed contact of the buttons and limit switch is used here.
// NOTE: contrairement aux autres tutoriels, le contact Normalement Fermé des boutons et de la « limit switch » est ici utilisé.
//       Cela Thisveut meansdire thatque, when the button or switch is not press,lorsque le bouton ou la « switch » ne sont pas appuyés, la valeur lue sera "LOW", willpuisqu'il bey
read// since an electrical continuity to GND // aura un chemin direct vers isle establishedGND. When they are pressed, the pin will therefore readÀ l'inverse, lorsqu'appuyés, la valeur lue sera "HIGH".
//      Why doPourquoi wechanger, doalors thatque here,tous insteadles ofautres thetutoriels methodutilisent usingdes theboutons NO contact? JustPour tovous showmontrez youque thattous allles pathschemins leadmènent toà Rome :)
//***************************************************************************
#include <CrcLib.h>

//Renaming pins with significant names
#define NEXT_STEP_ODDh>

// C'est pratique d'avoir un nom pour chaque port de contrôle
#define PROCHAINE_ETAPE_IMPAIRE CRC_DIG_1
#define NEXT_STEP_EVEN CRC_DIG_2

using namespace Crc;

int currentStep = 0; //Step management variable PROCHAINE_ETAPE_PAIRE CRC_DIG_2

enum etape_t {
  DODO = 0,
  ETAPE1 = 1,
  ETAPE2 = 2,
  ETAPE3 = 3
};

etape_t etape; // Variable d'état courant
//***************************************************************************
void setup() {
  CrcLib::Initialize();
  
  Serial.begin(2000000);  //Start the Serial Monitor communication for on computer screen display, at a high baud rate for faster code execution// Établir la connection à la console

  CrcLib::SetDigitalPinMode(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE,INPUT); //Digital portsInitialiser needles toports becomme tellentrées
wether they are used as inputs or outputs
  CrcLib::SetDigitalPinMode(NEXTPROCHAINE_STEPETAPE_EVENPAIRE,INPUT);
  
  // currentStepAu début =du 0; //We want to be in sleep mode upon startup
  programme, nous souhaitons être en train de dormir
  etape = DODO;
}
//***************************************************************************
void loop() {
  CrcLib::Update();
  //We continuously want to print on serial monitor the state of our program (what step it's in)*
void loop() {
  CrcLib::Update();
  //So weAfficher willen printcontinu atsur everyla programconsole scanl'état (du aprogramme scan beingquelle anétape exectuionnous ofsommes "loop(rendus)"
  //Remember: LOWLa means "0", and HIGH means "anything but "0"valeur affichée sera un entier correspondant à l'étape
  Serial.print("Step currently executedÉtape courante: "); Serial.print(currentStepetape);
  Serial.print(" durée de scanla timeboucle: "); Serial.println( CrcLib::GetDeltaTimeMicros() ); //Print theAffiche valuela returned by GetDeltaTime, which is the scan time durée de la dernière boucle

  switch(currentStepetape)
  {
//------------------
    case 0DODO:
    
      //The Le code you'dà wantexécuter tolors executedu duringmode Step0 wouldrepos
go here     
        if( CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE) == HIGH && CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_EVENPAIRE) == LOW)  
      {
        currentStepetape = 1ETAPE1;
      }
      break;
//------------------
    case 1ETAPE1:
    
      //The Le code you'dà wantexécuter todurant executela duringpremière Step1étape wouldirait go hereici
  
      if( CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_EVENPAIRE) == HIGH && CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE) == LOW )
      {
        currentStepetape = 2ETAPE2;
      }  
      break;
//------------------
    case 2ETAPE2:
    
      //The Le code you'dà wantexécuter todurant executela during Step22e wouldétape goirait hereici
  
      if( CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE) == HIGH && CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_EVENPAIRE) == LOW )
      {
        currentStepetape = 3ETAPE3;
      }
      break;
//------------------
    case 3ETAPE3:
    
      //The Le code you'dà wantexécuter todurant executela during3e Step3étape wouldirait go hereici
  
      if( CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_EVENPAIRE) == HIGH && CrcLib::GetDigitalInput(NEXTPROCHAINE_STEPETAPE_ODDIMPAIRE) == LOW )
      {
        currentStepetape = 0DODO;
      }  
      break;
//------------------
  }
}

...