kuatemachu kuatemachu - 2 months ago 23
C Question

Pick a random pwm pin in Arduino

I want to pick a random PWM pin each time a loop repeats. The pins that are PWM capable in the Arduino UNO are pins: 3,5,6,11,10,9. I tried rnd() but it gives me linear values from a range, same with TrueRandom.Random(1,9).

Answer

Well, there are at least two way to do it.

The first (and probably best) way is to load those values into an array of size six, generate a number in the range zero through five and get the value from that position in the array.

In other words, psedo-code such as:

values = [3, 5, 6, 9, 10, 11]
num = values[randomInclusive(0..5)]

In terms of actually implementing that pseudo-code, I'd look at something like:

int getRandomPwmPin(void) {
    static const int candidate[] = {3, 5, 6, 9, 10, 11};
    static const int count = sizeof(candidate) / sizeof(*candidate);
    return candidate[TrueRandom.random(0, count)];
}

There's also the naive way of doing it, which is to generate numbers in a range and simply throw away those that don't meet your specification (i.e., go back and get another one). This is actually an inferior method as it may take longer to get a suitable number under some circumstances. Technically, it could even take an infinitely(a) long time if suitable values don't appear.

This would be along the lines of:

num = -1  // force entry into loop
while num is not one of 3, 5, 6, 9, 10, 11:
    num = randomInclusive(3..11)

As stated, the former solution is probably the best one. I include the latter only for informational purposes.


(a) Yes, I know. Over an infinite time frame , statistics pretty much guarantees you'll get a useful value eventually. Stop being a pedant about my hyperbole :-)