MKRWAN.h sending a byte to TTS

I use the Arduino MKR WAN 1310 to send messages to The Things Stack. All the examples of the MKRWAN.h are referring only to sending strings. This works fine. I’d like to send a byte though, so I changed the code slightly.

  // Define an array with a byte
  uint8_t msg[1];
  byte var = 143;
  msg[0] = var;


  // Send the the message
  int err;
  modem.beginPacket();
  modem.print(msg[0]);
  err = modem.endPacket(true);

  // Check if the message has been sent correctly
  if (err > 0) {
    Serial.println("Message sent correctly!");
  } else {
    Serial.println("Error sending message :(");
  }

The message is being sent correctly to the TTS, but as it seems as a string. In TTS the string formater gives me the correct result of “143” as a string.

function Decoder(bytes, port) {
 var result = ""; 
 for (var i = 0; i < bytes.length; i++) { 
   result += String.fromCharCode(parseInt(bytes[i])); 
 } 
 return { payload: result, };
}

A formater for bytes gives me not a result of 143 but of 49.

function Decoder(bytes, port) {
	var decoded_var = bytes[0];
	
	return {
	var: decoded_var
	}
}

Is the MKRWAN.h designed only to send strings to the TTS?

I think, I found a solution to this problem. The MKRWAN.h library has two methods for sending data:

  • print() - is for strings
  • write() - is for bytes

So, if you want to send one byte, the relevant code is:

  // Define an array with a byte DEC=143, HEX=8F
  uint8_t payload[1];
  byte var = 143;
  payload[0] = var;

  // Send the payload
  int err;
  modem.beginPacket();
  modem.write(payload[0]);
  err = modem.endPacket(true);

The TTN formatter for this payload is:

function Decoder(bytes, port) {
	var decoded_var = bytes[0];
	
	return {
	var: decoded_var
	}
}

If you want to send and integer, the relevant code is:

  // Define an array with an integer DEC = 12450, HEX = 30 A2
  uint8_t payload[2];
  int var = 12450;
  payload[0] = var >> 8;
  payload[1] = var;

  // Send the payload
  int err;
  modem.beginPacket();
  modem.write(payload, 2);
  err = modem.endPacket(true);

The TTN formatter for this payload is:

function Decoder(bytes, port) {
  var decoded_var = bytes[0] << 8 | bytes[1];
  
  return {
  var: decoded_var
  }
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.