# Serial sending unexpected values

**URL:** <https://discourse.processing.org/t/serial-sending-unexpected-values/36412>\
**Category:** Electronics (Arduino, etc.)\
**Created:** [April 18, 2022, 12:05pm UTC](https://discourse.processing.org/t/serial-sending-unexpected-values/36412 "2022-04-18T12:05:06Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Smajdalf](https://avatars.discourse-cdn.com/v4/letter/s/c67d28/32.png) [@Smajdalf](https://discourse.processing.org/u/Smajdalf)\
**Post date:** [April 18, 2022, 12:05pm UTC](https://discourse.processing.org/t/serial-sending-unexpected-values/36412/1 "2022-04-18T12:05:06Z")

</div>

I encountered another problem when communicating with Arduino. I want to send raw data. On the Processing side I prepare them as a String and send them to Arduino via Serial. Using

```auto
void writeToArduino(String whatToWrite) {
  Arduino.write(whatToWrite);
}

```

mangles the data for some reasons. For example it always sends 0x3F instead of 0xFF. But other chars are sent correctly. To get correct data I need to do

```auto
void writeToArduino(String whatToWrite) {
  for (int i=0; i<whatToWrite.length(); i++) Arduino.write(whatToWrite.charAt(i));
}

```

Why? String is not “an array of chars?”

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [April 18, 2022, 1:20pm UTC](https://discourse.processing.org/t/serial-sending-unexpected-values/36412/2 "2022-04-18T13:20:45Z")

</div>

> [@Smajdalf](#):
>
> Why? String is not “an array of chars?”

A `char` primitive type in Java is an unsigned value of 16 bits (2 bytes):

> **[char / Reference](https://processing.org/reference/char.html)**
>
> Datatype for characters, typographic symbols such as A, d, and $. A char stores letters and symbols in the Unicode format, a coding system developed to support a variety of world languages. Eac…

So a String of **length()** 10 is actually 20 bytes for most cases.

> [@Smajdalf](#):
>
> ```auto
> void writeToArduino(String whatToWrite) {
> for (int i=0; i<whatToWrite.length(); i++) Arduino.write(whatToWrite.charAt(i));
> }
> 
> ```

A shorter workaround is call method String::**getBytes()**:  
[docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#getBytes()](http://docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#getBytes())

```auto
void writeToArduino(String whatToWrite) {
  Arduino.write(whatToWrite.getBytes());
}

```
