Serial message to integer on Arduino

2019-05-11 05:51发布

问题:

I want my Arduino to receive an integer through the serial communication. Can you help me with this?

It should be in a form like:

int value = strtoint(Serial.read());

回答1:

There are several ways to read an integer from Serial, largely depending on how the data is encoded when it is sent. Serial.read() can only be used to read individual bytes so the data that is sent needs to be reconstructed from these bytes.

The following code may work for you. It assumes that serial connection has been configured to 9600 baud, that data is being sent as ASCII text and that each integer is delimited by a newline character (\n):

// 12 is the maximum length of a decimal representation of a 32-bit integer,
// including space for a leading minus sign and terminating null byte
byte intBuffer[12];
String intData = "";
int delimiter = (int) '\n';

void setup() {
    Serial.begin(9600);
}

void loop() {
    while (Serial.available()) {
        int ch = Serial.read();
        if (ch == -1) {
            // Handle error
        }
        else if (ch == delimiter) {
            break;
        }
        else {
            intData += (char) ch;
        }
    }

    // Copy read data into a char array for use by atoi
    // Include room for the null terminator
    int intLength = intData.length() + 1;
    intData.toCharArray(intBuffer, intLength);

    // Reinitialize intData for use next time around the loop
    intData = "";

    // Convert ASCII-encoded integer to an int
    int i = atoi(intBuffer);
}


回答2:

You may use the Serial.parseInt() function, see here: http://arduino.cc/en/Reference/ParseInt