Check yourself

Try to answer each question before you open its answer.

About the code

  1. What does digitalRead(2) give back?

    Show the answer

    HIGH or LOW. It reads pin 2 and says which of the two it is. 5

  2. Why does the button need a resistor to GND?

    Show the answer

    So pin 2 reads LOW while the button is up. A pin joined to nothing is “floating”: it reads HIGH or LOW at random. 4, 5

  3. When does the else part run?

    Show the answer

    When digitalRead(2) == HIGH is false: the button is up. else runs when the condition in the if is false. 9, 10

About the registers

These are about step 4. If you skipped it, you can skip them too.

  1. Which register bit holds what pin 2 reads?

    Show the answer

    PIND bit 2 (PIND2). Pin 2 is bit 2 of port D, and digitalRead checks that bit of PIND. 1, 2

  2. What does DDRD &= ~(1 << DDD2); do?

    Show the answer

    It makes pin 2 an input, as pinMode(2, INPUT) does. pinMode(2, INPUT) clears bit 2 of DDRD, and bit 2 of PORTD too. 2

That was the last lesson. Next, try the missions, or write your own sketch on the Write code page.

All sources for Lesson 4

  1. ArduinoCore-⁠avr, variants/standard/pins_arduino.h: pins 0 to 7 are port D; pin 2 is PD2; pin 13 is PB5
  2. ArduinoCore-⁠avr, cores/arduino/wiring_digital.c: pinMode and digitalRead
  3. Arduino example: Button.ino: public domain
  4. Arduino tutorial: How to Wire and Program a Button: pull-⁠down resistor; a floating pin
  5. Arduino reference: digitalRead
  6. Arduino reference: pinMode
  7. Arduino reference: digitalWrite
  8. Arduino reference: if
  9. Arduino reference: else
  10. Arduino reference: == (equal to)
  11. Arduino reference: setup()
  12. Arduino reference: loop()
  13. avr-⁠libc, include/avr/iom328p.h: PIND, DDRD and PORTD, and their bit names