Lesson 4: Functions & Modularity – Writing Clean, Reusable Code

Lesson 4: Functions and Modularity – Circuits and Coding 101


📌 Introduction

Welcome back to Lesson 4 of Circuits and Coding 101! Today, we’re making our programs more organized and efficient by learning about functions and modularity.


Functions help us break down code into smaller, reusable parts, making it easier to read and debug.


🎯 What You’ll Learn Today

  • Functions – What they are and how to use them
  • Parameters & Return Values – Passing values into functions
  • Hands-on exercises – Custom LED blink functions and sensor-based LED control


🛠️ What Are Functions?

Definition: Functions are blocks of code designed to perform a specific task.


Why use functions?

  • Makes your code easier to read and debug.
  • Helps avoid repetition by reusing code.


📌 Basic Function Syntax:

Note: The void keyword means the function doesn’t return a value.

📥 Parameters and Return Values

What are parameters?

Parameters allow you to pass data into a function.


How to return values: A function can also return a result, which can be used later in the program.


💻 Example with Parameters and Return Values:

Here, the function takes an integer x and returns its square.

💡 Hands-On Exercise 1: Custom LED Blink Function

Let’s create a function to control an LED’s blink pattern.


🔧 Steps for Breadboard Setup:

Connect an LED to pin 13 with a resistor.


💻 Code:

Test and Experiment:

  • Upload the code and observe the LED blinking with different delays.
  • Try modifying the delayTime values.

📡 Hands-On Exercise 2: Sensor-Based LED Control with Functions

Now, let’s use a function to read a sensor value and control an LED.


🔧 Steps for Breadboard Setup:

  1. Connect a photoresistor to pin A0 using a voltage divider.
  2. Connect an LED to pin 13 with a resistor.

Circuit Diagram