Consider this Arduino code that reads a button connected with a pull-up resistor. What will be printed to the Serial Monitor when the button is pressed?
const int buttonPin = 2; void setup() { pinMode(buttonPin, INPUT_PULLUP); Serial.begin(9600); } void loop() { int buttonState = digitalRead(buttonPin); if (buttonState == LOW) { Serial.println("Button pressed"); } else { Serial.println("Button not pressed"); } delay(500); }
Remember that with a pull-up resistor, the button pin reads LOW when pressed.
Using INPUT_PULLUP sets the pin HIGH by default. When the button is pressed, it connects the pin to ground, making it LOW. So the code prints "Button pressed".
Why is it recommended to use INPUT_PULLUP mode when reading a button in Arduino?
Think about what happens if the input pin is not connected to anything.
Using INPUT_PULLUP activates the internal pull-up resistor, preventing the input pin from floating and reading random values.
This Arduino code always prints "Button pressed" even when the button is not pressed. What is the cause?
const int buttonPin = 2; void setup() { pinMode(buttonPin, INPUT); Serial.begin(9600); } void loop() { int buttonState = digitalRead(buttonPin); if (buttonState == LOW) { Serial.println("Button pressed"); } else { Serial.println("Button not pressed"); } delay(500); }
Think about what happens to an input pin without a pull-up or pull-down resistor.
Without INPUT_PULLUP, the input pin floats and may randomly read LOW, causing the code to think the button is pressed.
Which option contains the correct syntax to set the button pin as input with pull-up resistor?
const int buttonPin = 2; void setup() { // Set button pin mode here } void loop() {}
Check the syntax of the pinMode function and the constant name.
The correct syntax is pinMode(pin, INPUT_PULLUP); with a comma and the constant INPUT_PULLUP.
Given this Arduino code, how many times will "Button pressed" be printed to the Serial Monitor in 5 seconds if the button is held down continuously?
const int buttonPin = 2; void setup() { pinMode(buttonPin, INPUT_PULLUP); Serial.begin(9600); } void loop() { int buttonState = digitalRead(buttonPin); if (buttonState == LOW) { Serial.println("Button pressed"); } delay(500); }
Calculate how many 500 ms delays fit into 5 seconds.
The loop prints "Button pressed" once every 500 ms. In 5 seconds, 5 / 0.5 = 10 times.
