problem with code

In my naive, knows the square-root of diddly-squat about railway signalling way, I attempted to produce a simple framework to factor the code, presented below.

Do with it as you will.

(uncompiled, untested)

struct Signal 
{
  byte redLED;
  byte yellowLED;
  byte greenLED;
};

Signal signals [] = {{2, 3, 4},
                           {5, 6, 7},
                           {8, 9, 10}};

const byte inPins [] = {14, 15, 16};
const byte nSwitches = sizeof (inPins) / sizeof (inPins [0]);

const int LED_OFF = LOW;  // Depeding on how the LEDs are wired, you may 
const int LED_ON  = HIGH;  // need to swap these over.

void setup()
{
  for (auto & sig : signals ) {
    pinMode(sig.redLED, OUTPUT); 
    pinMode(sig.yellowLED, OUTPUT);
    pinMode(sig.greenLED, OUTPUT);
    setSignalState (sig, LED_OFF, LED_OFF, LED_ON);
  }

  for (auto & switchPin : inPins) {
    pinMode (switchPin, INPUT_PULLUP);
  }
}


void setSignalState (Signal& sig, byte redState, byte yellowState, byte greenState)
{
    digitalWrite (sig.redLED,     redState);
    digitalWrite (sig.yellowLED, yellowState);
    digitalWrite (sig.greenLED, greenState);
}

void loop() 
{
  int switchState [nSwitches];
  for (int i = 0; i < nSwitches; i++) {
    switchState [i] = digitalRead (inPins [i]);
  }
  // your code here
}

I think the problem you are having with conflicts between the buttons is caused by setting the LED's whenever the button is in the open state (HIGH) or closed state (LOW). I think your problems would be solved by acting only on CHANGES in the state. Here is an example of how that would be done for inPin1:

  static int oldval1 = HIGH;  // 'static' means 'keep the value between calls to this function'
  int newval1 = digitalRead(inPin1); // read input value 1
  if (newval1 != oldval1)            // check if input 1 has changed
  {
    oldval1 = newval1;


    if (newval1 == LOW)
    {
      // Button has just been pressed
      digitalWrite(R1, HIGH);   // turn R1 ON
      digitalWrite(Y1, LOW);    // turn Y1 OFF
      digitalWrite(G1, LOW);    // turn G1 OFF
      digitalWrite(Y2, HIGH);   // turn Y2 ON
      digitalWrite(G2, LOW);    // turn G2 OFF
    }
    else
    {
      // Button has just been released
      digitalWrite(R1, LOW);    // turn R1 OFF
      digitalWrite(G1, HIGH);   // turn G1 ON
      digitalWrite(Y2, LOW);    // turn Y2 OFF
      digitalWrite(G2, HIGH);   // turn G2 ON
    }
  }

When the button is not being actively pressed or released it will do nothing to the LEDs, allowing them to be controlled by the buttons that are actually being moved.

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