Converting strings to buffer

How can I send a string to i2c? I found a send buffer https://makecode.microbit.org/reference/pins/i2c-write-buffer

But how to convert a text string to a buffer?

2 Likes

Hi, Gus!

My interpretation is that you’d have to write to the buffer one character at a time, converting the characters to integers using something like string.charCodeAt(i).

As a professional programmer, I can do that. But this is a difficult one for teachers and students.

I am surprised to see buffer to string API but not the other way.

I will post an issue in GitHub

It looks like we have a gap in our documentation. Buffer has a static method called fromUTF8 that does this.

function stringToBuffer(str: string): Buffer {
    return Buffer.fromUTF8(str);
}

Here is a small example, exposing the function as a block in the Text category:

image

2 Likes