Go Down

Topic: RGB LED Debounce button programming help (Read 1 time) previous topic - next topic


Hello,  I am trying to program my Arduino so that when a certain colored button is pushed it lights an LED accordingly.  I am modifying a sample sketch called debounce and it does what i need but, not what I want.  I am having trouble assigning multiple buttons and multiple LEDs. Please review my coding and help would be very much appreciated.

const int buttonPinR = 2;
const int buttonPinG = 3;
const int buttonPinB = 4;
const int ledPinR =  11;
const int ledPinG = 10;
const int ledPinB = 9;

int ledState = HIGH;       
int buttonState;           
int lastButtonState = LOW;   

long lastDebounceTime = 0; 
long debounceDelay = 50;   
void setup() {
  pinMode(buttonPinR, INPUT);
  pinMode(buttonPinG, INPUT);
  pinMode(buttonPinB, OUTPUT);
  pinMode(ledPinR, OUTPUT);
  pinMode(ledPinG, OUTPUT);
  pinMode(ledPinB, OUTPUT);

void loop() {
  int reading = digitalRead(buttonPinR);
   reading = digitalRead(buttonPinG);
   reading = digitalRead(buttonPinB);

  if (reading != lastButtonState) {

    lastDebounceTime = millis();
  if ((millis() - lastDebounceTime) > debounceDelay) {
    buttonState = reading;
  digitalWrite(ledPinR, buttonState);
    digitalWrite(ledPinG, buttonState);
      digitalWrite(ledPinB, buttonState);

  lastButtonState = reading;


You get a mistake here :

  int reading = digitalRead(buttonPinR);
   reading = digitalRead(buttonPinG);
   reading = digitalRead(buttonPinB);

the reading value will ALWAYS be the one from buttonPinB, because it is the last digitalRead...

You can use arrays to perform it, like :

int reading[3];
int buttonState[3];
int lastButtonState[3];

   reading[0] = digitalRead(buttonPinR);
   reading[1] = digitalRead(buttonPinG);
   reading[2] = digitalRead(buttonPinB);

then something like :

for (i=0; i<4; i++)
   if (reading!=lastButtonState)
      lastDebounceTime = millis();

etc... etc..


damn it I been trying to do this for hours and cannot figure it out. Could you further explain the arrays  -_-


It would have been helpful if Grag38 had used the # button around that code. It would then have looked like this:
Code: [Select]
for (i=0; i<3; i++)
  if (reading[i] != lastButtonState[i])
     lastDebounceTime[i] = millis();

The idea is that you have 3 switches on 3 pins (which could/should also be stored in an array), so you need three readings, three states, and three times - one for each switch.

While you could have created readingR, readingG, and readingB, and similar variables for the times and states, the arrays allow you to loop through the elements. The individual variables do not.

In fact, your code could be quite short if you used arrays for the switch and LED pins, too. A loop in setup() to set the pin mode (and enable the pullup resistors), and another loop in loop() to read and act upon the switch states.

By the way, why is buttonPinB an OUTPUT?

Go Up