kelp99
kelp99

Reputation: 69

What is the difference between Serial and Stream on the Arduino, and how is Serial.write implemented?

I'm having a lot of trouble understanding the difference between the terms Serial and Stream. Is Serial not a type of Stream?

I have questions on homework that I just don't understand.

Computers "read" the data they send each other by using (Streams or Serial?) to determine what each byte means?

Also, Serial.write() confuses me a lot too. It returns a byte of data, correct? A byte is 8 bits. So if an int type (16-bits) is passed to Serial.write() on the Arduino, it would return 2 bytes to the serial stream?

Similarly, if a variable is an unsigned long in Arduino C, how can we represent the most significant byte of this variable to the serial stream using Serial.write()?

For example, I have variable x as the unsigned long. Would Serial.write(x>>8) be the correct answer, because a long is 32 bits so unsigned makes it twice as big. Since Serial.write() returns in bytes, 64/8 would be 8.

All of these questions may seem really amateur, but I really want to learn this stuff and my teacher is not the best at explaining. If anyone can make this more clear conceptually, I will be eternally grateful. Thank you!

Upvotes: 2

Views: 4233

Answers (1)

Delta_G
Delta_G

Reputation: 3243

Stream is the base class that Serial inherits. Serial is a type of Stream but there are other types of Stream as well.

write is different from print in one important way: write sends things as raw bytes and print sends things as ASCII. So, if I Serial.print(255), the Arduino will actually send out 3 bytes, the ASCII codes for all three digits. However, if I Serial.write(255) then the Arduino will send out one single byte with the value of 255 (0b11111111).

The number that write returns is the number of bytes that were written. It returns to the caller, not the serial stream. It tells the caller how many bytes got written.

For example, I have a variable x as the unsigned long. Would Serial.write(x>>8) be the correct answer, because a long is 32 bits so unsigned makes it twice as big. Since Serial.write() returns in bytes, 64/8 would be 8

You have some very fundamental misunderstandings here. The unsigned version is the same 32 bits as the signed version. It can hold a number twice as big because it doesn't need a sign bit, but it's got the same number of bits. To leave the MSB of a 32 bit quantity you need to shift right by 24 bits. Bitshifts are in bits, not bytes, so myLong >> 24.

Upvotes: 6

Related Questions