0

Я пытаюсь отправить два разных десятичных значения последовательно Arduino. Значения, которые отправляются в Arduino, разделяются запятой (,):Как отправить несколько разных значений с плавающей запятой или десятичной точкой последовательно в Arduino?

. 1.23.4.56

Моя проблема в том, что, когда значения принимаются микроконтроллером Arduino, код, похоже, не выводит желаемый результат.

Обе команды Serial.println видели в коде ниже выводит следующий за VALUE_1 переменных и значения_2:

1,20

0,00

4,50

0,00

Так я не понимаю, почему в обеих переменных есть дополнительное значение «0.00».

Заранее спасибо.

const int MaxChars = 3; // an int string contains up to 3 digits (3 s.f.) and 
         // is terminated by a 0 to indicate end of string 
char strValue_1[MaxChars+1]; // must be big enough for digits and terminating null 
char strValue_2[MaxChars+1]; // must be big enough for digits and terminating null 
int index_1 = 0;   // the index into the array storing the received digits 
int index_2 = 0;   // the index into the array storing the received digits 
double value_1; 
double value_2; 

void setup() 
{ 
    Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud 
} 

void loop() 
{ 
if(Serial.available()) 
{ 
char ch = Serial.read(); 
if(index_1 < MaxChars && ch >= '.' && ch <= '9') 
{ 
    strValue_1[index_1++] = ch; // add the ASCII character to the array; 

} 
else if (ch == ',') 
{ 
    if(index_2 < MaxChars && ch >= '.' && ch <= '9') 
    { 
     strValue_2[index_2++] = ch; // add the ASCII character to the array; 
    } 
} 
else 
{ 
    // here when buffer full or on the first non digit 
    strValue_1[index_1] = 0;  // terminate the string with a 0 
    strValue_2[index_2] = 0;  // terminate the string with a 0 
    value_1 = atof(strValue_1);  // use atof to convert the string to an float 
    value_2 = atof(strValue_2);  // use atof to convert the string to an float 
    Serial.println(value_1); 
    Serial.println(value_2); 
    index_1 = 0; 
    index_2 = 0; 
} 
} 
} 

Ниже самая последняя отредактированная версия кода, как предложено @mactro и @aksonlyaks, я до сих пор не удалось получить желаемых результатов, поэтому я открыт для более предложений.

В текущей выходе я получаю для конкретного ввода 1.23,4.56 для следующих переменных:

strValue [0]:

1,2

strValue [1]:

1,2

4,5

Valu e_1:

1,20

0,00

значение_2:

1,20

4,50

Заранее спасибо.

Вот самая последняя версия Кодекса:

const int MaxChars = 4; // an int string contains up to 3 digits (3 s.f.) including the '\0' and 
        // is terminated by a 0 to indicate end of string 

const int numberOfFields = 2; //Amount of Data to be stored 
char strValue[numberOfFields][MaxChars+1]; // must be big enough for digits and terminating null 

int index_1 = 0;   // the index into the array storing the received digits 

double value_1; 
double value_2; 

int arrayVal = 0; 

void setup() 
{ 
    Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud 
} 

void loop() 
{ 

if(Serial.available()) 
{ 
    char ch = Serial.read(); 

if (ch == ',') 
{ 
    arrayVal = 1; 

    if(index_1 < MaxChars-1 && ch >= '.' && ch <= '9') 
    { 
     strValue[arrayVal][index_1++] = ch; // add the ASCII character to the array; 
    } 
    if(index_1 == MaxChars - 1) 
    { 
     strValue[arrayVal][index_1++] = '\0'; 
    } 

} 
else if(index_1 < MaxChars-1 && ch >= '.' && ch <= '9') 
{ 
    strValue[arrayVal][index_1++] = ch; // add the ASCII character to the array; 

if(index_1 == MaxChars - 1) 
{ 
    strValue[arrayVal][index_1++] = '\0'; 
} 

} 

else 
{ 

    value_1 = atof(strValue[0]);  // use atof to convert the string to an float 
    value_2 = atof(strValue[1]);  // use atof to convert the string to an float 
    Serial.println(value_1); 
    Serial.println(value_2); 
    index_1 = 0; 
    arrayVal = 0; 
} 
} 
} 

