Arduino组合按钮?

时间:2017-01-13 03:30:13

标签: arduino arduino-uno arduino-ide

我正在尝试设置一个Arduino Uno加上一个RelayShield以及6个按钮(标准)和3个LED(红色,黄色,绿色)。现在我要做的代码是接受一个长按6次的按钮推送组合(命令仅对数组中设置的内容很重要)。我把所有东西连接到面包板和所有其他爵士乐。我的问题是,没有一个LED正在工作(我遵循了instructables的详细说明 - 减去代码),并且无论有多少按钮推动都没关系,只有按钮3触发继电器....现在,对于简单性为了这个,我没有连接所有6个按钮,我只是将阵列缩短为3并相应调整(我现在不想连接6个按钮)。有人可以为我验证这段代码吗?或者告诉我它有什么问题?提前谢谢!

//button pins
const int button1 = 2;
const int button2 = 3;
const int button3 = 4;
const int button4 = 5;
const int button5 = 6;
const int button6 = 7;
const int grnLed = 9;
const int redLed = 10;
const int yellowLed = 11;
const int openRelay = 8;

// how long is our code, kinda personal
const int codelen = 3;

//pin code values must match button pin values
char PIN[codelen] = {
'1', '2', '3'
};

// attempted combo
char attempt[codelen] = {
'0', '0', '0'
};

// attempt count
int z = 0;

void setup() {
// you've been setup
pinMode(button1, INPUT);
pinMode(button2, INPUT);
pinMode(button3, INPUT);
pinMode(button4, INPUT);
pinMode(button5, INPUT);
pinMode(button6, INPUT);
pinMode(openRelay, OUTPUT);
// set pullup resistor for buttons
digitalWrite(button1, HIGH);
digitalWrite(button2, HIGH);
digitalWrite(button3, HIGH);
digitalWrite(button4, HIGH);
digitalWrite(button5, HIGH);
digitalWrite(button6, HIGH);
// set openRelay state to open or closed
digitalWrite(openRelay, LOW);
}

void correctPIN()
{
pulseLED(grnLed, 3000);
digitalWrite(openRelay, HIGH);
delay(2000);
digitalWrite(openRelay, LOW);
delay(2000);
z = 0;
}
void incorrectPIN()
{
pulseLED(redLed, 3000);
z = 0;
}

void checkPIN()
{
int correct = 0;
int i;
for (i = 0; i < codelen; i++)
{

    if (attempt[i] == PIN[i])
    {
        correct++;
    }
}
if (correct == codelen)
{
    correctPIN();
}
else
{
    incorrectPIN();
}

for (int zz = 0; zz < codelen; zz++)
{
    attempt[zz] = '0';
}
}

void checkButton(int button){

if (digitalRead(button) == LOW)
{   
    while (digitalRead(button) == LOW) { } // do nothing
    //convert int to string for tracking/compare
    char buttStr = button + '0';
    attempt[z] = buttStr;
    z++;
    //light up led so we know btn press worked
    pulseLED(yellowLed, 500);
}
}

void pulseLED(int ledpin, int msec) {
digitalWrite(ledpin, HIGH);
delay(msec);
digitalWrite(ledpin, LOW);
}

void loop() {
// check buttons 
checkButton(button1);
checkButton(button2);
checkButton(button3);
checkButton(button4);
checkButton(button5);
checkButton(button6);
//if number of buttons pressed, z, matches code/pin length then check
if (z >= codelen)
{
    checkPIN();     
}   
}

0 个答案:

没有答案