Yordan Yanakiev
Yordan Yanakiev

Reputation: 2604

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.

Upvotes: 0

Views: 376

Answers (2)

Quinn Carver
Quinn Carver

Reputation: 605

I like to use unions for this, saves you from a lot of nasty casting.

union{
   uint8_t asBytes[SERIAL_ARRAY_LEN];
   unsigned long asULongs[SERIAL_ARRAY_LEN/sizeof(unsigned long)];
}data;

//use memcpy, or you could for while through and transfer byte by byte;
memcpy(sizeof(SERIAL_ARRAY_LEN, data.asBytes, serialBuffer);

for (int i = 0; i < SERIAL_ARRAY_LEN/sizeof(unsigned long); i++){
   ESP_LOGD(TAG, "%d", data.asULongs[i]);
}

Upvotes: 1

Codebreaker007
Codebreaker007

Reputation: 2989

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")
}

Upvotes: 0

Related Questions