Skip to main content
Arduino

Return to Answer

replaced http://arduino.stackexchange.com/ with https://arduino.stackexchange.com/
Source Link
  1. a bit faster than working with String
  2. no dynamic memory allocation/deallocation (String does a lot of these) which might lead your program to heap fragmentation heap fragmentation and eventually crash.
  1. a bit faster than working with String
  2. no dynamic memory allocation/deallocation (String does a lot of these) which might lead your program to heap fragmentation and eventually crash.
  1. a bit faster than working with String
  2. no dynamic memory allocation/deallocation (String does a lot of these) which might lead your program to heap fragmentation and eventually crash.
Source Link
jfpoilpret
  • 9.2k
  • 7
  • 38
  • 54

Your code could be improved by removing the use of IP string altogether, and directly calculating its numeric value while characters come in through Serial1:

...
boolean borrar = false;
int IP = 0;
...
void loop() {
 while (Serial1.available()) { 
 char caracter = Serial1.read(); //Comprobamos el caracter 
 switch(caracter) {
 // NOTE it is better to replace default by the list of all digits... 
 case '0':
 case '1':
 case '2':
 case '3':
 case '4':
 case '5':
 case '6':
 case '7':
 case '8':
 case '9':
 if (borrar) { 
 IP = 0; 
 lcd.clear();
 }
 
 lcd.print(caracter);
 delay(125);
 borrar = false;
 IP *= 10;
 IP += (int) (caracter - '0');
 break; 
 
 case '\r': 
 case 0x0F:
 case 0x0A: 
 
 String res = "";
 borrar = true;
 int num= IP;
 if (num < 127) 
 res="Clase A";
 if (num == 127) 
 res="Direccion reservada";
 if (num > 127 && num < 192)
 res="Clase B ";
 if (num >= 192 && num < 224)
 res="Clase C ";
 if (num >= 224 && num < 240)
 res="Clase D ";
 if (num >= 240 && num < 255)
 res="Clase E ";
 break; 
 
 } //fin switch
}//serial disponible
}//fin programa

This way would bring you 2 advantages:

  1. a bit faster than working with String
  2. no dynamic memory allocation/deallocation (String does a lot of these) which might lead your program to heap fragmentation and eventually crash.

Note that I have not further refactored your code as I guessed it was just a snippet, not the complete code for your program. Otherwise, I would have performed further refinement like:

  • remove num variable since it is the same as IP now
  • replace res from String to const char* (to further reduce heap fragmentation due to String usage)
lang-cpp

AltStyle によって変換されたページ (->オリジナル) /