0

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).

2 Answers2

3

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() {
    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 (psedo-code):

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

which becomes:

int getRandomPwmPin() {
    int value;
    do {
        value = TrueRandom.random(3, 12);
    } while ((value == 4) || (value == 7) || (value == 8));
    return value;
}

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


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

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
2

The trick is to make a list of pins and then pick an entry from the list at random

int pins[]={3,5,6,11,10,9}

int choice = rnd() //in range 0-5 

pin = pins[choice]

see Generating random integer from a range to get number in range

Community
  • 1
  • 1
Martin Beckett
  • 94,801
  • 28
  • 188
  • 263