2015-11-18 20 views
0

請幫助我。當我按下按鈕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; 
} 

回答

0

由於您每次都重置狀態,您的反彈將永遠不會奏效。

由於重新發明輪子是無用的,我建議您使用Bounce2庫,它可以爲您處理反彈。

這樣的東西應該可以工作......我還修復了一些類型(可以使用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
+0

非常感謝您的回答!它是9600,沒有計數器== 0等等。我改變他們只是因爲我需要測試它是如何工作的。但非常感謝!祝你今天愉快! –

+0

很高興工作;) – frarugi87