I am sure this is a very simple answer, but I don't know to look it up on google

In the example "SerialEvent" in the arduino IDE (v1.8.7), there is the following function

    void serialEvent() {
        while (Serial.available()) {
           // get the new byte:
           char inChar = (char)Serial.read();
           // add it to the inputString:
           inputString += inChar;
           // if the incoming character is a newline, set a flag so the main loop can
           // do something about it:
           if (inChar == '\n') {
               stringComplete = true;

On the third line "char inChar = (char)Serial.read();" the (char) is given in brackets before the serial read. Why is this? and more specifically how is called ?


It is called type casting and will convert one type to another. The return type of Serial.read() is int, because it will return -1, when you try to read without any bytes being available. The casting with (char) will drop the high byte of the (2-byte long) integer, leaving only the lower byte. This byte will contain the actual read data, in which you are interested here.

Casting is a complex thing, because there can be different ways to convert different types (for example maintaining the bit-content vs. maintaining the decimal value). The casting, that you are seeing here, should only be done, if you really know, what you are doing. The bits will not be changed to maintain the correct value, but the bit-content will be preserved, unless the new type is smaller than the former. In this case the rest is lost. Also, if you try to cast a float value to an int value with this, you will get a totally different decimal value out of it, because the numbers are encoded in the bits in a totally different way. Here it is known to be OK, especially, if you are checking for available bytes before reading with Serial.available(), because the library puts the ASCII data in the lower byte.

For further explanations you should consult C/C++ guides.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.