Newbie with a question about Serial.write() and Serial.read()

Hi,

I'm working on a project which requires communication with a game I'm making. But I'm a little confused about how this communication works.

I understand that Serial.read() reads bytes from a stream. I'm guessing this "stream" is like a queue of data? If there's nothing left in the queue then it returns -1? Is that correct?

But what about Serial.write()? If I were to write something, then read directly after, wouldn't it just give the value of whatever I just wrote? Or am I interpreting this wrong? Are the write streams and the read steams two separate things?

Sorry if my terminology is wrong.

PlasmaticNinja: I understand that Serial.read() reads bytes from a stream. I'm guessing this "stream" is like a queue of data? If there's nothing left in the queue then it returns -1? Is that correct?

It's a buffered stream, but other than that, you are correct.

PlasmaticNinja: But what about Serial.write()? If I were to write something, then read directly after, wouldn't it just give the value of whatever I just wrote? Or am I interpreting this wrong? Are the write streams and the read steams two separate things?

They are separate streams: Serial.read() looks at the next byte in the RX buffer while Serial.write() sends a byte on the TX wire to whatever device(s) is(are) connected to it.

Here is a good tutorial to learn about serial comms. That being said, it's probably better for you to use a tested library to make transferring data easy.

In UART based serial communication, these two methods: Serial.read() and Serial.write() are used to exchange data with the remote devices.

1. When a data byte (technically – a 10-bit wide asynchronous frame) arrives to the Arduino UNO, it is automatically saved (in the background through interrupt process and beyond the knowledge of the user) into an unseen FIFO (first-in first-out) Buffer. The user first checks if the Buffer has accumulated any data byte, and then he executes this code: char x = Serial.read() to bring the arrived data byte from the Buffer into user variable x.

byte n = Serial.available();  //checking if Buffer contains at least 1-byte data
if (n !=0 )
{
    char x = Serial.read();
}

2. When we have a data byte (say: 0x35) to transfer via Transmit Section (TX) of UART Port, we execute this code: Serial.write(0x35); as a result, the data byte enters into a FIFO Buffer (different buffer from Step-1); the Buffer interrupts the MCU; the MCU reads the data byte from the Buffer, convert it into an async frame, and then puts onto actual TX Register/Section. The process continues until all the data bytes (in case of multi bytes data: Serial.write(myData, sizeof myData)) of the Buffer get written onto TX Register.

Power_Broker: Here is a good tutorial to learn about serial comms. That being said, it's probably better for you to use a tested library to make transferring data easy.

This helped a lot, thank you.