Using Byte......

Hi All need a small help........ :slight_smile:

As per Arduino reference,Byte is a memory location of 8bits and it can take values ranging 0-255.
Qn 1 I tried to give character value to a byte variable (eg byte val='a':wink: and print it using Serial.print(val);, I was able to print the value as "a"; but when I tried to give a integer value to the byte variable(byte val=20;) I was not able to print it using the statement Serial.print(val). Instead of that I have to use the statement Serial.print(val, DEC) why is this so?
Qn2: Is there a way I can store value in an integer variable (eg int n=65;) and print the character 'a'(since ASCII 65= character a) using the integer variable n with the help of Serial.print(n);

Read this before posting a programming question

Your code?

byte val=20;
void setup()
{
Serial.begin(9600);

}
void loop()
{
Serial.println(val);
delay(500);
}

The above code is not working for integer, but if the global variable is byte val='a', then it's working.

if i replace the Serial.println(val) with Serial.println(val,DEC) then it's working.

Can you please tell me the reason? .... :slight_smile:

Ascii character 20 is not printable, try setting val to something larger - 65 for example.

As per Arduino reference,Byte is a memory location of 8bits and it can take values ranging 0-255.

Reference? I don't believe that Byte is defined anywhere in the Arduino documentation. byte, yes. Byte, no.

Qn2: Is there a way I can store value in an integer variable (eg int n=65;) and print the character 'a'(since ASCII 65= character a) using the integer variable n with the help of Serial.print(n);

If the values you want to store represent characters, why do you want to waste the extra byte storing them in ints, instead of bytes?

aruns06:
Hi All need a small help........ :slight_smile:

As per Arduino reference,Byte is a memory location of 8bits and it can take values ranging 0-255.
Qn 1 I tried to give character value to a byte variable (eg byte val='a':wink: and print it using Serial.print(val);, I was able to print the value as "a"; but when I tried to give a integer value to the byte variable(byte val=20;) I was not able to print it using the statement Serial.print(val). Instead of that I have to use the statement Serial.print(val, DEC) why is this so?
Qn2: Is there a way I can store value in an integer variable (eg int n=65;) and print the character 'a'(since ASCII 65= character a) using the integer variable n with the help of Serial.print(n);

byte is a datatype - it is an unsigned 8 bit value, so when such a value is stored in memory it takes a byte, but a value doesn't always get to memory (intermediate results for instance).

Casts enable one value to be treated as if a different type. For instance:

  print ((char) n) ;

will treat the value of n as a char (shortening it to 8 bits in the process, but not affecting the original variable n).