HOME
Shop
  • English
  • 简体中文
HOME
Shop
  • English
  • 简体中文
  • Product Series

    • FPGA+ARM

      • GM-3568JHF

        • Introduction

          • GM-3568JHF Introduction
        • Quick Start

          • Preface
          • Environment Setup
          • Compilation Notes
          • Flashing Guide
          • Debugging Tools
          • Software Update
          • Viewing System Information
          • Test Commands
          • Application Compilation
          • Source Code Access
        • Peripherals & Interfaces

          • USB
          • Display and Touch
          • Ethernet
          • WIFI
          • Bluetooth
          • TF-Card
          • Audio
          • Serial Port
          • CAN
          • RTC
        • Application Development

          • UART Read/Write Demo
          • Key Detection Demo
          • LED Blink Demo
          • MIPI Screen Detection Demo
          • Read USB Device Information Demo
          • FAN Detection Demo
          • FPGA FSPI Communication Demo
          • FPGA DMA Read/Write Demo
          • GPS Debugging Demo
          • Ethernet Test Demo
          • RS485 Read/Write Demo
          • FPGA I2C Read/Write Demo
          • PN532 NFC Card-Reading Demo
          • TF Card Read/Write Demo
        • QT Development

          • ARM64 Cross-Compiler Environment Setup
          • Adding a QT Program to Boot Auto-Start
        • RKNN_NPU Development

          • RK3568 NPU Overview
          • Development Environment Setup
          • Run the Official YOLOv5 Example
        • FPGA Development

          • ARM and FPGA Communication
          • FPGA Development Manual
        • Others

          • Modifying the Root Filesystem
          • System Auto-Start Services
        • Downloads

          • Downloads
      • MB-E30P

        • Introduction

          • MB-E30P Introduction
        • Quick Start

          • Preface
          • Environment Setup
          • Compilation Instructions
          • Flashing Guide
          • Debugging Tools
          • Software Update
          • Viewing Information
          • Test Commands
          • Application Compilation
          • Source Code Acquisition
        • Peripherals & Interfaces

          • USB
          • Display and Touch
          • Ethernet
          • WIFI
          • Bluetooth
          • TF-Card
          • Audio
          • RTC
        • Application Development

          • Key Detection Demo
          • LED Blink Demo
          • MIPI Screen Detection Demo
          • Read USB Device Information Demo
          • FAN Detection Demo
          • FPGA FSPI Communication Demo
          • FPGA DMA Read/Write Demo
          • Ethernet Test Demo
          • FPGA IIC Read/Write Demo
          • PN532 NFC Card Reading Demo
          • TF Card Read/Write Demo
        • QT Development

          • ARM64 Cross-Compiler Environment Setup
          • Adding a QT Program to the Boot Auto-Start Service
        • RKNN_NPU Development

          • RK3568 NPU Overview
          • Development Environment Setup
          • Run the Official YOLOv5 Example
          • Model Conversion In Detail
          • Run Custom Models on the Board
        • FPGA Development

          • ARM and FPGA Communication
          • FPGA Development Manual
        • Others

          • Modifying the Root Filesystem
          • System Auto-Start Service
        • Downloads

          • Downloads
    • ShimetaPi

      • M4-R1

        • Introduction

          • M4-R1 Introduction
        • Quick Start

          • OpenHarmony Overview
          • Image Burning
          • Application Development Quick Start
          • Device Development Quick Start
        • Application Development

          • ArkUI

            • ArkTS Language Overview
            • UI Components - Row Container Introduction
            • UI Components - Column Container Introduction
            • UI Components - Text Component
            • UI Components - Toggle Component
            • UI Components - Slider Component
            • UI Components - Animation Component & Transition Component
          • Documentation

            • OpenHarmony Official Materials
          • Development Notes

            • Full-SDK Replacement Tutorial
            • Introducing and Using Third-Party Libraries
            • HDC Debugging
            • Restore Factory Mode via Command Line
            • Upgrade App to System Permission
          • First App

            • Build Your First ArkTS Application - HelloWorld
          • Demos

            • Serial-Debug-Assistant Application Demo
            • Writing-Board Application Demo
            • Digital Clock Application Demo
            • Wi-Fi Information Acquisition Application Demo
        • Device Development

          • Ubuntu Development

            • Environment Setup
            • Download Source Code
            • Compile Source Code
          • DevEco Device Tool

            • Tool Introduction
            • Development Environment Construction
            • Import the SDK
            • HUAWEI DevEco Tool Function Introduction
        • Kernel Peripherals & Interfaces

          • Guide
          • Device Tree Introduction
          • NAPI Introduction
          • ArkTS Introduction
          • NAPI Development Hands-on Demo
          • GPIO Introduction
          • I2C Communication
          • SPI Communication
          • PWM Control
          • UART Communication
          • TF Card (MicroSD)
          • Screen (Display)
          • Touch
          • Ethernet
          • M.2 SSD
          • Audio
          • WIFI & BT
          • Camera
        • Downloads

          • Downloads
      • M5-R1

        • Introduction

          • M5-R1 Development Docs
        • Quick Start

          • Image Burning
          • Environment Setup
          • Download Source Code
        • Peripherals & Interfaces

          • Raspberry Pi Interfaces
          • GPIO Interface
          • I2C Interface
          • SPI Communication
          • PWM Control
          • Serial Port Communication
          • TF Card
          • Display
          • Touch
          • Audio
          • RTC
          • Ethernet
          • M.2
          • MINI-PCIE
          • Camera
          • WIFI & BT
        • Downloads

          • Downloads
      • Pico-G1

        • Product Overview

          • Product Introduction
          • SDK Version Information
        • Quick Start

          • Development Environment Setup
          • Image Build
          • Image Flashing
          • System Login
          • Network Configuration
          • File Transfer
          • SDK Directory Structure
          • Deploying Your First Application
          • Deploying Your First Driver
          • Mounting an SD Card
        • Peripherals & Interfaces

          • GPIO Control
          • UART Serial Communication
          • I2C Communication
          • SPI Communication
        • MPP Media Development

          • MPP Media Processing Software
          • Image Processing Chain
          • Video Input
          • Image Encoding
        • NPU & AI

          • NPU Driver and Runtime Library Architecture
          • .xmm Model Loading
          • SVP Video Processing
          • AI Noise Reduction (AI_NR)
        • Application Samples

          • Encryption/Decryption Application
          • ADC Acquisition Application
          • Low-Power Application
          • Audio Processing Application
          • Video Encoding Application
          • Video Input Application
          • Video Graphics Subsystem (VGS) Application
          • 08 Region Overlay Application
          • 09 Intelligent Video Engine Application
          • 10 UVC Webcam Application
          • 11 All-in-One Quickstart Application
          • 12 FPN Correction Application
          • 13 Regional Motion Detection Application
          • 14 MTCNN Face Detection Application
        • Expansion Board Peripheral Examples

          • 00 - Pico Expansion Board Peripheral Examples Overview
          • 01 - OLED Display Application
          • 02 - TFT Display Application
          • 03 - MPU6050 Gyroscope Application
          • 04 - ADC Acquisition Application
          • 05 - Passive Buzzer Application
          • 06 - MQ Gas Sensor Application
          • 07 - GPS Positioning Application
          • 08 - SHT20 Temperature & Humidity Application
          • 09 - Ultrasonic Ranging Application
          • 10 - SpO2 Sensor Application
          • 11 - DC Motor Control Application
          • 12 - Servo Control Application
    • OpenHarmony

      • SC-3568HA

        • Introduction

          • SC-3568HA Overview
        • Quick Start Guide

          • OpenHarmony Overview
          • Image Flashing
          • Setting Up the Development Environment
          • Hello World Application and Deployment
        • Application Development

          • ArkUI

            • Introduction to ArkTS Language
            • Introduction to UI Components and Practical Applications (Part 1)
            • Introduction to UI Components and Practical Applications (Part 2)
            • Introduction to UI Components and Practical Applications (Part 3)
          • Expand

            • Getting Started Guide
            • Referencing and Using Third-Party Libraries
            • Application Compilation and Deployment
            • Command-Line Factory Reset
            • System Debugging -- HDC Debugging
            • APP Stability Testing
            • Chapter 7 Application Testing
        • Device Development

          • Environment Setup
          • Download Source Code
          • Compiling Source Code
        • Peripheral And Interface

          • Raspberry Pi interface
          • GPIO Interface
          • I2C Interface
          • SPI communication
          • PWM (Pulse Width Modulation) control
          • Serial port communication
          • TF Card
          • Display Screen
          • Touch
          • Audio
          • RTC
          • Ethernet
          • M.2
          • MINI-PCIE
          • Camera
          • WIFI&BT
          • Raspberry Pi expansion board
        • Downloads

          • Downloads
      • M-K1HSE

        • Introduction

          • M-K1HSE Introduction
        • Quick Start

          • Development environment construction
          • Source code acquisition
          • Compilation Notes
          • Burning Guide
        • Application Development

          • Application Development Environment Setup
          • First Application - Hello World
        • Peripherals and interfaces

          • 01 Audio
          • 02 RS485
          • 03 Display
        • System customization development

          • System transplant
          • System customization
          • Driver Development
          • System Debugging
          • OTA Update
        • Downloads

          • Downloads
    • HVS Camera

      • Quick Start

        • SDK Overview
        • Downloads
        • Your First C++ Program
        • Python Data Analysis
        • MultiVision Studio
      • Development

        • Programming Guides

          • Open Camera
          • Read Events
          • Recording & Replay
          • Event Processing (Denoising)
          • Display & Visualization
          • Tuning
          • Capture APS Image
        • Toolkit SDK

          • Hybrid Vision Toolkit
          • Quick Start
          • C++ API
          • Python API
        • Algorithm

          • Hybrid Vision Algo
          • Hybrid Vision Algo API
          • Windows Algo SDK
        • Samples Overview
        • Applications
      • Fundamentals

        • Event Camera Fundamentals
        • HVS Hybrid Vision
        • Event Visualization
        • Data Formats Reference
        • Glossary
        • Bias & Tuning
        • Video Tutorials
      • USB Cameras

        • HVS Camera Quick Start
        • Networking Capabilities

          • HVS Camera System Architecture
          • EVS Network Server
          • EVS Time Sync
          • Web Window
        • HVS Camera Compatibility Matrix
        • FAQ & Troubleshooting Guide
        • Products

          • CF-NRS1 (Lingguang No.1 Hybrid Vision Camera)
      • MIPI Modules

        • MIPI Module Quick Start
        • Carrier Boards

          • RDK X5 Carrier Board Adaptation
          • Raspberry Pi Carrier Board Adaptation
          • Digua Pi Carrier Board Adaptation
          • ShimeTai Board Carrier Board Adaptation
        • MIPI Module Compatibility Matrix
        • Products

          • EVS_003 Sensor Module
    • AI-model

      • 1684XB-32T

        • Introduction

          • AIBOX-1684XB-32 Introduction
        • Quick Start

          • First Use
          • Network Configuration
          • Disk Usage
          • Memory Allocation
          • Fan Control Strategy
          • Firmware Upgrade
          • Cross Compilation
          • Model Quantization
        • Application Development

          • Development Overview

            • Sophgo SDK Development
            • Sophgo Demo Introduction
          • Large Language Models

            • Deploying Llama3 Example
            • Sophon LLM_api_server Development
            • Deploying MiniCPM-V-2_6
            • Qwen-2-5-VL Image and Video Recognition Demo
            • Qwen3-chat Demo
            • Qwen3-Qwen Agent-MCP Development
            • Qwen3-langchain-AI Agent
          • Deep Learning

            • ResNet (Image Classification)
            • LPRNet (License Plate Recognition)
            • SAM (General Image Segmentation Foundation Model)
            • YOLOv5 (Object Detection)
            • OpenPose (Human Keypoint Detection)
            • PP-OCR (Optical Character Recognition)
        • Downloads

          • Downloads
      • 1684X-416T

        • Introduction

          • AIBOX-1684X-416 Introduction
        • Demo Quick Guide

          • ShimeTai Intelligent Monitoring Demo Quick Usage Guide
      • RDK-X5

        • Introduction

          • RDK-X5 Hardware Introduction
        • Quick Start

          • RDK-X5 Quick Start
        • Application Development

          • AI Online Model Development

            • Experiment 01 - Access Volcengine Doubao AI
            • Experiment 02 - Image Analysis
            • Experiment 03 - Multimodal Visual Analysis & Localization
            • Experiment 04 - Multimodal Image-Text Comparison
            • Experiment 05 - Multimodal Document/Table Analysis
            • Experiment 06 - Camera-based AI Visual Analysis
          • Large Language Models

            • Experiment 01 - Speech Recognition
            • Experiment 02 - Voice Conversation
            • Experiment 03 - Multimodal Image Analysis - Voice
            • Experiment 04 - Multimodal Image Comparison - Voice
            • Experiment 05 - Multimodal Document Analysis - Voice
            • Experiment 06 - Multimodal Vision Application - Voice
          • ROS2 Basics

            • Experiment 01 - Environment Setup
            • Experiment 02 - Create & Build a Workspace Package
            • Experiment 03 - Run ROS2 Topic Communication Node
            • Experiment 04 - ROS2 Camera Application
          • 40-pin IO Development

            • Experiment 01 - GPIO Output (LED Blink)
            • Experiment 02 - GPIO Input
            • Experiment 03 - Button-controlled LED
            • Experiment 04 - PWM Output
            • Experiment 05 - Serial Output
            • Experiment 06 - I2C Experiment
            • Experiment 07 - SPI Experiment
          • USB Module Usage

            • Experiment 01 - USB Voice Module Usage
            • Experiment 02 - Sound Source Localization Module
          • Machine Vision Practice

            • Experiment 01 - Open USB Camera
            • Experiment 02 - Color Recognition
            • Experiment 03 - Gesture Recognition
            • Experiment 04 - YOLOv5 Object Detection
      • RDK-S100

        • Introduction

          • RDK-S100 Hardware Introduction
        • Quick Start

          • RDK-S100 Quick Start
        • Application Development

          • AI Online Model Development

            • Experiment 01 - Access Volcengine Doubao AI
            • Experiment 02 - Image Analysis
            • Experiment 03 - Multimodal Visual Analysis & Localization
            • Experiment 04 - Multimodal Image-Text Comparison
            • Experiment 05 - Multimodal Document/Table Analysis
            • Experiment 06 - Camera-based AI Visual Analysis
          • Large Language Models

            • Experiment 01 - Speech Recognition
            • Experiment 02 - Voice Conversation
            • Experiment 03 - Multimodal Image Analysis - Voice
            • Experiment 04 - Multimodal Image Comparison - Voice
            • Experiment 05 - Multimodal Document Analysis - Voice
            • Experiment 06 - Multimodal Vision Application - Voice
          • ROS2 Basics

            • Experiment 01 - Environment Setup
            • Experiment 02 - Create & Build a Workspace Package
            • Experiment 03 - Run ROS2 Topic Communication Node
            • Experiment 04 - ROS2 Camera Application
          • 40-pin IO Development

            • Experiment 01 - GPIO Output (LED Blink)
            • Experiment 02 - GPIO Input
            • Experiment 03 - Button-controlled LED
            • Experiment 04 - PWM Output
            • Experiment 05 - Serial Output
            • Experiment 06 - I2C Experiment
            • Experiment 07 - SPI Experiment
          • USB Module Usage

            • Experiment 01 - USB Voice Module Usage
            • Experiment 02 - Sound Source Localization Module
          • Machine Vision Practice

            • Experiment 01 - Open USB Camera
            • Experiment 02 - Image Processing Basics
            • Experiment 03 - Object Detection
            • Experiment 04 - Image Segmentation
      • RK1828

        • Introduction

          • M5-182X-A1 AI Edge Box - Product Introduction
          • M5-182X-A1 Hardware Specifications
          • M5-182X-A1 Usage & Safety
        • Quick Start

          • M5-182X-A1 Image Flashing
          • RK182X Hardware Installation & Verification
          • RK182X Development Environment Quick Setup
          • RK182X SDK Overview
          • RK182X Environment Setup in Detail
          • RK182X Quick Start
          • Vendor SDK Data Extraction Record
        • Development Guide

          • ClawChips Architecture and Principles
          • SKILL User Manual
          • RK182X Series LLM Inference (RK1828 Model)
          • RK182X Series CNN Inference (RK1828 Model)
          • Model Conversion
          • RK182X AI Agent Application Development Guide
          • RK182X Industrial Anomaly Detection Application
        • SDK Reference

          • RKNN3-SDK Overview

            • RKNN3 SDK Overview
          • RKNN3-Toolkit

            • RKNN3 Toolkit Installation and Usage
          • RKLLM

            • RKLLM On-Device LLM Inference
          • RK182X Series NPU Overview and Architecture (RK1828 Model)
          • RK182X INT8 Quantized Inference Deployment
          • RK182X MPP Multimedia Framework
          • MPP Details

            • RK182X Video Decoding
            • RK182X Video Encoding
          • NPU Details

            • RKNN Model Conversion
            • RK182X NPU INT8 Quantized Inference
            • RK182X Multi-Model Parallel Inference
          • RGA Details

            • RK182X RGA 2D Graphics Acceleration
          • VPU Details

            • RK182X VPU Codec
        • Hardware Reference

          • RK182X Series Hardware Architecture Overview (RK1828 Model)
          • RK182X Pin Definitions and Multiplexing Configuration
          • RK182X Pin Definitions
          • RK182X Power Management
          • RK182X Clock and PLL Configuration
          • RK182X Clock and Frequency Configuration
        • Tutorials

          • Hello World
          • Hello RK1828 - The First Program
          • RTSP Streaming
          • RTSP Streaming + AI Analysis
          • ShiMetaPi AI Lobster One-Click Deployment
          • PaddleOCR-VL Text Recognition
          • Qwen3-1.7B LLM Text Chat
          • AI Multi-View Inspection (Qwen3-VL Wrapper)
          • YOLOv5 Object Detection
        • Downloads

          • Downloads
        • FAQ

          • FAQ
    • Core-Board

      • C-3568BQ

        • Introduction

          • C-3568BQ Overview
      • C-3588LQ

        • Introduction

          • C-3588LQ Overview
      • GC-3568JBAF

        • Introduction

          • GC-3568JBAF Overview
      • C-K1BA

        • Introduction

          • C-K1BA Overview
    • Software Platform

      • ShiMetaPi Workbench

        • Introduction

          • Product Overview
          • Core Architecture
          • Feature Entries
          • Supported Hardware
          • Release Notes
        • Quick Start

          • Install & Login
          • Connect the Device
          • Set Up the Environment
          • Connect to AIHub
          • First Inference
        • User Guide

          • Workspace Overview
          • Device Manager
          • Model Market
          • One-Click Deploy
          • Vision — SVP
          • Vision - Custom Models
          • shimeta-py IDE
          • Terminal
          • Agent Debug Assistant
          • Settings and Resources
        • FAQ

          • Installation & Login
          • Device Connection
          • Models & Deployment
          • Vision & Runtime
          • Settings & Other
      • ShimetaPi Repository

        • Introduction

          • ShimetaPi Software Repository
        • Pico G1 (GK7206)

          • Quick Start

            • Installation & First Inference
            • shimeta_infer — Image Inference
            • shimeta_camera — Real-time Camera Inference
            • SVP Scene Detection
            • File Transfer & Built-in Model Reference
            • FAQ
          • HTTP API & Python SDK

            • HTTP API Reference
      • Model Fine-tuning Platform

        • Introduction

          • Model Training Platform
        • Quick Start

          • Register & Login
          • Create Your First Model (30-Minute Quick Experience)
        • Training Guide

          • Data Preparation & Annotation
          • Training Parameter Configuration
          • Start & Monitor Training
          • Model Evaluation & Testing
        • Model Deployment

          • Export Model
          • Deploy to Edge Device

I2C Communication

1 I2C Introduction

The I2C bus controller transfers information between devices connected to the bus through the Serial Data (SDA) line and the Serial Clock (SCL) line. Each device has a unique address identification (whether it is a microcontroller — MCU, LCD driver, memory, or keyboard interface), and each can act as a transmitter or receiver (determined by the device's function).

I2C总线结构图

For a detailed I2C introduction, please refer to:

  • CSDN Blog Article

2 I2C Board Interface

I2C板卡接口

The board's pins expose a total of 2 groups of I2C interfaces, namely i2c-3 and i2c-5.

3 I2C Usage — Command-Line Method

3.1 I2C Device-Tree Configuration

Below, based on the introduction in the device-tree chapter, we will analyze the device-tree configuration of I2C3 and I2C5.

Tips

For the file paths below: out/kernel/src_tmp/linux-5.10/arch/arm64/boot/dts/rockchip/ requires compiling the source code first.

Let's first find the basic configuration content of I2C3 and I2C5 in rk3568.dtsi, as follows:

i2c3: i2c@fe5c0000 {
    compatible = "rockchip,rk3399-i2c";
    reg = <0x0 0xfe5c0000 0x0 0x1000>;  // 寄存器地址
    clocks = <&cru CLK_I2C3>, <&cru PCLK_I2C3>;  // 时钟配置
    clock-names = "i2c", "pclk";
    interrupts = <GIC_SPI 49 IRQ_TYPE_LEVEL_HIGH>;  // 中断配置
    pinctrl-names = "default";
    pinctrl-0 = <&i2c3m0_xfer>;  // 引脚复用配置
    #address-cells = <1>;
    #size-cells = <0>;
    status = "disabled";  // 默认禁用
};

i2c5: i2c@fe5e0000 {
    compatible = "rockchip,rk3399-i2c";
    reg = <0x0 0xfe5e0000 0x0 0x1000>;  // 寄存器地址
    clocks = <&cru CLK_I2C5>, <&cru PCLK_I2C5>;  // 时钟配置
    clock-names = "i2c", "pclk";
    interrupts = <GIC_SPI 51 IRQ_TYPE_LEVEL_HIGH>;  // 中断配置
    pinctrl-names = "default";
    pinctrl-0 = <&i2c5m0_xfer>;  // 引脚复用配置
    #address-cells = <1>;
    #size-cells = <0>;
    status = "disabled";  // 默认禁用
};

Then go to rk3568-pinctrl.dtsi to view the I2C pin configuration:

i2c3m0_xfer: i2c3m0-xfer {
    rockchip,pins =
        /* i2c3_sclm0 - 时钟线 */
        <1 RK_PA1 1 &pcfg_pull_none_smt>,
        /* i2c3_sdam0 - 数据线 */
        <1 RK_PA0 1 &pcfg_pull_none_smt>;
};

i2c5m0_xfer: i2c5m0-xfer {
    rockchip,pins =
        /* i2c5_sclm0 - 时钟线 */
        <3 RK_PB3 4 &pcfg_pull_none_smt>,
        /* i2c5_sdam0 - 数据线 */
        <3 RK_PB4 4 &pcfg_pull_none_smt>;
};

Finally, find the board-level configuration file to view the I2C peripheral's specific configuration.

In rk3568-toybrick.dtsi, I2C5 is enabled and sensor devices are configured:

&i2c5 {
	status = "okay";

	gs_mxc6655xa: gs_mxc6655xa@15 {
		status = "okay";
		compatible = "gs_mxc6655xa";
		pinctrl-names = "default";
		pinctrl-0 = <&mxc6655xa_irq_gpio>;
		reg = <0x15>;
		irq-gpio = <&gpio3 RK_PC1 IRQ_TYPE_LEVEL_LOW>;
		irq_enable = <0>;
		poll_delay_ms = <30>;
		type = <SENSOR_TYPE_ACCEL>;
		power-off-in-suspend = <1>;
		layout = <1>;
	};

    mxc6655xa: mxc6655xa@15 {
		status = "disabled";
		compatible = "gs_mxc6655xa";
		pinctrl-names = "default";
		pinctrl-0 = <&mxc6655xa_irq_gpio>;
		reg = <0x15>;
		irq-gpio = <&gpio3 RK_PC1 IRQ_TYPE_LEVEL_LOW>;
		irq_enable = <0>;
		poll_delay_ms = <30>;
		type = <SENSOR_TYPE_ACCEL>;
		power-off-in-suspend = <1>;
		layout = <1>;
	};

    hym8563: hym8563@51 {
		compatible = "haoyu,hym8563";
		reg = <0x51>;
		pinctrl-names = "default";
		pinctrl-0 = <&rtc_int>;

		interrupt-parent = <&gpio0>;
		interrupts = <RK_PD3 IRQ_TYPE_LEVEL_LOW>;
	};
};

Info

MXC6655XA is a digital-output three-axis accelerometer released by MEMSIC. hym8563 is an I2C-interface real-time clock (RTC) chip; the development board actually enables this device.

In rk3568-toybrick-x0-linux.dts, I2C3 is enabled and NCA9555 is configured:

&i2c3{
    nca9555:nca9555@20{
        reg=<0x20>;  // I2C设备地址为0x20
        compatible = "novosense,nca9555";  // 设备兼容性字符串
        status="okay";  // 设备状态为使能
        gpio-controller;  // 声明为GPIO控制器
        #gpio-cells = <2>;  // GPIO单元格数量
    };
};

Info

NCA9555 is a 24-pin CMOS device that provides 16-bit general-purpose parallel I2C-bus input/output GPIO expansion.

3.2 Common Commands for Operating I2C

Check I2C devices:

ls dev/i2c*

Test I2C commands:

I2C tool is an open-source tool. The SDK we provide has already downloaded and cross-compiled it. After compilation, test commands such as i2cdetect, i2cdump, i2cset, and i2cget have been generated on the board and can be used directly for debugging on the command line:

  • i2cdetect – used to enumerate the I2C bus and all the devices on it
  • i2cdump – displays all register values of an i2c device
  • i2cget – reads the value of a register of an i2c device
  • i2cset – writes the value of a register of an i2c device

3.3 Specific Function Demo

The following are common usage examples of the above commands:

1. Detect how many groups of i2c buses the current system has:

i2cdetect -l
I2C总线检测

2. View devices on the i2c-3 interface:

i2cdetect -a 3
I2C设备扫描

UU indicates that the device driver for the device with address 20 has been loaded successfully, that is, the NCA9555 mounted on I2C3 mentioned above.

3. Read all register values of the specified device:

i2cdump -f -y 3 0x20

(Display the values of all register addresses from 0x00 to 0xff on the slave device 0x20 on i2c bus 3)

I2C寄存器读取

The command executed successfully and output data, which indicates that a device with address 0x20 exists on bus 3 and that basic communication is normal.

4. Read the value of a register of the specified I2C device:

i2cget -f -y 3 0x20 0x01

(Read the value of the 0x01 register in the device with address 0x20)

I2C单个寄存器读取

4. I2C Usage — NAPI Method

Materials Path

hap package: \05-Development Materials\01-OpenHarmory Development Materials\Peripheral Test APP\HAP\I2C_TEST.hap

Project source code: \05-Development Materials\01-OpenHarmory Development Materials\Peripheral Test APP\SRC\I2C_TEST

4.1 Kernel Permission Setting

We execute the following command in the terminal to add permission for I2C3:

chmod 777 /dev/i2c-3

4.2 Test Program Explanation

To see the data intuitively, a logic analyzer is used here to capture the sent I2C signals, to verify the correctness of the sent data.

After adding permission, first click to open the I2C device. After the prompt indicates the open succeeded, click to start sending "Shimeta Pi".

I2C设备打开

After clicking, I2C3 will send the string "Shimeta Pi" once every 100ms.

I2C自动发送

After enabling auto-send, we use a logic analyzer to capture data; the data captured within 1s is as follows:

I2C数据采集

We can see that the data sent every 100ms is as shown above.

Let's take the last 2 data items as an example to view:

I2C最后两个数据

The last two data packets are 0x50 and 0x69, corresponding to decimal 80 and 105. Check the ASCII table as follows:

ASCII表P字符

These correspond to the last 2 data items of the string "ShiMeta Pi".

By the same logic, the organized data is as shown in the table below:

CharacterHex ValueDecimal ValueDescription
'S'0x5383Character S
'h'0x68104Character h
'i'0x69105Character i
'M'0x4D77Character M
'e'0x65101Character e
't'0x74116Character t
'a'0x6197Character a
' '0x2032Space
'P'0x5080Character P
'i'0x69105Character i

There is no difference from the values actually observed by the logic analyzer.

I2C数据对比

4.3 Partial Code Explanation

Here we use the method of reading system nodes to operate I2C for read/write operations on the peripheral. We excerpt part of the code for introduction.

Let's first introduce the function ioctl, a very important control-operation function in the embedded field. You can imagine it as a universal remote control: press the corresponding button against the specified device and the device will perform the corresponding operation.

The function prototype is:

int ioctl(int fd, unsigned long request, ...);

Parameter introduction:

fd is the file descriptor, specifying the device file to operate on; request is the request code. For example, after you press the AC remote control, the remote control sends a section of ENC infrared encoding. After receiving this string of encoding, the AC decodes it; for example, if the decoded result is "0x9E", the AC internally looks at its own "task list". If it sees that "0x9E" means to turn on cooling, it performs the cooling operation. Correspondingly, the kernel has already defined some I2C operations; we only need to send the corresponding request code, and the kernel will perform the corresponding operation after receiving it.

... is a variable parameter that sends different data according to different request codes. For example, if the AC command code "0x88" means to set the temperature, then this data may be the temperature data.

Now look at one of the most important functions in our program: ioctl(i2c_fd, I2C_RDWR, &i2c_data). Is it not hard to understand? It tells the Linux kernel: "The I2C controller corresponding to i2c_fd is to perform an I2C read/write operation, and the specific data is &i2c_data."

Let's look again at the i2c-dev.h file provided by the Linux kernel, placed in the project in the same directory as napi_init.cpp. The code is as follows:

/*
    i2c-dev.h - i2c-bus driver, char device interface

    Copyright (C) 1995-97 Simon G. Vogl
    Copyright (C) 1998-99 Frodo Looijaard <frodol@dds.nl>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#ifndef _LINUX_I2C_DEV_H
#define _LINUX_I2C_DEV_H

#include <linux/types.h>
#include <linux/compiler.h>

/* /dev/i2c-X ioctl commands.  The ioctl's parameter is always an
 * unsigned long, except for:
 *  - I2C_FUNCS, takes pointer to an unsigned long
 *  - I2C_RDWR, takes pointer to struct i2c_rdwr_ioctl_data
 *  - I2C_SMBUS, takes pointer to struct i2c_smbus_ioctl_data
 */
#define I2C_RETRIES 0x0701 /* number of times a device address should
                be polled when not acknowledging */
#define I2C_TIMEOUT 0x0702 /* set timeout in units of 10 ms */

/* NOTE: Slave address is 7 or 10 bits, but 10-bit addresses
 * are NOT supported! (due to code brokenness)
 */
#define I2C_SLAVE   0x0703 /* Use this slave address */
#define I2C_SLAVE_FORCE 0x0706 /* Use this slave address, even if it
                is already in use by a driver! */
#define I2C_TENBIT  0x0704 /* 0 for 7 bit addrs, != 0 for 10 bit */

#define I2C_FUNCS   0x0705 /* Get the adapter functionality mask */

#define I2C_RDWR    0x0707 /* Combined R/W transfer (one STOP only) */

#define I2C_PEC    0x0708 /* != 0 to use PEC with SMBus */
#define I2C_SMBUS   0x0720 /* SMBus transfer */


/* This is the structure as used in the I2C_SMBUS ioctl call */
struct i2c_smbus_ioctl_data {
    __u8 read_write;
    __u8 command;
    __u32 size;
    union i2c_smbus_data __user *data;
};

/* This is the structure as used in the I2C_RDWR ioctl call */
struct i2c_rdwr_ioctl_data {
    struct i2c_msg __user *msgs;   /* pointers to i2c_msgs */
    __u32 nmsgs;         /* number of i2c_msgs */
};

#define  I2C_RDRW_IOCTL_MAX_MSGS    42

#ifdef __KERNEL__
#define I2C_MAJOR   89    /* Device major number    */
#endif

#endif /* _LINUX_I2C_DEV_H */

We can find that these are mainly some macro definitions, defining the operations that need to be performed upon receiving the corresponding request code.

#define I2C_RDWR    0x0707 /* Combined R/W transfer (one STOP only) */
/* This is the structure as used in the I2C_RDWR ioctl call */
struct i2c_rdwr_ioctl_data {
    struct i2c_msg __user *msgs;   /* pointers to i2c_msgs */
    __u32 nmsgs;         /* number of i2c_msgs */
};

Let's pull out I2C_RDWR, used in this project, as an example (code as above). Its function is to perform a complex combined I2C message transfer. The parameter is a pointer to i2c_rdwr_ioctl_data. The function it implements is to create an array i2c_msg containing read operations, write operations, and read/write combination operations, producing only one STOP signal that conforms to the I2C standard during the process.

At this point, looking at the NAPI function that sends I2C data, it is easy to explain:

// I2C写入一个字节
// 参数:offset (寄存器偏移地址), data (要写入的字节)
// 返回:成功返回0,失败返回-1
static napi_value I2cWriteByte(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};
    napi_value result;

    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

    if (argc < 2) {
        napi_create_int32(env, -1, &result);  // 参数错误返回-1
        return result;
    }

    if (!i2c_opened || i2c_fd < 0) {
        napi_create_int32(env, -1, &result);  // 设备未打开返回-1
        return result;
    }

    int32_t offset, data;
    napi_get_value_int32(env, args[0], &offset);
    napi_get_value_int32(env, args[1], &data);

    // 使用ioctl直接操作I2C设备
    struct i2c_rdwr_ioctl_data i2c_data;
    struct i2c_msg msg;
    unsigned char buf[2];

    buf[0] = (unsigned char)offset;  // 寄存器地址
    buf[1] = (unsigned char)data;    // 要写入的数据

    msg.addr = I2C_SLAVE_ADDR;       // I2C设备地址
    msg.flags = 0;                   // 写操作
    msg.len = 2;                     // 数据长度
    msg.buf = buf;                   // 数据缓冲区

    i2c_data.msgs = &msg;
    i2c_data.nmsgs = 1;

    int ret = ioctl(i2c_fd, I2C_RDWR, &i2c_data);

    if (ret < 0) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, I2C_TAG,
                   "I2C write byte failed: %{public}s", strerror(errno));
        napi_create_int32(env, -1, &result);  // 写入失败返回-1
        return result;
    }

    OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, I2C_TAG,
               "I2C write byte success: addr=0x%{public}02X, offset=0x%{public}02X, data=0x%{public}02X",
               I2C_SLAVE_ADDR, offset, data);

    napi_create_int32(env, 0, &result);  // 成功返回0
    return result;
}

Let's first look at the function I2cWriteByte. The process of implementing the function is as follows:

  1. Use the functions napi_get_cb_info and napi_get_value_int32 to obtain the offset value (offset) and data (data) passed in from the JavaScript side.
  2. Write the 2 bytes of data into the array i2c_data.
  3. Through the ioctl function, tell the kernel to perform the I2C_RDWR operation, with data i2c_data.
  4. The underlying layer will automatically drive the physical layer to generate the corresponding I2C start signal, send the corresponding 2 bytes of data, and then generate a stop signal to complete the I2C signal-transfer process.
// I2C写入字符串
// 参数:offset (寄存器偏移地址), data (要写入的字符串)
// 返回:成功返回0,失败返回-1
static napi_value I2cWriteString(napi_env env, napi_callback_info info)
{
    size_t argc = 2;
    napi_value args[2] = {nullptr};
    napi_value result;

    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

    if (argc < 2) {
        napi_create_int32(env, -1, &result);  // 参数错误返回-1
        return result;
    }

    if (!i2c_opened || i2c_fd < 0) {
        napi_create_int32(env, -1, &result);  // 设备未打开返回-1
        return result;
    }

    int32_t offset;
    napi_get_value_int32(env, args[0], &offset);

    size_t str_length;
    napi_get_value_string_utf8(env, args[1], nullptr, 0, &str_length);

    if (str_length == 0 || str_length > 256) {
        napi_create_int32(env, -1, &result);  // 字符串长度无效返回-1
        return result;
    }

    char* str_buffer = new char[str_length + 1];
    napi_get_value_string_utf8(env, args[1], str_buffer, str_length + 1, &str_length);

    // 使用ioctl直接操作I2C设备,逐字节写入
    struct i2c_rdwr_ioctl_data i2c_data;
    struct i2c_msg msg;
    unsigned char buf[2];
    int success_count = 0;

    for (size_t i = 0; i < str_length; i++) {
        buf[0] = (unsigned char)(offset + i);  // 寄存器地址
        buf[1] = (unsigned char)str_buffer[i]; // 要写入的数据

        msg.addr = I2C_SLAVE_ADDR;             // I2C设备地址
        msg.flags = 0;                         // 写操作
        msg.len = 2;                           // 数据长度
        msg.buf = buf;                         // 数据缓冲区

        i2c_data.msgs = &msg;
        i2c_data.nmsgs = 1;

        int ret = ioctl(i2c_fd, I2C_RDWR, &i2c_data);

        if (ret < 0) {
            OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, I2C_TAG,
                       "I2C write string failed at byte %{public}zu: %{public}s", i, strerror(errno));
            break;
        }
        success_count++;
    }

    delete[] str_buffer;

    if (success_count == (int)str_length) {
        OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, I2C_TAG,
                   "I2C write string success: addr=0x%{public}02X, offset=0x%{public}02X, length=%{public}d",
                   I2C_SLAVE_ADDR, offset, success_count);

        napi_create_int32(env, 0, &result);  // 成功返回0
    } else {
        OH_LOG_Print(LOG_APP, LOG_WARN, GLOBAL_RESMGR, I2C_TAG,
                   "I2C write string partial success: %{public}d/%{public}zu bytes written", success_count, str_length);

        napi_create_int32(env, -1, &result);  // 部分失败返回-1
    }

    return result;
}

The I2C write-string function is simpler: after obtaining the string length, perform the corresponding number of character transfers. It will not be explained further here.

Edit this page on GitHub
Prev
GPIO Introduction
Next
SPI Communication