Skip to content

Instantly share code, notes, and snippets.

@keshavsaharia
Created June 30, 2013 05:39
Show Gist options
  • Save keshavsaharia/5894000 to your computer and use it in GitHub Desktop.
Save keshavsaharia/5894000 to your computer and use it in GitHub Desktop.
nextInt() for Arduino serial communication
// Main method to call to get an integer.
// It will block until an integer followed by a non-digit delimiter is read from the serial input stream.
int getInt() {
return getInt(0);
}
// Recursive helper method.
// @param sum - an accumulator that "builds" the next number, character by character.
int getInt(int sum) {
// Read a single character from the serial input stream.
char c = Serial.read();
// If it is not a digit character, return whats in the accumulator.
if (c < 48 || c > 57)
return sum;
// Otherwise, shift the digits in the accumulator over by 1 decimal place and add the next digit to them. Once
// the value is computed, pass the new accumulator value to another call to getInt.
sum = sum * 10;
return getInt(sum + ((int) (c - 48)) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment