c - 从串行端口 Arduino 读取整数



我做了一个C程序,将整数数组写入Arduino:

// ...
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 ???
}

您需要读取数据并将其放入缓冲区中。遇到' '字符后,终止缓冲区内的字符串并将其转换为 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 代码将只等待数据,而不会执行任何其他操作。在此处阅读更多内容。

最新更新