Catching instantiation errors

Referring to this WOKWI project:

Starting at line 87 are these statements:

const uint8_t orangeLED = 4;
const uint8_t greenLED = 2;
const uint8_t blueLED = 4;
const uint8_t yellowLED = 7;
const uint8_t orangeSwitch = A0;
const uint8_t greenSwitch = A1;
const uint8_t blueSwitch = A2;
const uint8_t yellowPot = A3;

// Following the form: input inverted, output pin, output inverted, T1 ms, T2 ms.
// T2 is optional; if T2 not included ON and OFF times will be equal.
//
SimpleFlasher orangeFlasher(false, orangeLED, false, 337, 2107); // Instantiate a flasher object
SimpleFlasher greenFlasher(true, greenLED, false, 100, 3000); // Instantiate a flasher object
SimpleFlasher blueFlasher(false, blueLED, false, 647); // Instantiate a flasher object
SimpleFlasher yellowFlasher(true, yellowLED, false, 200, 2100); // Instantiate a flasher object

Notice that the orangeLED and the blueLED are both given the same pin number.  Unsurprisingly this causes the respective outputs to misbehave.

My question:  Is there a way to crosscheck the pin assignments against each other and flag duplicates to give some notice at run time?

Why at runtime? Compile time would be better but neither are really possible.

That is why I always have a pin declaration section with the pins in ascending order, not grouped by function or category.

1 Like

I can see a way to do it at compile-time if the constant identifiers (e.g. use 4 instead of orangeLED) are not used. But that would place an annoying restriction on the user.

I think the only way to do it at run-time would be to maintain a global integer set. That's not especially difficult but more code means more possibility of bugs.

The biggest caveat with run-time detection would be deciding how to report the mistake. Dealing with it during construction is certainly problematic.

Now that I think of it all I was really after was some way to let a human know there's a problem before the hardware starts breaking.   So compile time would work too.

At a minimum I suppose one could flash the built-in LED on an UNO.  But, what if the built-in LED is one of those designated for a flasher?  Possibly a message could be sent to the serial monitor.

I think a comment to the effect of 'Don't do this!' may be the answer.

That would be even more obvious if you assigned names in pin-number order:

const uint8_t greenLED = 2;
const uint8_t orangeLED = 4;
const uint8_t blueLED = 4;
const uint8_t yellowLED = 7;

That makes it a little clearer that you are assigning two different names to Pin 4.

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