Quels sont les aventage d'une librarie

Hello

Je travaille sur une project qui va collecter des position GPS et les envoyer sur un server via HTTP/HTTPS. Comme débutant, j'ai un très bon résultat et je suis content. Je recois bien les positions GPS qui sont stocké dans une variable String.

J'ai aussi un autre code qui lui envoie les données au serveur toutes les 10 sec.
Il les envoi avec le protocole HTTP et AT+ commande

J0'ai testé ce code séparément dans un autre fichier, et il marche.

Maintenant, j'ai fusionné les code en ajoutant une fonction void sendDATA(){} dans lequel se trouve mon code qui envoit donc les commandes au serveur.

Le problème, c'est qu'au moment ou le code sendDATA() est exécuté, le terminal crash et reboot, comme si on appuzait sur la touche reboot. Si je commande le code sendDATA(), ca fonctionne. Si je l'utilise séparément, il fonctionne.
C'est un peu comme, si la mémoire était plein, ou si le terminal avait "trop à lire/faire...."

Seriez-vous la raison?

Maintenant, je me demande des bénéfice d'une librairie. par exemple, je pourrais créer un fichie SendData/SendData.h avec la fonction sendDATA() et le mettre dans le dossier library.

Es-ce que ca me serait bénéfique?
Quel est le bénéfique d'une librairie?

Que me recommanderiez-vous pour créer ma première librairie avec succès?
Quels sont les points que je dois pas manquer?

Merci pour vos lumières?

Voci le code de sendDATA()

NewSoftSerial.h

/* FUNCTIONS RELATED TO GPRS WHILE SENDING DATA TO THE SERVER*/

// HOW TO HAVE IT AS A LIBRARAY AND SEND DATA (GPS FIXES) TO A SERVER IN HTTP OT HTTPS

// getMessage is defined outside, but I can have that function here
// cell. is defined outside
// GPRS_ACTIVE, DEBUG and SENDDATA are defined outside but I can remove its
// requests (is a String) is defined outside but I should add it as para,meter in my function sendDATA(requests)

// for eating a single message we expect from the module
// prints out the next message from the module. if it's not the expected value, die
void waitFor(String s) {
  String message=getMessage();
  if (message != s) {
    Serial.print(F("Wait, that's not what we were expecting. We wanted "));
    Serial.println("\""+s+"\"");
    cellOutputForever();
  }
  delay(100); // wait for a tiny bit before sending the next command
}

// if something goes wrong, abort and just display cell module output so we can see error messages
// this will loop forever
void cellOutputForever() {
  Serial.println(F("Looping forever displaying cell module output..."));
  while(1) {
    if(cell.available()>0) {
      Serial.print((char)cell.read());
    }
  }
}

// keep reading characters until we get char c
void waitForGSM(char c) {
  while(1) {
    if(cell.available()>0) {
      if ((char)cell.read() == c) {
        delay(100);
        return;
      }
    }
  }
}

// receive string such as "SOCKSTATUS: 1,1,0102,10,10,0"
// 0 is connection id. 1 is whether connected or not. 2 is status (0104 is connecting, 0102 is connected, others)
// 3 is sent bytes. 4 is acknowledged bytes. 5 is "received data counter"
// THIS FUNCTION WILL check that sent bytes == ack bytes, and return that value
// return 0 if they don't match or if amount of data is 0
int checkSocketString(String s) {
  if (socketStringSlice(3,s) == 0)
    return 0;
  else if (socketStringSlice(3,s) == socketStringSlice(4,s))
    return socketStringSlice(3,s);
  else
    return 0;
}

// returns the index of the nth instance of char c in String s
int nthIndexOf(int n, char c, String s) {
  int index=0;
  for (int i=0; i<=n; i++) {
    index = s.indexOf(c,index+1);
  }
  return index;
}

// expects string such as "SOCKSTATUS: 1,1,0102,10,10,0"
// returns nth chunk of data, delimited by commas
int socketStringSlice(int n, String s) {
  String slice = s.substring(nthIndexOf(n-1,',',s)+1,nthIndexOf(n,',',s));
  char cArray[slice.length()+1];
  slice.toCharArray(cArray, sizeof(cArray));
  return atoi(cArray);
}

