Digital Electronics Lab 7

“Push” ON/OFF Button:

The “Push” Button works in 4 steps: First we store the “button states” within 3 boolean values, which controls the button and the LEDs. The checkButton() is used to check to make sure the last button state equals the current button state. If this is true, it will then take the values stored in after the button is turned “on” and then proceed to call the flipButtonState() so that it can keep track of the state that is active. This is the value that is used to actually turn the LED on or off.

The Code:

#include <Adafruit_NeoPixel.h>
Adafruit_NeoPixel neopixel = Adafruit_NeoPixel(2, 32, NEO_RGB);

int red = 0;
int green = 0;
int blue = 0;
int mappedRed = 0;
int mappedGreen = 0;
int mappedBlue = 0;

int buttonPin = 36;
//this is for the on off push button
bool lastButton1State = LOW;
bool button1State = LOW;
bool switchedOn = false;

void setup() { //setup neo pixel
  neopixel.begin();
  neopixel.clear();
  neopixel.show();
  pinMode(buttonPin, INPUT);
}

void loop() {
  checkButton();
  updatefunction();
  
  red = analogRead(A16); //set as analog read
  green = analogRead(A15);
  blue = analogRead(A14);

  mappedRed = map(red, 0, 1023, 0, 255);
  mappedGreen = map(green, 0, 1023, 0, 255);
  mappedBlue = map(blue, 0, 1023, 0, 255);

  neopixel.setPixelColor (0, mappedRed, mappedGreen, mappedBlue); //define colors/set colors
  neopixel.setPixelColor (1, mappedRed, mappedGreen, mappedBlue);
}

void checkButton() {
  lastButton1State = button1State;
  button1State = digitalRead(buttonPin);
  if(lastButton1State == LOW && button1State == HIGH) {
    flipButtonState();
    delay(5);
  } else if(lastButton1State == HIGH && button1State == LOW) {
    delay(5);
  }
}
//this function defines "off and on"
void flipButtonState() {
    if(switchedOn == true) {
      switchedOn = false;
    } else if(switchedOn == false) {
      switchedOn = true;
    }  
}

void updatefunction() {
  if(switchedOn == true) {
    neopixel.show();
  } else {
    neopixel.setPixelColor (0, 0, 0, 0);
    neopixel.setPixelColor (1, 0, 0, 0);
    neopixel.show();
  }
}

Video:

Leave a comment

Design a site like this with WordPress.com
Get started