Home > Software design >  Arduino: Int to byte array
Arduino: Int to byte array

Time:11-13

I want to send an integer (total count of packets) over lora. I want to use the first 10 bytes to store this integer. So for 522, first 3 bytes of the total 10 would be 53, 50 and 50. Followed by 7 zeroes. After this, I would have bytes representing my payload.

On the orther end, I would read the first 10 bytes and get the packet count that I need.

I've read a lot of posts but I can't understand how to cast an integer to byte array, if possible. I am sure there is a way more elegant way to solve this.

void sendMessage(byte payload[], int length) {  
  int iPt = 552;
  String sPt = String(iPt);
  byte aPt[10];
  sPt.toCharArray(aPt, 10);
  LoRa.beginPacket();   
  LoRa.write(aPt,10);
  LoRa.write(payload, length);
  LoRa.endPacket();  
}

What I'd like to get on the receiving end is: 53 50 50 0 0 0 0 0 0 0.

What I am getting is 53 50 50 0 (I guess this 0 is the null termination?)

I appreciate any help. Thanks!

CodePudding user response:

There is no need to covert an int to String and then convert it back to char[].

An int (in Arduino) is 16-bit or 2 bytes data, you can send it in two bytes.

int iPt = 552;

LoRa.beginPacket();   
LoRa.write((uint8_t) iPt >> 8);    // shift the int right by 8 bits, and send as the higher byte
LoRa.write((uint8_t) iPt && 0xFF); // mask out the higher byte and cast it to a byte and send as the lower byte
LoRa.endPacket();

For those who are not familiar with the shiftRight operator, Arduino has two helper functions (highByte() and lowByte()) for beginners or those not familiar with bit manipulation.

int iPt = 552;

LoRa.beginPacket();   
LoRa.write(highByte(iPt)); // send higher byte
LoRa.write(lowByte(iPt);   // send lower byte
LoRa.endPacket();

Both codes are the same, the second one with more abstraction and beginner friendly.

  • Related