Advertisement
Guest User

Serial Integer Reader

a guest
Sep 1st, 2010
641
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. /*
  2. * Serial Integer Reader, by Pedro Tome'
  3. * Version 0.01
  4. *
  5. * Reads integer numbers from the Serial buffer and translates them
  6. * into the value of the variable "number".
  7. *
  8. * Use this code if you want to read integer values from another Arduino,
  9. * which should have the Serial Integer Writer code, by Pedro Tome'.
  10. *
  11. * Example:
  12. * The number 3782 is outputted to the Serial buffer.
  13. * The variable "number" now holds the value 3782.
  14. *
  15. * The maximum value is 65535 due to "number" being an unsigned int.
  16. */
  17.  
  18.  
  19. char charArray[6];
  20. int intArray[6];
  21. unsigned int number;
  22.  
  23.  
  24. void setup() {
  25. Serial.begin(9600);
  26. }
  27.  
  28.  
  29. void loop () {
  30. int charIndex = 1;
  31. int intIndex = 1;
  32. int max_intIndex;
  33. number = 0;
  34.  
  35. /* If there is something in the serial buffer */
  36. if (Serial.available()){
  37.  
  38. /* Read the data from Serial and store it in a charArray */
  39. while (Serial.available()) { // while there's something in the serial buffer...
  40. int serialIn = Serial.read();
  41. delay(5);
  42. charArray[charIndex] = serialIn; // store everything that was read in charArray byte-by-byte
  43. charArray[charIndex+1] = '\0'; // add a NULL value
  44. charIndex++;
  45. }
  46. charIndex = 1; // Reset charIndex
  47.  
  48.  
  49. /* Separate the charArray and convert it into an intArray */
  50. while (charArray[charIndex] != '\0') { // while the value is not NULL, ie, while there's a relevant value
  51. max_intIndex = intIndex;
  52. intArray[intIndex] = charArray[charIndex]-'0';
  53. charIndex++;
  54. intIndex++;
  55. }
  56. intIndex = 1; // Reset intIndex
  57.  
  58.  
  59. /* Build one single number from the intArray */
  60. for (intIndex = 1; intIndex <= max_intIndex; intIndex++) {
  61. number = number*10 + intArray[intIndex];
  62. }
  63.  
  64. Serial.print("number: "); Serial.println(number);
  65. Serial.flush();
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement