Looking to insert a hexadecimal value into an array in order to write to a device via modbus/TCP using socket communication.
Currently facing an issue where I am unable to retrieve the hex
value with the same data type as the elements present in byteArrayWriteTemperature
.
After calculating the crc
for preparing the array to be sent, it is necessary to add this crc
at the end of the array.
For instance, if value = 45
, my resulting array would look like:
array = [0x01, 0x10, 0x04, 0x00, 0x00, 0x01, 0x02, 0x00, 0x2d, 0x23, 0x8d]
When using the Crc16()
method on
buff = [0x01, 0x10, 0x04, 0x00, 0x00, 0x01, 0x02, 0x00, 0x2d]
where the last element is 0x2d
(equivalent to decimal value `45`), the generated crc result is swapped = 8d23
rather than 238d
as seen in the last 2 elements of array
.
setTemperature(value: number) {
console.log('about to set temperature value ', value);
let hex = value.toString(16)
const byteArrayWriteTemperature = [0x01, 0x10, 0x04, 0x00, 0x00, 0x01, 0x02, 0x00, hex];
let crc = this.Crc16(byteArrayWriteTemperature, byteArrayWriteTemperature.length)
console.log('crc ', crc)
console.log('array: ', byteArrayWriteTemperature);
this.writeToDevice(byteArrayWriteTemperature)
}
Crc16(buff, length) {
let crc = 0xffff;
for (let pos = 0; pos < length; pos++) {
crc ^= buff[pos]; // (uint8_t) // XOR byte into least sig. byte of crc
for (let i = 8; i != 0; i--) {
// Loop over each bit
if ((crc & 0x0001) != 0) {
// If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xa001;
} else {
crc >>= 1; // Just shift right
} // Else LSB is not set
}
}
return crc;
}
Seeking guidance on how to properly format my array. Thank you