ARDUINO按钮不会为我随机化数字

时间:2015-11-18 10:16:48

标签: arduino

请帮帮我。当我按下按钮时,Arduino不会随机抽取任何数字?我找不到解决方案,我希望你们能帮助我。 该项目是为了让我的学校每年都举办一次。如果你们需要更多信息,请随时提出!

const int buttonPin = 1;   
const int ledPin = 12;      
int ledState = HIGH;        
int buttonState;            
int lastButtonState = LOW; 
int counter = 0;
int randNumber;

// the following variables are long's because the time, measured in    miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers


void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
  Serial.begin(1200);
}

void loop() {
   if(counter==0 && buttonState==HIGH){
  randNumber = random(1,7);
  Serial.println(randNumber);
  Serial.println("counter" + counter);
  counter=2;

  }


  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState) {

    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
      if (reading != buttonState) {
      buttonState = reading;

      if (buttonState == HIGH) {
        ledState = !ledState;

      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}

1 个答案:

答案 0 :(得分:0)

你的去抖将永远不会奏效,因为你每次都要重置状态。

由于重新发明轮子是没用的,我建议你使用Bounce2库,为你处理debouncing。

这样的东西应该有用...我还修了一些类型(尽可能使用byte而不是int,因为处理器是8位的。)

#include <Bounce2.h>

Bounce debouncedButton = Bounce();

const byte buttonPin = 1;   
const byte ledPin = 12;      
byte ledState = HIGH; 
byte randNumber;

byte lastButtonState;

const byte debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
    pinMode(buttonPin, INPUT);
    pinMode(ledPin, OUTPUT);

    debouncedButton.attach(buttonPin);
    debouncedButton.interval(debounceDelay);

    // set initial LED state
    digitalWrite(ledPin, ledState);
    Serial.begin(1200);
    lastButtonState = digitalRead(buttonPin);
}

void loop() {
    debouncedButton.update();

    byte buttonState = debouncedButton.read();

    if(counter==0 && buttonState==HIGH){
        randNumber = random(1,7);
        Serial.println(randNumber);
        Serial.println("counter" + counter);
        counter=2;
    }

    if ((lastButtonState != buttonState) && (buttonState == HIGH))
        ledState = !ledState;

    digitalWrite(ledPin, ledState);

    lastButtonState = buttonState;
}

还有两件事:

  1. 为什么使用1200 b / s波特率?它不是太低了吗?通常最低使用率为9600,但我通常使用115200(除非其他设备不支持)
  2. 我无法理解counter变量的使用情况。你使用它(和我复制)的方式将防止随机数生成,因为没有任何东西会重置它。如果您想计算生成的数字数量,请删除counter==0测试,请写counter++而不是counter=2,并在setup函数中将变量初始化为0