Разделить строку на массив строк

Я экспериментировал с программированием для Arduino, но сегодня я столкнулся с проблемой, которую я не могу решить, обладая очень ограниченными знаниями Си. Вот как это происходит. Я создаю приложение для ПК, которое отправляет последовательный ввод в arduino (идентификатор устройства, команда, параметры команды). Этот Arduino будет передавать эту команду по RF на другие Arduino. в зависимости от идентификатора устройства правильный Arduino выполнит команду.

Чтобы иметь возможность определять deviceID, я хочу разбить эту строку на ",". это моя проблема, я знаю, как это легко сделать в java (даже не используя стандартную функцию разделения), однако в C это совсем другая история.

Ребята, кто-нибудь из вас может сказать мне, как заставить это работать?

спасибо

/*
  Serial Event example

 When new serial data arrives, this sketch adds it to a String.
 When a newline is received, the loop prints the string and 
 clears it.

 A good test for this is to try it with a GPS receiver 
 that sends out NMEA 0183 sentences. 

 Created 9 May 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/SerialEvent

 */

String inputString;         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
String[] receivedData;

void setup() {
    // initialize serial:
    Serial.begin(9600);
    // reserve 200 bytes for the inputString:
    inputString.reserve(200);
}

void loop() {
    // print the string when a newline arrives:
    if (stringComplete) {
        Serial.println(inputString); 
        // clear the string:
        inputString = "";
        stringComplete = false;
    }
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
    while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read(); 
        if (inChar == '\n') {
            stringComplete = true;
        } 
        // add it to the inputString:
        if(stringComplete == false) {
            inputString += inChar;
        }
        // if the incoming character is a newline, set a flag
        // so the main loop can do something about it:
    }
}

String[] splitCommand(String text, char splitChar) {
    int splitCount = countSplitCharacters(text, splitChar);
    String returnValue[splitCount];
    int index = -1;
    int index2;

    for(int i = 0; i < splitCount - 1; i++) {
        index = text.indexOf(splitChar, index + 1);
        index2 = text.indexOf(splitChar, index + 1);

        if(index2 < 0) index2 = text.length() - 1;
        returnValue[i] = text.substring(index, index2);
    }

    return returnValue;
}

int countSplitCharacters(String text, char splitChar) {
    int returnValue = 0;
    int index = -1;

    while (index > -1) {
        index = text.indexOf(splitChar, index + 1);

        if(index > -1) returnValue+=1;
    }

    return returnValue;
} 

Я решил, что буду использовать функцию strtok . У меня сейчас другая проблема. Произошла ошибка

SerialEvent.cpp: в функции 'void splitCommand (String, char)':

SerialEvent: 68: ошибка: невозможно преобразовать 'String' в 'char *' для аргумента '1' в 'char * strtok (char *, const char *) '

SerialEvent: 68: ошибка:' null 'не был объявлен в этой области

Код похож на

String inputString;         // a string to hold incoming data

void splitCommand(String text, char splitChar) {
    String temp;
    int index = -1;
    int index2;

    for(temp = strtok(text, splitChar); temp; temp = strtok(null, splitChar)) {
        Serial.println(temp);
    }

    for(int i = 0; i < 3; i++) {
        Serial.println(command[i]);
    }
}
11
задан jjm 15 March 2017 в 13:24
поделиться