Arduino中的Serial和DigitalRead输入

时间:2016-06-27 06:07:03

标签: button arduino led

我在编写Arduino时遇到了问题。 我想从Serial Port接收char来打开LED并用按钮关闭。

请检查我的代码。

#include SoftwareSerial.h

int led[] = {30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53};
int buttons[] = {4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,22,23,24,25,26,27,28,29};

void setup() {
  Serial.begin(9600);
  for (int i=0; i<sizeof(buttons); i++){
    pinMode(buttons[i], INPUT);
  }
  for (int i=0; i<sizeof(led); i++){
    pinMode(led[i], OUTPUT);
  }
  for (int i=0; i<sizeof(led); i++){
    digitalWrite(led[i], HIGH);
    delay(10);
  }
}
void loop(){
  for (int i=0; i<sizeof(buttons); i++){
    if(digitalRead(buttons[i])==stbtn[i]){
      digitalWrite(led[i], HIGH);
    }
  }
  if(Serial.available()) {
    char inChar = (char)Serial.read();
    switch (inChar){
     case 'A': digitalWrite(led[0], LOW); stbtn[0]=0; break;
     case 'B': digitalWrite(led[1], LOW); stbtn[1]=0; break;
     case 'C': digitalWrite(led[2], LOW); stbtn[2]=0; break;
     case 'D': digitalWrite(led[3], LOW); stbtn[3]=0; break;
     case 'E': digitalWrite(led[4], LOW); stbtn[4]=0; break;
     case 'F': digitalWrite(led[5], LOW); stbtn[5]=0; break;
     case 'G': digitalWrite(led[6], LOW); stbtn[6]=0; break;
     case 'H': digitalWrite(led[7], LOW); stbtn[7]=0; break;
     case 'I': digitalWrite(led[8], LOW); stbtn[8]=0; break;
     case 'J': digitalWrite(led[9], LOW); stbtn[9]=0; break;
     case 'K': digitalWrite(led[10], LOW); stbtn[10]=0; break;
     case 'L': digitalWrite(led[11], LOW); stbtn[11]=0; break;
     case 'M': digitalWrite(led[12], LOW); stbtn[12]=0; break;
     case 'N': digitalWrite(led[13], LOW); stbtn[13]=0; break;
     case 'O': digitalWrite(led[14], LOW); stbtn[14]=0; break;
     case 'P': digitalWrite(led[15], LOW); stbtn[15]=0; break;
     case 'Q': digitalWrite(led[16], LOW); stbtn[16]=0; break;
     case 'R': digitalWrite(led[17], LOW); stbtn[17]=0; break;
     case 'S': digitalWrite(led[18], LOW); stbtn[18]=0; break;
     case 'T': digitalWrite(led[19], LOW); stbtn[19]=0; break;
     case 'U': digitalWrite(led[20], LOW); stbtn[20]=0; break;
     case 'V': digitalWrite(led[21], LOW); stbtn[21]=0; break;
     case 'W': digitalWrite(led[22], LOW); stbtn[22]=0; break;
     case 'X': digitalWrite(led[23], LOW); stbtn[23]=0; break; 
    }
  }
}

0 个答案:

没有答案