Question sur un programme d'exemple

Bonjour à tous,

Dans un des sketch d'exemple, je me pose des questions sur
inString += (char)inChar;
je ne vois pas tout à fait sa fonction.

et quelle est l'utilité de mettre ceci: while (!Serial)

merci bcp

/*
  String to Integer conversion

  Reads a serial input string until it sees a newline, then converts the string
  to a number if the characters are digits.

  The circuit:
  - No external components needed.

  created 29 Nov 2010
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/StringToInt
*/

String inString = "";  // string to hold input

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ;  // wait for serial port to connect. Needed for native USB port only
  }

  // send an intro:
  Serial.println("\n\nString toInt():");
  Serial.println();
}

void loop() {
  // Read serial input:
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
      // convert the incoming byte to a char and add it to the string:
      inString += (char)inChar;
    }
    // if you get a newline, print the string, then the string's value:
    if (inChar == '\n') {
      Serial.print("Value:");
      Serial.println(inString.toInt());
      Serial.print("String: ");
      Serial.println(inString);
      // clear the string for new input:
      inString = "";
    }
  }
}

Le premier concatène le caractère lu à une chaine, dans ton code cela lit les caractères un par un par lorsqu'il arrive dans la liaison série, pour les concaténer dans une chaine, lorsque le caractère lu est un retour chariot, cela affiche la chaine ainsi constitué et la remet à 0.

pour la deuxième instruction, les commentaires t'indique que tant que Serial n'est pas vrai, répéter ne rien faire.

Eskimon a fait d'excellent article qui devrait te permet de comrendre tout cela facilement.

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