void sendDATA(){
          
          /********************************/
          /*  SEND THE DATA TO THE SERVER */
          /********************************/
      
          //cell.println("AT+SBAND=6");
        
	#ifdef GPRS_ACTIVE
    	#ifdef SENDDATA
         //cell.println("AT+SBAND=6");
       
         #ifdef DEBUG
           freeRAM();
            Serial.println(F("1. Attaching GPRS..."));
          #endif
        
          cell.println("AT+CGATT=1");
          waitFor("OK"); 
            
          #ifdef DEBUG
            Serial.println(F("2. Setting up PDP Context..."));
          #endif
          cell.println("AT+CGDCONT=1,\"IP\",\""+apn+"\"");
          waitFor("OK");
           
          #ifdef DEBUG
            Serial.println(F("3. Activating PDP Context..."));
          #endif
            
          cell.println("AT+CGACT=1,1");
          waitFor("OK");
            
          #ifdef DEBUG
            Serial.println(F("4. Configuring TCP connection to TCP Server..."));
          #endif
          cell.println("AT+SDATACONF=1,\"TCP\",\""+ip+"\",80");
          //cell.println("AT+SDATACONF=1,\"TCP\",\""+ip+"\","+port+"");
          waitFor("OK");
           
           #ifdef DEBUG
             Serial.println(F("5. Starting TCP Connection..."));
           #endif

           cell.println("AT+SDATASTART=1,1");
           waitFor("OK");
            
           delay(5000); // wait for the socket to connect
      
           // now we'll loop forever, checking the socket status and only breaking when we connect
           while (1) {
             #ifdef DEBUG
               Serial.println(F("6. Checking socket status:"));
             #endif
             cell.println("AT+SDATASTATUS=1"); // we'll get back SOCKSTATUS and then OK
             String sockstat = getMessage();
             waitFor("OK");
             if (sockstat=="+SOCKSTATUS:  1,0,0104,0,0,0") {
               Serial.println(F("Not connected yet. Waiting 1 second and trying again."));
               delay(1000);
             }
             else if (sockstat=="+SOCKSTATUS:  1,1,0102,0,0,0") {
               Serial.println(F("Socket connected"));
               break;
             }
             else {
               Serial.println(F("We didn't expect that."));
               cellOutputForever();
             }
           }
            
            // we're now connected and can send HTTP packets!
            //int packetLength = 26+host.length()+request.length()+useragent.length(); // 26 is size of the non-variable parts of the packet, see SIZE comments below
           int packetLength = 26+host.length()+requests.length()+useragent.length();
            
           #ifdef DEBUG
             Serial.println(F("7. Sending HTTP packet..."));
           #endif
           cell.print("AT+SDATATSEND=1,"+String(packetLength)+"\r");
           waitForGSM('>'); // wait for GSM module to tell us it's ready to recieve the packet
           cell.print(requests+"\r\n"); // SIZE: 2
           cell.print("Host: "+host+"\r\n"); // SIZE: 8
           cell.print("User-Agent: "+useragent+"\r\n\r\n"); // SIZE: 16
           cell.write(26); // ctrl+z character: send the packet
           waitFor("OK");
            
            
           // now we're going to keep checking the socket status forever
           // break when the server tells us it acknowledged data
           while (1) {
              cell.println("AT+SDATASTATUS=1"); // we'll get back SOCKSTATUS and then OK
              String s = getMessage(); // we want s to contain the SOCKSTATUS message
              if (s == "+STCPD:1") // this means server sent data. cool, but we want to see SOCKSTATUS, so let's get next message
                s = getMessage();
              if (s == "+STCPC:1") // this means socket closed. cool, but we want to see SOCKSTATUS, so let's get next message
                s = getMessage();
              waitFor("OK");
              
              if (!s.startsWith("+SOCKSTATUS")) {
                
                  Serial.println(F("Wait, this isn't the SOCKSTATUS message!"));
                
                cellOutputForever(); // something went wrong
              }
              if (checkSocketString(s) == packetLength) // checks that packetLength bytes have been acknowledged by server
                break; // we're good!
              else {
                Serial.println(F("Sent data not yet acknowledged by server, waiting 1 second and checking again."));
                delay(1000);
              }
            }
            
            #ifdef DEBUG
              Serial.println(F(" "));
              Serial.println(F("YES! DATA ARE SENT AND ACKNOWLEDGE BY SRERVER!"));
         
            #endif
         
         #endif // END IFDEF DSENDDATA
       #endif // END IEF GPRS_ACTIVE    
       
     /***************************************/
     /* **** END SENDING DATA TO THE SERVER */
     /***************************************/

}

Une librairie permet principalement de simplifier l'écriture en évitant d'avoir des fonctions et des fonctions qui remplissent ton code, et deuxième gros avantage, on peut la partager !

Donc ca permetrait de libérer e la mémoire et éviter un crash/reboot du script?

Nan une librairie ne permet pas de gagner en mémoire, mais en visibilité. Si on prend simplement la librairie Serial il y a des centaines (voires des milliers) de lignes de code derrière. Mais ces lignes seront quand même forcement compilées dans ton code, mais toi tu n'auras écrit que Serial.print().

Je vois que sur certaines lignes tu as utiliser la fonction F(), fait le pour toutes les chaînes possible. Mais on a pas le reste de ton code donc peut-être qu'il traîne un autre consommateur de RAM ...

Après tu touches peut-être aux limites techniques de ton Arduino, et le passage au modèle au-dessus serait peut-être la solution (il y a des copies chinoises sur ebay de mega pour moins de 15€)

Une librairie c'est un moyen de réutiliser dans un nouveau programme un code qui a été développé pour une autre application.
Typiquement on fait des librairies pour des fonctions que l'on utilise souvent. Cela évite de les reécrire à chaque fois avec les risques d'erreurs de saisie et la mise au point associée.
Une librairie c'est aussi un moyen de diffuser une portion de programme dont d'autres personnes pourraient avoir besoin. Par exemple si je met en oeuvre un capteur particulier je fais une librairie avec le code qui interface ce capteur comme ça:

  1. je peux le réutiliser quand je veux
  2. je fais gagner du temps à ceux qui voudraient utiliser ce même capteur (en leur évitant la saisie et la mise au point de cette portion de code) et comme ça ils peuvent se polariser sur leur application et non sur la mise en oeuvre du capteur.

Petite note perso : j'essaye d'utiliser le moins de library possible afin de me rapprocher au maximum du système étudier, de familiariser un peut avec du bas niveau quand cela est possible, sinon sa devient presque anti pédagogique car le fait d'envoyer 4 fonction et avoir le résultat tout prêt tout cuit au final on apprend rien quand on est débutant. Mais par moment l'appel d'une library est presque vital comme ex : pour le OneWire ou le MPU 6050 et d'autres.