Week 3 ยท Functions, Outputs & Buttons

Session 12: Functions that share values

Teach & buildFlex120 minLesson 08: Functions: Naming & Reusing Tasks

Learning outcomes

  • Explain why parameters are copies and local variables are temporary
  • Use pass-by-reference when a function must change the caller's variable
  • Split a long loop() into named steps without changing behaviour

Kit and components

  • Four-LED circuit, Uno and lab PC

Pre-reading about 15 min

Students read these on their phones before class. They are listed on the student Before class page.

  1. Lesson 08: Parameters are copies; locals are temporary
  2. Lesson 08: Make loop() read like a plan
  3. Theory Reference: Variable scope

Session plan

  1. 0:0010 min
    Recap

    Quiz: functions

  2. 0:1020 min
    Demo

    Copies, locals and references

    Show a counter that resets because it is local, then a swap that fails with copies and works with references.

  3. 0:3040 min
  4. 1:1040 min
    Build

    Refactor the pattern controller

    Students restructure their S10 mini-project into readCommand(), updatePattern() and showPattern(), testing after each step so behaviour never changes.

  5. 1:5010 min
    Wrap-up

    Does loop() read like a plan?

Checkpoint: ready to move on?

Each student's refactored sketch behaves exactly as before, and loop() contains only function calls.

Extension for fast finishers

Write bool anyPressed(const byte pins[], byte count) from the lesson challenge.

Catch-up path

Skip the refactor and complete the two exercises.

Homework and practice

Code Along 5.6.

Facilitator notes

  • Flex session: in a shorter course set the two exercises as homework and skip the refactor.