How to make this code run once in a loop when the button is pressed?

I have a code that I need to be run once only if user presses the button, and after depending on the array generated randomly AD9850 will generate pulses with different frequencies.

  String after[4];
  String before[]={"1000","0100","0010","0001"};
  uint8_t array_size = sizeof(before) / sizeof(before[0]);
  int LED=13;
  int btn=5;
  int btn_state;

void setup() {
  Serial.begin(9600);
  while(!Serial);
  pinMode(LED, OUTPUT);
  pinMode(btn, INPUT_PULLUP);
  btn_state=digitalRead(btn);
  randomSeed(analogRead(0));
  for(int i=0; i<4; i++) {
  
    // ---Pick a random array element.---
    uint8_t pick = random(0, array_size);

    // ---Display the value.---
    //Serial.println(before[pick]);

    // ---Assign the values to after[] array---
    after[i]=before[pick];
    //Serial.println(after[i]);

    // ---Overwrite with the last element of the array.---
    before[pick] = before[array_size - 1];

    // ---Reduce the array size to be selected.---
    array_size--;
    digitalWrite(LED, HIGH);
  }
  
  for (String element : after)
  Serial.println(element);
  
  }


void loop() {
  
}

The problem is that I can not acces thhe array in loop() function, or in any other function as it is a local variable. My "circuit" is here (sorry for simplicity):

изображение

So when the button is pressed random array is generated and displayed on OLED menu, also pulses are generated by AD9850 and with encoder I can change the interval between different LFM pulses.
Thanks in advance.

What array are you talking about?

before[] array after mixing its elements (in for loop)

Array before[] is not a local, it is global variable
What's your problem with it?

it is global here

String after[4];
  String before[]={"1000","0100","0010","0001"};
  uint8_t array_size = sizeof(before) / sizeof(before[0]);
  int LED=13;
  int btn=5;
  int btn_state;

but i need this array after being mixed, after this code:

randomSeed(analogRead(0));
  for(int i=0; i<4; i++) {
    // ---Pick a random array element.---
    uint8_t pick = random(0, array_size);

    // ---Assign the values to after[] array---
    after[i]=before[pick];

    // ---Overwrite with the last element of the array.---
    before[pick] = before[array_size - 1];

    // ---Reduce the array size to be selected.---
    array_size--;
  }

before for loop the array before[] is like a sequence for ex. [1,2,3,4] is global, after for loop it becomes mixed for ex. [3,1,2,4] only inside setup() function. I need [3,1,2,4], not [1,2,3,4]. But in loop() function whenever I serial print before[] array, it prints [1,2,3,4].

This is not true. By changing an array in setup, you are changing the global array.
If you then print its elements in the loop(), they will be changed

Also, your question doesn't match the title at all.

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