从串口Arduino读取整数

时间:2017-02-01 21:24:29

标签: c arrays arduino serial-port

我已经完成了一个将整数数组写入Arduino的C程序:

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

如何从我的arduino代码(.ino)中捕获文件中的三个整数?

while (Serial.available() > 0) {

    // What can I do here ???

}

1 个答案:

答案 0 :(得分:1)

您需要读取数据并将其放入缓冲区。遇到' '字符后,终止缓冲区内的字符串并将其转换为int 当你这样做三次时,你已经阅读了所有三个整数。

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
}

或者,如果您不介意阻止代码 [1] ,您可以使用内置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]如果您的计算机出现打嗝并且没有立即发送所有数据,您的Arduino代码将只等待数据而不会执行任何其他操作。阅读更多here