1

I have this really simple code. Let's say I have a variable X. Then all I want to do is create a random value R, if R > X then I want X to become R. But for some reason, my n_of_buttons_pressed climbs up and then sometimes drops back to lower values. I can not wrap my head around how it could get a lower value then a previous value.

#define N_OF_BUTTONS 60

int n_of_buttons_pressed;


void setup() {
  Serial.begin(9600);
  Serial.println("start");
}

void loop() {

  n_of_buttons_pressed = (int) max(random(0, N_OF_BUTTONS), n_of_buttons_pressed);

  Serial.print("n_of_buttons_pressed:");
  Serial.print(n_of_buttons_pressed);
  Serial.println();

  delay(100);

}
7

The max() “function” is actually a macro defined in Arduino.h as

#define max(a,b) ((a)>(b)?(a):(b))

This expands in your code into something like

buttons_pressed = random(0, N_OF_BUTTONS) > n_of_buttons_pressed) ? \
                  random(0, N_OF_BUTTONS) : n_of_buttons_pressed

The problem with the macro is that it evaluates at least one of its arguments twice. In this case, if the test is true, the variable buttons_pressed gets assigned another pseudo-random number.

The way around this is to store the pseudo-random number in a variable, to avoid random() being evaluated twice:

int pseudo_random = random(0, N_OF_BUTTONS);
buttons_pressed = max(pseudo_random, n_of_buttons_pressed);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.