Ross M.
Ross M.

Reputation: 313

Arduino int to String conversion

I have this code:

String c = String(BTLEserial.read());
char relevant = c.charAt(0);
Serial.println(relevant);

where BTLEserial.read() returns type Int. I'm converting that to a String, in the first line so that I can use the charAt function on it in the next.

When I send my Bluetooth "0000", my println(relevant) prints 4.

I made a test println() statement to print the value of c, and found that its value when BTLEserial.read() is 0000 turns out to be 48. This tells me that I have a conversion problem, when I change the Int value BTLEserial.read() to a string, c.

What's happening here, and what's the right way to convert BTLEserial.read() to type String?

Upvotes: 2

Views: 3100

Answers (2)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

I made a test println() statement to print the value of c, and found that its value when BTLEserial.read() is 0000 turns out to be 48.

Hardly surprising. The ASCII value of "0" is 48.

The "int" that Adafruit_BLE_UART::read() returns is the most recent byte received; if you want to receive multiple bytes, e.g. the string "0000", then you will need to call it multiple times, adding the character to a buffer each time.

Upvotes: 1

xtofl
xtofl

Reputation: 41509

Could it be that the first character of your String object is at index 0? So actually, you're reading one character behind your string (It doesn't contain a null character as for the docs).

A convenient String implementation should throw an exception or at least warn you that you're reading out of bounds. But on Arduino you need to verify your bounds-check yourself (hey, it's embedded).

Upvotes: 0

Related Questions