Consider this Arduino code snippet that reads a serial input string and extracts a number:
String input = "TEMP:25;";
int value = 0;
int index = input.indexOf(':');
if (index != -1) {
String numberPart = input.substring(index + 1, input.indexOf(';'));
value = numberPart.toInt();
}
Serial.println(value);What will be printed on the Serial Monitor?
String input = "TEMP:25;"; int value = 0; int index = input.indexOf(':'); if (index != -1) { String numberPart = input.substring(index + 1, input.indexOf(';')); value = numberPart.toInt(); } Serial.println(value);
Look at how substring and toInt() work on the extracted part.
The code finds the colon, extracts the substring between ':' and ';' which is "25", then converts it to integer 25 and prints it.
In Arduino, which function reads characters from the serial buffer until it encounters a newline character and returns the result as a String?
Think about reading until a specific character.
Serial.readStringUntil('\n') reads characters until it finds a newline, returning the collected string.
Analyze this Arduino code snippet:
String data = Serial.readStringUntil(';');
int val = data.toInt();
Serial.println(val);If the serial input is "123abc;", what happens?
String data = Serial.readStringUntil(';'); int val = data.toInt(); Serial.println(val);
Check how toInt() handles strings with trailing letters.
toInt() converts the initial numeric part and stops at the first non-digit, so it returns 123.
Which of these Arduino code snippets will cause a syntax error?
1) String s = Serial.readStringUntil(';');
2) int n = s.toInt();
3) String part = s.substring(2, 5);
4) int x = s.substring(1, 3).toInt()Look carefully for missing punctuation.
Option 4 misses a semicolon at the end, causing a syntax error.
Given this Arduino code:
String input = "CMD,100,ON,45";
int count = 0;
int start = 0;
int commaIndex = -1;
while ((commaIndex = input.indexOf(',', start)) != -1) {
String part = input.substring(start, commaIndex);
count++;
start = commaIndex + 1;
}
count++;
Serial.println(count);What number will be printed?
String input = "CMD,100,ON,45"; int count = 0; int start = 0; int commaIndex = -1; while ((commaIndex = input.indexOf(',', start)) != -1) { String part = input.substring(start, commaIndex); count++; start = commaIndex + 1; } count++; Serial.println(count);
Count how many commas split the string and add one.
The string has 3 commas, so 4 parts. The code counts each comma found and adds one at the end.
