0
0
Raspberry Piprogramming~30 mins

LED class and methods in Raspberry Pi - Mini Project: Build & Apply

Choose your learning style9 modes available
LED class and methods
📖 Scenario: You have a Raspberry Pi connected to an LED light. You want to control the LED by turning it on and off using a simple program.
🎯 Goal: Create a class called LED that can turn the LED on and off using methods. Then, use this class to turn the LED on and off.
📋 What You'll Learn
Create a class named LED
Add an __init__ method that takes a pin number and stores it
Add a method turn_on that prints "LED on pin X is ON" where X is the pin number
Add a method turn_off that prints "LED on pin X is OFF" where X is the pin number
Create an instance of LED with pin number 17
Call turn_on and turn_off methods on the instance
💡 Why This Matters
🌍 Real World
Controlling hardware like LEDs on a Raspberry Pi is common in home automation and robotics projects.
💼 Career
Understanding how to create classes and methods to control hardware devices is useful for embedded systems and IoT developer roles.
Progress0 / 4 steps
1
Create the LED class with an __init__ method
Create a class called LED with an __init__ method that takes a parameter pin and stores it in self.pin.
Raspberry Pi
Need a hint?

Remember, the __init__ method sets up the object with the pin number.

2
Add methods to turn the LED on and off
Add a method turn_on that prints "LED on pin {self.pin} is ON" and a method turn_off that prints "LED on pin {self.pin} is OFF" inside the LED class.
Raspberry Pi
Need a hint?

Use print(f"LED on pin {self.pin} is ON") inside turn_on and similar for turn_off.

3
Create an LED instance with pin 17
Create an instance of the LED class named led with the pin number 17.
Raspberry Pi
Need a hint?

Use led = LED(17) to create the LED object.

4
Turn the LED on and off using the methods
Call the turn_on method on led to turn the LED on, then call the turn_off method on led to turn the LED off. Print the output.
Raspberry Pi
Need a hint?

Use led.turn_on() and led.turn_off() to show the LED status.