简体   繁体   中英

Reading ints from serial port Arduino

I've done a C program that writes an integer array into the Arduino:

// ...
FILE* file;
file = fopen("/dev/ttyuSB0","w");
for (int i = 0; i < 3; i++) {
    fprintf(file, "%d ", rgb[i]);
}
fclose(file);
// ...

How can I do from my arduino code (.ino) to catch the three integers from the file?

while (Serial.available() > 0) {

    // What can I do here ???

}

You need to read the data and put it into a buffer. After you encounter a ' ' character you terminate the string inside the buffer and convert it into an int.
When you do this three times you have read all three ints.

const uint8_t buff_len = 7; // buffer size
char buff[buff_len]; // buffer
uint8_t buff_i = 0; // buffer index

int arr[3] = {0,0,0}; // number array
uint8_t arr_i = 0; // number array index

void loop() {
    while (Serial.available() > 0) {
        char c = Serial.read();
        if (buff_i < buff_len-1) { // check if buffer is full
            if (c == ' ') { // check if got number terminator
                buff[buff_i++] = 0; // terminate the string
                buff_i = 0; // reset the buffer index
                arr[arr_i++] = atoi(buff); // convert the string to int
                if (arr_i == 3) { // if got all three numbers
                    arr_i = 0; // reset the number array index

                    // do something with the three integers
                }
            }
            else if (c == '-' || ('0' <= c && c <= '9')) // if negative sign or valid digit
                buff[buff_i++] = c; // put the char into the buffer
        }
    }
    // maybe do some other stuff
}

Or if you don't mind blocking code [1] you can use builtin ParseInt .

void loop() {
    while (Serial.available() > 0) {
        arr[0] = Serial.parseInt();
        arr[1] = Serial.parseInt();
        arr[2] = Serial.parseInt();
        Serial.read(); // read off the last space

        // do something with the three integers
    }
    // maybe do some other stuff, but might be blocked by serial read
}

[1] If your computer has a hiccup and doesn't send all the data at once, your Arduino code will just wait for data and won't be doing anything else. Read more here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM