Consider the following Arduino code that reads bytes from the serial port and prints them as characters:
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int data = Serial.read();
Serial.print((char)data);
}
}If the user sends the characters HELLO over the serial monitor, what will be printed back?
void setup() {
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0) {
int data = Serial.read();
Serial.print((char)data);
}
}Remember that Serial.read() returns the ASCII value of the received byte. Casting it to char prints the character.
The code reads each byte from the serial buffer and prints it as a character. Sending HELLO sends ASCII codes for those letters, which are printed back as the same letters.
In Arduino, what value does Serial.read() return if you call it when no data is available in the serial buffer?
Check the Arduino documentation for Serial.read() return values.
If no data is available, Serial.read() returns -1 to indicate no byte was read.
Look at this Arduino code snippet:
void loop() {
int data = Serial.read();
if (data != -1) {
Serial.print(data);
}
}The user sends the string 123 over serial, but the output is 495051. Why?
Think about what Serial.print() does with integers vs characters.
The code prints the integer values of the ASCII codes (49 for '1', 50 for '2', 51 for '3'), so the output is the numbers concatenated as strings.
Which of the following Arduino code snippets correctly reads characters from Serial until a newline and stores them in a char array buffer?
Remember to check the character after reading it and to increment the index properly.
Option A reads each byte, stores it, checks if it is newline, then breaks. It increments index after storing. Other options either read twice or increment incorrectly.
Given this Arduino code snippet:
char buffer[10];
int i = 0;
void loop() {
while (Serial.available() > 0 && i < 10) {
int c = Serial.read();
if (c == '\n') break;
buffer[i++] = (char)c;
}
buffer[i] = '\0';
}If the user sends the string HELLOWORLD\n (10 characters plus newline), how many characters will be stored in buffer after the loop?
Count characters until newline or buffer limit, whichever comes first.
The buffer size is 10, but the loop stops if i reaches 10. Since newline is at position 11, the loop reads 10 characters before newline and stores them. Then it adds null terminator.
