W
W
WhatYouDoing2016-11-20 09:27:50
Arduino
WhatYouDoing, 2016-11-20 09:27:50

How to read data from serial port correctly?

How can I properly process a string that is sent on a port? now the line looks like this

100%\n
, I pass the value of the processor, but I would also like to transfer another value, for example, RAM, if I pass it, everything is mixed into a heap, who has any options? I think that you need to add headers to the lines, something like this
CPU: 100%\n
, but how then to process it correctly in arudino a piece of code of the current firmware
char rx_byte = 0;
String rx_str = "";

void loop() {
  if (Serial.available() > 0) {
    rx_byte = Serial.read();
    
    if (rx_byte != '\n') {
      rx_str += rx_byte;
    }
    else {
    display.setTextSize(1);
    display.setTextColor(WHITE);
    display.setCursor(10,0);
   
    display.clearDisplay();
    display.println("Usage CPU - " + rx_str);
    rx_str = "";
    display.display();
                   
    }
  } 
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Volkov, 2016-11-21
@a_volkov1987

1 byte - ID of the parameter (0x01 - CPU, 0x02 - RAM, etc.)
2 bytes - Value of the parameter
3 bytes - XOR between ID and Value
4 bytes - sign of the end of the transfer 0xFA, for example
Total transfer 4 bytes
On arduino:

int counter = 0;
if (Serial.available() > 0){
    rx_byte = Serial.read();
    if(rx_byte !=0xFA)
    {
        read_array[counter] = rx_byte
    }
    else
    {
     counter = 0;   
     if ((read_array[0] xor read_array[1])== read_array[3])
        {
        //данные приняты успешно, можно передавать в обработку
        }
        else
        {
        //данные искажены, не берем их в расчет
        } 
    }
}

The code is conditional, only to demonstrate the idea of ​​transmitting a packet with slightly better noise immunity than none.

E
evgeniy_lm, 2016-11-20
@evgeniy_lm

What does "everything is mixed together" mean? You have \n as a line separator control character, you can pass as many parameters as you like in this format. At the end of the package, an end-of-package character, such as \f, is required. On the MK side, you need to provide a code that will separate the line. The code you provided does all this, but it doesn't take into account the possible passing of multiple parameters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question