Consider this Arduino code snippet that sends data over Serial. What will be printed on the Serial Monitor?
void setup() {
Serial.begin(9600);
while (!Serial) { ; }
Serial.println("Hello");
Serial.print(123);
Serial.println(" World");
}
void loop() {
// empty
}Remember that println adds a new line after printing, while print does not.
The println function prints the text and then moves to a new line. The print function prints without moving to a new line. So the output is:Hello with a new line, then 123 without a new line, then World with a new line.
Why is it important for devices like Arduino boards and sensors to use communication protocols?
Think about how two people can talk clearly only if they speak the same language.
Communication protocols are like languages for devices. They set rules so devices can send and receive data correctly and understand each other.
This Arduino code tries to read data from an I2C sensor but does not work as expected. What is the main error?
void setup() {
Wire.begin();
Serial.begin(9600);
}
void loop() {
Wire.requestFrom(0x40, 2);
if (Wire.available()) {
int data = Wire.read();
Serial.println(data);
}
delay(1000);
}Check how many bytes are requested and how many are read.
The code requests 2 bytes but reads only one byte from the buffer. The second byte remains unread, which can cause problems in communication.
Look at this Arduino SPI code snippet. What error will it cause when compiled?
void setup() {
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV16);
}
void loop() {
SPI.transfer(0xFF);
delay(1000);
}Check punctuation at the end of each statement.
The line SPI.setClockDivider(SPI_CLOCK_DIV16) is missing a semicolon at the end, causing a syntax error.
This Arduino code sends a string over UART. How many bytes are actually sent?
void setup() {
Serial.begin(115200);
Serial.write("Hi\n");
}
void loop() {
// empty
}Count each character including special characters like newline.
The string "Hi\n" has three characters: 'H', 'i', and newline '\n'. Each character is one byte, so 3 bytes are sent. However, Serial.write sends the string as bytes, so it sends exactly 3 bytes.
