3

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());
3
  • Is the int a fixed number of characters or will it be terminated by a non-numeric? Commented Apr 21, 2013 at 7:29
  • Mmm... Serial.read() already returns an int... Commented Apr 21, 2013 at 7:54
  • @angelatlarge Serial.read() does return an int but only so that the calling code can distinguish between a successful read and an error. Correct usage treats the return value as a byte after checking that it doesn't return -1 (which indicates an error). Commented Apr 22, 2013 at 11:29

2 Answers 2

5

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I had to change byte intBuffer[12]; to char intBuffer[12]; for it to compile
5

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

1 Comment

Not sure what the benefits of the above method are, but this worked for me perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.