Return as char

Hello,

I'm trying to echo the input to the serial monitor. It returns as Dec, so it doesn't echo. But i want it to return as character. I try the code below but it doesn't work. The error is at : Serial.println(val, char);. Where am i wrong?

Thnx,

void setup(){
  
  Serial.begin(9600);
}

void loop(){

        if (Serial.available() > 0) {
  
                    int val= Serial.read();
  
                    Serial.println(val, char);
  
                    }
    
}

I use Serial.write() and the lowByte function to get the low byte of an int.

Serial.write(lowByte(val));

easiest is to cast the int to a char - casting is an explicit conversion command for the compiler

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  if (Serial.available() > 0)
  {
    int val= Serial.read();
    Serial.println((char)val);  // you neeed to cast 
  }
}

thanks both of you! it works now. but what is the real difference between Serial.print and Serial.write in this case?

And if i want to echo a string like "Hello Mars!", what should i use?

For a string or character array, use Serial.print() or Serial.println(). Serial.write() sends a character (byte), and does no skinware conversion. It sends it as-is, so it is a bit faster.

thanks both of you! it works now. but what is the real difference between Serial.print and Setrial.write in this case?

And if i want to echo a string like "Hello Mars!", what should i use?

Think you should spend some time to go through the tutorial section,- http://arduino.cc/en/Tutorial/HomePage - you will pick up many code snippets there how things are done. Time spend there is definitely worth it Also the reference section is full of small code snippets. - http://arduino.cc/en/Reference/HomePage -

But feel free to ask if you don't understand an example!

An understanding of serial communications is very important. The Serial.read() function returns one byte/char at a time. The function would have byte as a return type if there was another mechanism to convey the error that arises when trying to read data that is not there. Because this problem can arise, and is so frequent, the Serial.read() function must return an int, since all possible values that can fit in a byte are possible legal return values.

If you are careful to always call Serial.available() before calling Serial.read(), you can store the returned value in a char, instead of an int. That convinces Serial.print() to handle the printing of the character correctly.

Storing the return value as a char also makes appending the character to a char array a lot easier.