Arduino中Serial与Stream的区别及Serial.write实现原理问询
Answers to Your Arduino Serial/Stream Questions
Great questions—let’s break these down clearly so you can wrap your head around them!
1. Serial vs Stream: What’s the Difference, and How Does Data Get Parsed?
First off, yes—Serial is absolutely a type of Stream in Arduino. Here’s the breakdown:
Streamis an abstract base class in the Arduino core. It defines a common set of methods for working with data streams (likeread(),available(),find(),parseInt()), but it doesn’t handle any actual hardware communication on its own. Think of it as a blueprint for "how to interact with a stream of data."Serialis a concrete subclass ofStreambuilt specifically for UART serial communication (the physical RX/TX pins on your Arduino). It implements all the abstract methods fromStreamusing the board’s UART hardware, so you can send/receive bytes over the serial port while using the familiar Stream interface.
As for parsing data between Arduino and computer:
- The Arduino uses
Serial(which leverages the Stream interface) to send raw bytes over the UART hardware. - On the computer side, your serial monitor or custom program doesn’t care about Arduino’s
Streamabstraction—it just receives the raw bytes transmitted over the serial port. The computer parses those bytes directly (you might convert them to strings, integers, etc., depending on your code), not via the Arduino’s Stream class.
2. How Does Serial.write() Work with 16-bit int Values?
Let’s get into the nitty-gritty of this function’s behavior:
Serial.write()has several overloaded versions, but there’s no direct overload for 16-bitintvalues. When you pass a 16-bitinttoSerial.write(), it gets implicitly cast to an 8-bituint8_t(unsigned byte). That means only the lower 8 bits of your int get sent, and the function will return1(the number of bytes transmitted).- If you want to send both bytes of a 16-bit int, you need to split it manually. For example:
int myInt = 0xABCD; // 16-bit value // Send high byte first Serial.write((uint8_t)(myInt >> 8)); // Sends 0xAB, returns 1 // Send low byte Serial.write((uint8_t)myInt); // Sends 0xCD, returns 1 - Under the hood,
Serial.write()ultimately calls hardware-specific functions to push bytes into the UART transmit buffer. The exact implementation varies slightly between Arduino boards (like AVR vs. ESP32), but the core behavior of truncating non-8-bit values holds true across most platforms.
内容的提问来源于stack exchange,提问作者kelp99
相关产品推荐
相关产品推荐

