Skip to main content
Arduino

Return to Revisions

2 of 3
add code example

The approach noted in the question – having an identifying character at the front of each number – is a workable approach. Other approaches include:
• always sending numbers in pairs, eg 2000,300 would denote A2000 B300.
• encoding the A or B as part of the number; eg, the range 0-4999 could denote A delays of 0 to 4999, while the range 5000-9999 could denote B delays of 0 to 4999.
• sending A delays via decimal digits, and B delays via letter-substitutes for digits; eg DAA could encode a B delay of 300.

One of the easiest-to-parse approaches is to have an identifying character at the end of each number, rather than at the front. This allows your code to pick up digits until a letter appears, and then dispatch based on the letter. Here's some example code:

// Sketch that accepts numbers and action code via serial input.
// Silently ignores any numbers not followed by a valid action letter.
// Does not test for number overflow. - jiw 3 Nov 2016
void setup() {
 Serial.begin(115200); // init serial port
}
unsigned int val=0;
void loop() {
 char inc;
 while (Serial.available()) { // Get characters
 inc = Serial.read();
 if (inc >= '0' && inc <= '9') {
 val = 10*val + (inc-'0');
 } else {
 switch (toupper(inc)) {
 case 'A':
 Serial.print("Case A got ");
 Serial.println(val);
 break;
 case 'B':
 Serial.print("Case B got ");
 Serial.println(val);
 break;
 default :
 ; // handle blanks, returns, etc
 }
 val = 0; // Set val to zero after any non-digit
 }
 }
}

AltStyle によって変換されたページ (->オリジナル) /