Classes

We created functions to do specific jobs, for example the function to turn off all the lights, and the function to make all the lights blue:
def lightsOff():
  for i in range(20):
    pixels[i] = (0,0,0)

def allBlue():
  for i in range(20):
      pixels[i] = (0,0,10)
      time.sleep(0.1)

Now we'll use a "class" to organize our functions in one place. In fact, we'll give the class a specific purpose and it might have to do a bunch of different things related to that purpose.

Let's create a class called "picoStrip" that makes it easier to set up our LED strip, and do all the little functions we made.

References:

  1. QuickRef: Classes
  2. QuickRef: Functions

LEDs Index

A picoStrip Class

Making a class called "picoStrip" to operate the LED strip:

import board
import neopixel
import time

# this is our class
class picoStrip:

    def __init__(gpPin = board.GP0, nPix = 20):
        self.pixels = neopixel.NeoPixel(gpPin, nPix)

    def lightsOff():
        for i in range(20):
            self.pixels[i] = (0,0,0)

    def allBlue():
        for i in range(20):
            pixels[i] = (0,0,10)
            time.sleep(0.1)

# Now we start our main program
myStrip = picoStrip(board.GP0, 20)

myStrip.allBlue()  # Make the lights blue
myStrip.lightsOff()  # Turn off the lights

Assignment 1

Adapt the picoStrip class, to ADD a method that makes all the lights red, then adapt the program so it:
  1. makes all the lights blue,
  2. Turn off the lights
  3. Wait for 1 second,
  4. Light up all the lights again (red)
  5. Turn off the lights
Code ▼

Passing Parameters to a Class and Having Methods Refer to Each Other

Now let's make a method that runs the allBlue and allRed methods a given number of times.

import board
import neopixel
import time

# this is our class
class picoStrip:

    def __init__(gpPin = board.GP0, nPix = 20):
        self.pixels = neopixel.NeoPixel(gpPin, nPix)

    def lightsOff():
        for i in range(20):
            self.pixels[i] = (0,0,0)

    def allBlue():
        for i in range(20):
            pixels[i] = (0,0,10)
            time.sleep(0.1)

    def allRed():
        for i in range(20):
            pixels[i] = (10,0,0)
            time.sleep(0.1)

    def blueRed(n = 2):
        for i in range(n):
            self.allBlue()
            time.sleep(1)
            self.allRed()
            time.sleep(1)


# Now we start our main program
myStrip = picoStrip(board.GP0, 20)

myStrip.blueRed()

Assignment 3: Method practice

Add two more methods to your picoStrip class