You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  • Stream is an abstract base class in the Arduino core. It defines a common set of methods for working with data streams (like read(), 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."
  • Serial is a concrete subclass of Stream built specifically for UART serial communication (the physical RX/TX pins on your Arduino). It implements all the abstract methods from Stream using 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 Stream abstraction—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-bit int values. When you pass a 16-bit int to Serial.write(), it gets implicitly cast to an 8-bit uint8_t (unsigned byte). That means only the lower 8 bits of your int get sent, and the function will return 1 (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:52:09