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;
}
}
}