arduino serial HELP ME

时间:2016-12-22 18:41:45

标签: arduino serial-port arduino-uno serial-communication

当串口上传来某条消息但没有任何工作时,我正试图让LED点亮! 请帮帮我!!

int awsState = "AWS:0";   // for incoming serial data

 void setup() {
    Serial.begin(9600);   
    pinMode(13, OUTPUT);
}

void loop() {

    // send data only when you receive data:
    if (Serial.available() > 0) {
            // read the incoming byte:
            awsState = Serial.read();

            // say what you got:
            Serial.print(incomingByte);
            Serial.println("Good");
            if (awsState == "AWS:1"){

              digitalWrite(13, HIGH);
            }
    else if (awsState == "AWS:0"){
      digitalWrite(13, LOW);
    }
    }

}

1 个答案:

答案 0 :(得分:-1)

这是一种从Serial链接读取命令的方法。

步骤1 - 声明一个String以将输入数据存储为全局变量

String awsState;

而不是:

int awsState = "AWS:0"; 

第2步 - 初始化setup()

中的字符串
void setup() {
    Serial.begin(9600);   
    pinMode(13, OUTPUT);
    awsState= "";
}

第3步 - 提取所有收到的字符,显示它们并处理命令

void loop() {
    while (Serial.available() > 0) {
        // read all received characters
        char rec =  Serial.read();
        // until <return> character
        if (rec != '\n') {
            awsState += rec; 
        }
        else {
            Serial.print(awsState);
            Serial.println("Good");
            if (awsState == "AWS:1"){
              digitalWrite(13, HIGH);
            }
            else if (awsState == "AWS:0"){
              digitalWrite(13, LOW);
            }
            // reset the command to wait the next one
            awsState= "";
        }
    }
}