Search code examples
arduinoesp32

Read Array of Unsigned Long from the hardware serial?


I got an array of unsigned longs

unsigned long readings[ 64 ];

which I would like to fill from the hardware Serial interface. Anyway there is no function to read directly unsigned long from it.

  • How to fill the array from the serial ?

Solution

  • If you get something over serial its ASCII characters so you convert chunks of chars to what ever format you need:

     unsigned long my_long = 0;
     char inputChunk[] ="2273543"; // you fill that from serial
     my_long = strtoul(inputChunk, NULL, 10);
     Serial.print(my_long);
    readings[0] = my_long;
    

    As you gave no example how the data comes over serial or how to differentiate between different junks (is it '\n' or some other terminator) thats just a basic howto for ASCII.
    As you experiment with '\n' and ASCII here an example:

     unsigned long my_long = 0;
     char inputChunk[16] = {'\0'}; // size big enough you fill that from serial
    
    uint8_t strIndex = 0;
    uint8_t longCounter = 0;
    while (Serial.available())  {
     char readChar = Serial.read();
     if (readChar == '\n') {
        my_long = strtoul(inputChunk, NULL, 10);
        break;
     }
     else {
        inputChunk[strIndex] = readChar;
        strIndex++;
        inputChunk[strIndex] = '\0]; // Keep the array NULL-terminated
     }
     Serial.print(my_long);
     readings[longCounter] = my_long;
     longCounter++;
     if (longCounter>=64) Serial.print("readings[] is full")
    }