Reading and Storing Integer from Serial Monitor Description 

I wanted to understand how integers can be written and stored inside variables without the use of Serial.parseInt(). I couldn't find any code examples about this. Perhaps this is the right way to do it, although it doesn't detect and block letters and special characters. Please leave some feedback on ways to improve it. Thanks in advance! :)

void setup()
{
  Serial.begin(9600); // Opens serial port, sets data rate to 9600 bps
  Serial.println(F("Serial port opened!"));
}

void loop()
{
  byte received;
  static byte counter = 0;
  static uint32_t number = 0; // Store value from 0 to 4294967295

  while (Serial.available()) // Read data in serial receive buffer
  {
    received = Serial.read(); // Store received byte
    if (received != 10) // Terminate if newline char detected
    {
      if (counter != 0) // Put number in its correct position (base-10 system)
      {
        number *= 10;
        number += (received - '0');
      }
      else
      {
        number = (received - '0');
      }
      counter++;
    }
    else
    {
      Serial.println(number); // Print value inside number and reset
      counter = 0;
    }
  }
}
Character literals

While this is technically correct:

if (received != 10) // Terminate if newline char detected


you're better off writing

if (received != '\n')


Much of embedded electronics assumes ASCII encoding, and this is no exception, but you're still better off using the symbol instead of the code.

IO management

You loop while serial I/O is available:

while (Serial.available())


But what if there is a pause in the availability of bytes in the middle of your integer? Your code will not do the right thing. Instead:

uint32_t number = 0;
while (true) {
  int received = Serial.read();
  if (received == -1) continue;
  if (received == '\n') break;
  // ...
}
Serial.println(number);



Do not use static for number
Don't need a counter
Keep looping if no data are available
Ensure that one execution of loop maps to one full output integer


Condition in loop

If you are using the ATmega328P, it has a dedicated MUL instruction that only takes two cycles. It's more complex and expensive to have your if (counter != 0) than it is to simply unconditionally multiply-and-add.