Wei Chun Wen (Wei Chun)
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    <iframe src="https://catdogbird3.github.io/Ring-Buffer-Teaching/" frameborder="1" height="1000"> 嵌入式通訊協議完整入門指南 </iframe> # 嵌入式通訊協議完整入門指南 (含封包格式、常見問題與實務解法) 本篇從嵌入式資料流的整體架構開始,完整說明 **Ring Buffer、UART、I2C、SPI、I2S、USB** 的: * 資料框架(Frame / 封包結構) * 實務常見問題 * 工程解決方式 * 排錯思維 目標是建立「完整系統觀」,而不是只記規格。 --- # 一、嵌入式資料流的全貌 在嵌入式系統中,資料通常遵循這條路徑: ``` 外部設備 → 通訊協議 → MCU 周邊硬體 → ISR / DMA → Buffer → 主程式邏輯 ``` 關鍵分工: * **通訊協議**:負責資料搬運 * **Buffer(通常是 Ring Buffer)**:負責暫存與解耦 * **主程式 / Task**:負責解析與邏輯處理 理解這個資料流,是排錯的基礎。 --- # 二、Ring Buffer(環形緩衝區) ## 1. 結構 核心變數: ``` writeIdx readIdx count ``` 基本操作: ```c buffer[writeIdx] = data; writeIdx = (writeIdx + 1) % SIZE; count++; ``` ```c data = buffer[readIdx]; readIdx = (readIdx + 1) % SIZE; count--; ``` --- ## 2. 使用目的 * ISR 不做重運算 * 解決資料流速度不一致 * 固定記憶體使用 * O(1) 操作效率 --- ## 3. 常見問題 ### Overflow * ISR 推資料太快 * 主程式消費太慢 **解法** * 使用 DMA * 擴大 buffer * Flow control --- # 三、UART ## 1. UART Frame(以 8N1 為例) <div style="text-align: center;"><img src="https://makerpro.cc/wp-content/uploads/2019/12/UART2.png"></div> ``` Idle(1) | Start(0) | D0 D1 D2 D3 D4 D5 D6 D7 | Stop(1) ``` * LSB first * 無時鐘線(非同步) --- ## 2. 封包設計(UART 無天然封包) 常見自訂格式: ``` [SOF][LEN][PAYLOAD][CRC] ``` 或 ``` 固定長度封包 ``` --- ## 3. 常見問題 ### 資料亂碼 原因: * 鮑率誤差 * Parity / Stop 不一致 * 時鐘誤差 解法: * 量測 bit time * 使用外部晶振 * 降低鮑率 --- ### 資料遺失 原因: * Overrun * ISR 太慢 解法: * ISR 只推入 Ring Buffer * 使用 DMA --- ### 黏包 / 切包錯誤 解法: * 使用長度欄位 * 使用分隔符 * 使用 CRC 驗證 --- # 四、I2C <div style="text-align: center;"><img src="https://makeryan.wordpress.com/wp-content/uploads/2017/04/e89ea2e5b995e5bfabe785a7-2017-04-30-e4b88be58d8811-31-14.png?w=365&h=192"></div> ## 1. I2C 基本框架 ### Write ``` S | Addr + W | ACK | Data | ACK | P ``` ### Read ``` S | Addr + W | ACK | Reg | ACK Sr | Addr + R | ACK | Data | NACK | P ``` --- ## 2. 特性 * 兩條線:SCL / SDA * 同步 * 多從設備 * 每 byte 都有 ACK --- ## 3. 常見問題 ### Bus 卡死(SDA stuck low) 原因: * Slave reset 中斷傳輸 * Stop 未送出 解法: * 手動 toggle SCL 9 次 * 重新送 Stop * 初始化時做 bus clear --- ### NACK 原因: * 位址錯誤(7-bit / 8-bit 混淆) * 上電延遲不足 * Pull-up 不正確 解法: * 確認位址格式 * 加上電延遲 * 檢查阻值 --- ### 雜訊導致錯誤 解法: * 降速 * 加 CRC * 強化佈線 --- # 五、SPI <div style="text-align: center;"><img src="https://hackmd.io/_uploads/rJRUFZBFbl.png"></div> ## 1. SPI 交易結構 SPI 沒有固定封包,通常由協議定義: ``` CS low [CMD][ADDR][DATA...] CS high ``` --- ## 2. 關鍵設定 * CPOL * CPHA * Bit order * Clock speed --- ## 3. 常見問題 ### 全 0xFF / 0x00 原因: * SPI mode 錯 * CS 時序錯 * MISO 浮動 解法: * 確認 Mode 0/3 * 確保 CS 包住整段傳輸 * 檢查 MISO tri-state --- ### 資料位移錯誤 原因: * 時鐘太快 * setup/hold 不足 解法: * 降頻 * 加 series resistor --- # 六、I2S(數位音訊) ## 1. I2S Frame 訊號: * BCLK * LRCLK(左右聲道) * SD 典型: ``` LRCLK=0 → Left channel LRCLK=1 → Right channel ``` MSB first I2S 標準:資料延遲 1 bit --- ## 2. 常見問題 ### 左右聲道錯誤 原因: * WS 極性錯 * 格式錯(I2S vs Left-Justified) 解法: * 對照 datasheet * 用固定音訊測試 --- ### 爆音 / 斷音 原因: * DMA underflow * 時鐘不穩 解法: * 使用 double buffer * 提升任務優先權 --- # 七、USB ## 1. USB 分層 USB 通訊結構: ``` Transaction → Transfer → Endpoint ``` --- ## 2. Transaction 結構 ``` Token | Data | Handshake ``` * IN / OUT / SETUP * DATA0 / DATA1 * ACK / NAK / STALL --- ## 3. Control Transfer 三階段: 1. Setup 2. Data 3. Status Setup Packet 8 bytes: ``` bmRequestType bRequest wValue wIndex wLength ``` --- ## 4. 常見問題 ### 無法 Enumerate 原因: * 描述符錯 * EP0 處理錯 * 硬體 pull-up 問題 解法: * 從最小描述符開始 * 用 USB analyzer 檢查 * 確認 SET_ADDRESS 處理正確 --- ### 傳輸不穩 原因: * NAK 過多 * buffer 太小 解法: * 使用 double buffer * 正確選 transfer type(Bulk / Interrupt / Iso) --- # 八、自訂封包設計建議 建議格式: ``` [SOF][VER][TYPE][LEN][PAYLOAD][CRC] ``` 設計原則: * SOF 用特殊值 * LEN 避免黏包 * CRC 防干擾 * Sequence number 可重送 --- # 九、排錯思維模型 遇到問題時,按層檢查: 1. 硬體層(線 / 電壓 / 接地) 2. 時序層(Clock / Mode / 極性) 3. 協議層(封包格式 / ACK) 4. 緩衝層(Overflow / Underflow) 5. 應用層(解析邏輯) --- # 十、協議選擇總結 | 協議 | 線數 | 同步 | 速度 | 用途 | | ---- | -- | --- | -- | --------------- | | UART | 2 | 非同步 | 低 | Debug / 模組 | | I2C | 2 | 同步 | 中 | 感測器 | | SPI | 4+ | 同步 | 高 | Flash / Display | | I2S | 3 | 同步 | 中 | 音訊 | | USB | 4 | 同步 | 極高 | 外部設備 | --- # 核心結論 1. 通訊協議只是資料搬運工具 2. Buffer 是穩定系統的關鍵 3. 封包設計決定系統可靠性 4. 多數問題來自時序與硬體層 5. 排錯要分層思考 掌握這些觀念後,任何新協議(CAN、Ethernet、BLE、RS485)都能用相同思維拆解。 --- 如果需要,我可以再幫你補: * DMA + Ring Buffer + 協議整合實戰架構圖 * RTOS 架構下的通訊設計 * 面試強化版本(工程師答題邏輯) * 或做成完整教學投影片架構 你想往哪個方向進階?

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully