0
0
Arduinoprogramming~30 mins

Code organization with functions in Arduino - Mini Project: Build & Apply

Choose your learning style9 modes available
Code organization with functions
📖 Scenario: You are building a simple Arduino program to control an LED light. Instead of writing all the code in the loop() function, you want to organize your code by creating functions. This will make your program easier to read and change later.
🎯 Goal: Create a function to turn the LED on and another function to turn the LED off. Then use these functions inside the loop() to blink the LED.
📋 What You'll Learn
Create a function called turnLedOn that turns the LED on.
Create a function called turnLedOff that turns the LED off.
Use these functions inside the loop() to blink the LED with a delay.
Use the built-in digitalWrite and delay functions.
💡 Why This Matters
🌍 Real World
Organizing code with functions is important in real Arduino projects to keep code clean and easy to update.
💼 Career
Many jobs in embedded systems and hardware programming require writing clear, organized code using functions.
Progress0 / 4 steps
1
Set up the LED pin
Write code to create a constant integer called ledPin and set it to 13. Then write the setup() function to set ledPin as an output using pinMode.
Arduino
Need a hint?

Use const int ledPin = 13; to define the LED pin. Inside setup(), use pinMode(ledPin, OUTPUT); to set it as output.

2
Create functions to turn LED on and off
Write two functions: void turnLedOn() that sets ledPin HIGH using digitalWrite, and void turnLedOff() that sets ledPin LOW using digitalWrite.
Arduino
Need a hint?

Define turnLedOn() to call digitalWrite(ledPin, HIGH); and turnLedOff() to call digitalWrite(ledPin, LOW);.

3
Use functions to blink the LED
Inside the loop() function, call turnLedOn(), then delay(1000), then call turnLedOff(), then delay(1000) to blink the LED on and off every second.
Arduino
Need a hint?

Call turnLedOn(), then delay(1000);, then turnLedOff(), then delay(1000); inside loop().

4
Display the blinking LED behavior
Upload the program and observe the LED on pin 13 blinking on and off every second. Write a Serial.println statement inside loop() to print "LED is blinking" each cycle after turning the LED off.
Arduino
Need a hint?

Use Serial.println("LED is blinking"); after turning the LED off and delaying.