ответ

0

Я внес некоторые изменения в ваш код, и теперь он печатает то, что вы хотите. Модифицированный код выглядит следующим образом:

const int MaxChars = 4; // an int string contains up to 3 digits (3 s.f.) including the '\0' and 
        // is terminated by a 0 to indicate end of string 

const int numberOfFields = 2; //Amount of Data to be stored 
char strValue[numberOfFields][MaxChars+1]; // must be big enough for digits and terminating null 

int index_1 = 0;   // the index into the array storing the received digits 

double value_1; 
double value_2; 

int arrayVal = 0; 

void setup() 
{ 
    Serial.begin(9600); // Initialize serial port to send and receive at 9600 baud 
} 

void loop() 
{ 

    if(Serial.available()) 
    { 
     char ch = Serial.read(); 

     if (ch == ',') 
     { 
      arrayVal = 1; 
      index_1 = 0; // Initialise this to zero for the float value received after ',' 
/* 
      if(index_1 < MaxChars-1 && ch >= '.' && ch <= '9') 
      { 
       strValue[arrayVal][index_1++] = ch; // add the ASCII character to the array; 
      } 
      if(index_1 == MaxChars - 1) 
      { 
       strValue[arrayVal][index_1++] = '\0'; 
      } 
*/ 
     } 
     else if((index_1 < MaxChars + 1) && (ch >= '.' && ch <= '9')) // one float value size including null character is 5 (1.23 size 4) 
     { 
      strValue[arrayVal][index_1++] = ch; // add the ASCII character to the array; 
      if(index_1 == MaxChars)    // When we have recevied the 4 character of float value add NULL character 
      { 
       strValue[arrayVal][index_1++] = '\0'; 
      } 
     }else 
     { 
      value_1 = atof(strValue[0]);  // use atof to convert the string to an float 
      value_2 = atof(strValue[1]);  // use atof to convert the string to an float 
      Serial.println(value_1); 
      Serial.println(value_2); 
      index_1 = 0; 
      arrayVal = 0; 
     } 
    } 
} 

Кроме того, я сделал правильный отступ для вашего кода.

Дайте мне знать, если это поможет.

С уважением

+0

Да его печать значения, как требуется сейчас, спасибо за помощь. –

0

Вы никогда не добавляйте ничего strValue_2, потому что

if(index_2 < MaxChars && ch >= '.' && ch <= '9') 
{ 
    strValue_2[index_2++] = ch; // add the ASCII character to the array; 
} 

выполняется только тогда, когда ch==','. Когда вы получаете запятую, вы должны установить флаг, который будет сигнализировать код для ввода дополнительных символов в strValue_2 вместо strValue_1.Или у вас может быть массив строк, например char strValues[2][MaxChars+1], и изменение и индекс элемента, в который вы пишете strValues[stringNumber][index++].

+0

Я дал свой метод с использованием массива строк попробовать, и я добавил код на мой вопрос, как вы можете видеть выше. Тем не менее, я все еще не могу решить проблему, не могли бы вы дать мне больше намеков относительно того, что я делаю неправильно на этот раз с новым кодом. Я думаю, проблема связана с установкой флага, может быть, вы могли бы предложить способ, как я могу это сделать лучше. Большое спасибо за ваш отзыв. –

+0

@bat_wave Какой результат вы получаете сейчас? Попробуйте 'Serial.println (strValue [0])', чтобы вы знали, что находится внутри буфера. – mactro

+0

Я попробовал 'Serial.println (strValue [0])'. Я ввожу значения: 1.23.4.56. И значение, которое выдает: 1.2 1.2 Я не уверен, что вызывает дублирование. И когда я делаю то же самое, но с 'Serial.println (strValue [1])' для того же входа 1.23.4.56. Я получаю результат: 4.5 После преобразования atof, значение_1 дает: 1,20 1,20 –

Смежные вопросы