我需要使按钮随机化,然后显示在 4 段上

i need to make the button randomize and then display on a 4-segment

那是我的主要代码,在无效循环中我想制作它所以有一个按钮激活的随机函数,然后它进入要显示的 sevseg.setNumber 部分。我正在尝试制作一个 20 面的骰子,因此随机函数将为 1-20。我不太确定该怎么做,我能得到一些帮助吗?

#include "SevSeg.h"
SevSeg sevseg; 


const int  BUTTON = 1;    
int buttonState = 0;          
int lastButtonState = LOW;   

void setup(){
  byte numDigits = 4;
  byte digitPins[] = {10, 11, 12, 13};
  byte segmentPins[] = {9, 2, 3, 5, 6, 8, 7, 4};

  bool resistorsOnSegments = true; 
  bool updateWithDelaysIn = true;
  byte hardwareConfig = COMMON_ANODE; 
  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, 
resistorsOnSegments);
  sevseg.setBrightness(150);

  pinMode(BUTTON, OUTPUT);
  Serial.begin(9600);
  lastButtonState = LOW;
}

void loop(){
  sevseg.setNumber();
  sevseg.refreshDisplay();
  if (digitalRead (BUTTON) == HIGH)
  {
    rand() % 20 + 1;
  }
}

我将 buttonPin 更改为 BUTTON,现在我需要弄清楚如何将 rand 值放在 sevseg.setNumber 的括号内。

像这样更改主循环:

void loop(){

  if (digitalRead (BUTTON) == HIGH)
  {
    if (!high) {//<-- make sure it only changes the value the first time
      sevseg.setNumber(rand() % 20 + 1);
      sevseg.refreshDisplay();
      high = true
    }
  }
  else {
    high = false;//<-- reset high to false when the button isn't pressed anymore
  } 
}

不要忘记在定义部分声明 bool high = false;