0

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!

2
  • how are you getting 53 50 50 0? Commented Nov 12, 2022 at 2:59
  • because you use 10 and not the true length of the string in write Commented Nov 12, 2022 at 10:20

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This was really helpful. As a note, I used the following code to recontruct the data on the other side: int bTi = lB | hB << 8; Where lB and hB are lowByte and highByte respectively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.