ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Embedded / IoT > 고속 SPI 버스 통신 프로토콜과 센서 레지스터 읽기/쓰기 타이밍 제어High-Speed SPI Bus Protocol and Sensor Register Read/Write Timing Control
Embedded / IoT Intermediate Arduino SPI Library / ESP-IDF

고속 SPI 버스 통신 프로토콜과 센서 레지스터 읽기/쓰기 타이밍 제어High-Speed SPI Bus Protocol and Sensor Register Read/Write Timing Control

I2C 대비 빠른 10~80MHz 클럭의 SPI 4선식(MOSI, MISO, SCK, CS) 버스 통신 원리와 레지스터 읽기·쓰기 바이트 시퀀스 제어 기법입니다.Principles of 4-wire SPI (MOSI, MISO, SCK, CS) communication at 10–80 MHz clock speeds and byte-sequence control for reading and writing peripheral registers.

#Embedded #SPI #Hardware #Protocols #Communication
핵심 개념SPI는 전이중(Full-Duplex) 동기식 직렬 통신으로, 마스터가 클럭(SCK)을 인가할 때마다 MOSI 라인으로 비트를 출력하고 MISO 라인으로 동시에 비트를 수신합니다. 슬레이브 셀렉트(CS) 핀을 LOW로 내린 후 최상위 비트(MSB)에 R/W 플래그(0x80)를 설정하여 대상 레지스터 값을 읽어옵니다.
Key ConceptSPI is a full-duplex synchronous serial bus where the master shifts bits out on MOSI and simultaneously shifts bits in on MISO with every SCK clock pulse. To read a sensor register, pull the target Chip Select (CS) pin LOW, transmit the register address with the MSB Read/Write flag (0x80) set, and clock out a dummy byte (0x00) to receive the response.

1. SPI 1바이트 레지스터 읽기 C++ 함수1. Single-Byte SPI Register Read Function in C++

spi_register_read.cpp
#include <SPI.h>

uint8_t readSpiRegister(uint8_t csPin, uint8_t regAddress) {
    // 읽기 모드 플래그(최상위 비트 1) 세팅
    uint8_t readAddr = regAddress | 0x80;

    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
    digitalWrite(csPin, LOW); // 슬레이브 칩 활성화 (Active-Low)

    SPI.transfer(readAddr);                // 1. 대상 레지스터 주소 전송
    uint8_t regValue = SPI.transfer(0x00); // 2. 더미 바이트를 보내며 슬레이브 응답 클럭 생성

    digitalWrite(csPin, HIGH); // 슬레이브 칩 해제
    SPI.endTransaction();

    return regValue;
}
spi_register_read.cpp
#include <SPI.h>

uint8_t readSpiRegister(uint8_t csPin, uint8_t regAddress) {
    // Set read-mode flag (MSB = 1)
    uint8_t readAddr = regAddress | 0x80;

    SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE0));
    digitalWrite(csPin, LOW); // Assert Slave Chip Select (Active-Low)

    SPI.transfer(readAddr);                // 1. Transmit target register address
    uint8_t regValue = SPI.transfer(0x00); // 2. Send dummy byte to generate SCK pulses for slave reply

    digitalWrite(csPin, HIGH); // Deassert Slave Chip Select
    SPI.endTransaction();

    return regValue;
}

2. 실무 적용 및 주의사항2. Practical Considerations and Caveats

  • 클럭 극성(CPOL)과 위상(CPHA) 모드 일치: 센서 데이터시트에 명시된 SPI 모드(SPI_MODE0~SPI_MODE3)가 마스터 설정과 다르면 비트가 1비트씩 밀려 읽히는 현상이 발생합니다. 대부분의 MEMS 센서(BMI270, ICM-42688 등)는 SPI_MODE0(CPOL=0, CPHA=0) 또는 SPI_MODE3(CPOL=1, CPHA=1)을 사용합니다.
  • beginTransaction과 CS 핀 토글 순서: 다중 SPI 디바이스가 하나의 버스를 공유할 때 클럭 설정이 바운싱을 일으키지 않도록 SPI.beginTransaction()을 먼저 호출해 버스 클럭 모드를 확정한 뒤 digitalWrite(csPin, LOW)로 슬레이브를 선택해야 합니다.
  • 고속 클럭(10MHz 이상) 배선 길이 관리: 브레드보드 점퍼선이 15cm 이상 길어지면 기생 커패시턴스로 인해 10MHz 이상의 SCK 구형파 에지가 뭉개져 통신 오류가 발생하므로, 고속 전송 시에는 배선을 짧게 유지하고 GND 선을 나란히 배치해야 합니다.
  • Match Clock Polarity (CPOL) and Phase (CPHA): Mismatched SPI modes (SPI_MODE0–SPI_MODE3) between master and peripheral cause 1-bit shift errors. Check the peripheral datasheet—most MEMS IMUs operate in SPI_MODE0 (CPOL=0, CPHA=0) or SPI_MODE3 (CPOL=1, CPHA=1).
  • Call beginTransaction Before Pulling CS Low: When multiple devices share the same SPI bus with different clock modes, call SPI.beginTransaction() before asserting digitalWrite(csPin, LOW) so the SCK idle level stabilizes before the slave listens.
  • Keep Traces Short Above 10 MHz: Long breadboard jumper wires (> 15 cm) introduce parasitic capacitance that rounds off SCK edges above 10 MHz; keep wiring short and route a ground return alongside SCK.

SPI 트랜잭션 구간 보호와 더미 바이트 클럭 생성 원리를 정확히 지키면, IMU 센서나 외부 플래시 메모리로부터 지연 없이 데이터를 수집할 수 있습니다.

Properly framing SPI transactions and clocking dummy bytes for full-duplex reads enables deterministic, high-bandwidth communication with IMUs, ADCs, and external flash memory.

참고자료 & 관련 링크