Advertisement
baldengineer

Read Integers over Serial

Jul 28th, 2012
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. /*****************************
  2. * Read multiple integers over serial
  3. * James C4S / byerly0503@gmail.com / www.cmiyc.com
  4. *
  5. * NEWLINE *MUST* be enabled to work.
  6. * Arduino's Serial Monitor must have NewLine enabled (lower right corner)
  7. *
  8. * Maximum Value of integerValue depends on its data type.
  9. * unsigned int max is 999
  10. * unsigned long max is 999999999
  11. * otherwise, the number received rolls over.
  12. *
  13. ******************************/
  14. void setup() {
  15.   Serial.begin(9600);
  16. }
  17.  
  18. unsigned int integerValue=0;  // Max value is 999
  19. char incomingByte;
  20.  
  21. void loop() {
  22.   if (Serial.available() > 0) {   // something came across serial
  23.     integerValue = 0;         // throw away previous integerValue
  24.     while(1) {            // force into a loop until '\n' is received
  25.       incomingByte = Serial.read();    
  26.       if (incomingByte == '\n') break;   // exit the while(1), we're done receiving
  27.       if (incomingByte == -1) continue;  // if no characters are in the buffer read() returns -1
  28.  
  29.       // convert ASCII to integer, add, and shift left 1 decimal place
  30.       integerValue = ((incomingByte - 48) + integerValue)*10;      
  31.     }
  32.     integerValue /= 10;      // shift back right once, corrects for when '\n' is received
  33.     Serial.println(integerValue);   // Do something with the value
  34.   }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement