Help needed using a counter to set LED colour on boot

I have an RGB LED that cycles through colours using a pushbutton, the counter value for them is then saved with EEPROM.put, which seems to be working, but the issue I have is how to start it up again with the value saved in the EEPROM? I have very limited programming knowledge and can’t think of a way around it despite reading up for the past few hours… I tried using setColor() in the setup() to somehow read the value with EEPROM.get and display in on boot, but it is expecting 3 int values. Maybe saving the RGB values from each press in the EEPROM rather than the counter might be a better way around it? Any help would be much appreciated.

#include "OneButton.h"
#include <EEPROM.h>

OneButton buttonPin(7, true);
OneButton ejectButtonPin(10, true);

const int xboxPin =  8;
const int ejectPin = 9;
const int bluePin = 4;
const int greenPin = 5;
const int redPin = 6;
int counter = 0;

void setup() {
  pinMode(xboxPin, INPUT);
  pinMode(ejectPin, INPUT);
  pinMode(redPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(greenPin, OUTPUT);

  buttonPin.attachClick(click1);
  buttonPin.attachLongPressStart(longclick1);

  ejectButtonPin.attachClick(click2);
  ejectButtonPin.attachLongPressStart(longclick2);

  EEPROM.get(0, counter);

}

void setColor(int R, int G, int B) {
  analogWrite(redPin,   R);
  analogWrite(greenPin, G);
  analogWrite(bluePin,  B);
}

void loop() {

  buttonPin.tick();
  ejectButtonPin.tick();

  delay(10);
}

void click1() {
  counter = (counter % 5) + 1;
  delay(150); {}

  if (counter == 1) {
    setColor(180, 0, 0); //red
  }

  else if (counter == 2) {
    setColor(0, 0, 0); //off
  }

  else if (counter == 3) {
    setColor(0, 180, 0); //green
  }

  else if (counter == 4) {
    setColor(0, 0, 180);    //blue
  }

  else if (counter == 5) {
    setColor(255, 255, 255); //white
  }

  EEPROM.put(0, counter);
}

In setup you load "counter" but you do not use the loaded value. If you move the color setting to it's own method, you could call that method in setup and in click1():

void setup()
{
  //insert code
  //load counter from eeprom
  setColorFromCounter();
}

void click1()
{
  counter = (counter % 5) + 1;
  delay(150);
  EEPROM.put(0, counter);
  setColorFromCounter();
}

void setColorFromCounter()
{
if (counter == 1) {
    setColor(180, 0, 0); //red
  }

  else if (counter == 2) {
    setColor(0, 0, 0); //off
  }

  else if (counter == 3) {
    setColor(0, 180, 0); //green
  }

  else if (counter == 4) {
    setColor(0, 0, 180);    //blue
  }

  else if (counter == 5) {
    setColor(255, 255, 255); //white
  }
}

That's amazing, thanks! I'm always confused about how I can break up code to perform separate functions.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.