How should I write a byte array representing RGB values in JavaScript?

782 views Asked by At

I've been working on a React Native app that is using the react-native-ble-manager package. We're trying to write a RGB value to a LED light strip, but we're having issues finding the correct way to format a byte array with RGB values in JavaScript. We were able to get this working in Kotlin by passing this byte array that represents the RGB value of blue:

val payload = byteArrayOf(0x00, 0xff.toByte(), 0x00 )

I've been trying replicate this in Javascript but I've had no luck getting the LED light strip to change colors like it does for Kotlin. This is the JavaScript code for the byte array I'm passing:

const payload = new Uint16Array(3);
payload[0] = 0x00;
payload[1] = 0xff;
payload[2] = 0x00;

Can someone please explain how I should write a byte array representing RGB values in JavaScript, and provide the JavaScript equivalent to Kotlin example above(byteArrayOf(0x00, 0xff.toByte(), 0x00 ))?

1

There are 1 answers

0
PotatoParser On BEST ANSWER

Since RGB values are 1 byte for each color (8 bits), you can use Uint8Array:

function byteArrayOf(r, g, b) {
  let byteArray = new Uint8Array(3);
  byteArray[0] = r;
  byteArray[1] = g;
  byteArray[2] = b;
  return byteArray;
}

console.log(byteArrayOf(0x0, 0xff, 0x0));