Reading only on digit out of the Serial buffer

Hey there,
i'd like to know if its possible to read only one digit(int) out of the Serial buffer of an arduino?

I know that the function Serial.parseInt(); reads all Integers out of the Serial buffer, but is it also possible to read just one digit out of buffer.
I could also just throw it all in to an int with paresInt and sort the digits out one by one with for example (1234 * 10U ) % 10 (might be wrong), or I delay the Input from the Serial Monitor to the Arduino, I dunno how, but I hope there is another way to do it.

If not I'll go with the digit sorting.

Thank You all!!

Take each element as a char then put in an array.
After you can convert it to integer.

Please see Serial Input Basics - updated for excellent advice on dealing with serial data.

Please clarify what you mean by

What do you mean 'one digit'? Assuming the data is being sent to your Arduino as ASCII there will be any number of digits depending on how big the number is. Follow the advice in the tutorial.

Could be something like this.

#define MAX_SIZE 100

char myArray[MAX_SIZE];
int index = 0;

void setup() 
{
  Serial.begin(9600);
}

void loop() 
{
  if (Serial.available() > 0) 
  {
    char c = Serial.read();
    
    if(index < MAX_SIZE)
    {
      myArray[index] = c;
      index++;
    }
  }

  int myValue = ((myArray[0] - 48) * 100 + (myArray[1] - 48) * 10 + (myArray[2] - 48));

  Serial.println(myValue);
}
1 Like

By digit I mean an Integere type like 0123456789.
If we write "Hello I'm 25 Years old and my hight is 190cm" over the Serial Monitor, I just wanna take out number 2 out of the buffer and store it.

AH that is really helpfull, I had to think twice what is happening at myValue, but understand the way it works.
Thank you for the code example!

OK, thank you. I think the best advice is in the tutorial I linked to.

1 Like

In this case you can use this condition.


  if (Serial.available() > 0)
  {
    char c = Serial.read();

    if (index < MAX_SIZE)
    {
      if ((c >= 48 ) && (c <= 57))
      {
        myArray[index] = c;
        index++;
      }
    }
   }
1 Like

On my way read me through, thank you

1 Like

And thank you too, I didn't thought about this way.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.