ENع
→SPI in firmware
الدرس 28 · UART, I2C and SPI in firmware

SPI in firmware: modes and chip select

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

Write an SPI driver on an Arduino Uno R3 and read the chip ID of a BME280 sensor: state the settings, pull chip select LOW, send 0xD0, clock in 0x60 with a dummy byte, and raise chip select again. Then see what the SPI mode really means on a logic analyser, and why every chip on the bus needs its own chip select. The Hardware lesson “Serial buses: UART, I2C and SPI” explains the wires, and the Hardware lesson “Test and debug” shows what a logic analyser is; here we write the code and use the analyser to find two classic bugs.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 28 · تفاعلي
01 / 10

Four wires to a sensor

An Arduino Uno R3 reads a BME280 sensor over SPI. The Uno is the controller: it makes the clock. Four wires: SCK, the clock (pin 13); MOSI, data out (11); MISO, data in (12); and chip select, CS (10).

controller   Arduino Uno R3 (ATmega328P)
peripheral   BME280 breakout
SCK   pin 13   clock, made by the Uno
MOSI  pin 11   controller out, peripheral in (COPI)
MISO  pin 12   controller in, peripheral out (CIPO)
CS    pin 10   chip select, LOW = "talk to me"
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Four wires to a sensor

    An Arduino Uno R3 reads a BME280 sensor over SPI. The Uno is the controller: it makes the clock. Four wires: SCK, the clock (pin 13); MOSI, data out (11); MISO, data in (12); and chip select, CS (10).

    controller   Arduino Uno R3 (ATmega328P)
    peripheral   BME280 breakout
    SCK   pin 13   clock, made by the Uno
    MOSI  pin 11   controller out, peripheral in (COPI)
    MISO  pin 12   controller in, peripheral out (CIPO)
    CS    pin 10   chip select, LOW = "talk to me"
  2. Settings first

    SPISettings names three things: the top speed (1 MHz), the bit order (most significant bit first) and the mode (SPI_MODE0). beginTransaction() loads them into the Uno's SPI hardware. The BME280 datasheet allows up to 10 MHz.

    SPISettings BME(1000000, MSBFIRST, SPI_MODE0);
    speed   1,000,000 Hz asked  ->  1 MHz (16 MHz / 16)
    order   MSBFIRST: bit 7 goes first
    mode    SPI_MODE0: see the Modes chapter
    line 1  SPI.beginTransaction(BME);
  3. Chip select goes LOW

    digitalWrite(CS, LOW) selects the sensor. Chip select is active low: a chip listens while its CS is LOW and ignores the bus while it is HIGH. SPI picks a chip this way, with a wire, instead of an address.

    line 2  digitalWrite(CS, LOW);
    pin 10  HIGH -> LOW: the frame starts
    CS LOW   this chip listens and may drive MISO
    CS HIGH  this chip ignores the bus
  4. Send 0xD0: read the ID

    SPI.transfer(0xD0) clocks 8 bits out on MOSI, most significant first: 1101 0000. Bit 7 = 1 means read; the other 7 bits pick the register. So the byte asks for register 0xD0, the chip ID.

    line 3   SPI.transfer(0xD0);
    MOSI     1101 0000   (8 clocks, MSB first)
    bit 7    1 = read   (0 would be write)
    bits 6-0 0x50  ->  register 0xD0 "id"
    sensor   heard 0xD0
  5. Clock in the answer

    The sensor can only answer while the clock runs, so the Uno sends a dummy 0x00. On those same 8 clocks the sensor shifts 0110 0000 out on MISO: 0x60. Every transfer sends one byte and receives one.

    line 4   id = SPI.transfer(0x00);
    MOSI     0000 0000   dummy, keeps the clock going
    MISO     0110 0000   = 0x60
    
    # Python: one transfer is two shift registers swapping bits
    def transfer(sent, reply):
        got = heard = 0
        for i in range(7, -1, -1):        # 8 clocks, MSB first
            heard = heard << 1 | (sent >> i) & 1   # sensor reads MOSI
            got = got << 1 | (reply >> i) & 1      # Uno reads MISO
        return got, heard
    
    print([hex(b) for b in transfer(0x00, 0x60)])
    # -> ['0x60', '0x0']
  6. CS HIGH: frame over

    digitalWrite(CS, HIGH) ends the frame; endTransaction() frees the bus for other code. id holds 0x60, the chip ID the datasheet promises, so the driver works. The clocking took 16 clocks: 16 µs at 1 MHz.

    line 5   digitalWrite(CS, HIGH);   frame over
    line 6   SPI.endTransaction();     bus free
    id       0x60  (datasheet: chip_id = 0x60)
    time     16 clocks x 1 µs = 16 µs of clocking
    
    // Arduino Uno R3 + BME280 breakout on SPI, CS on pin 10
    #include <SPI.h>
    const int CS = 10;
    const SPISettings BME(1000000, MSBFIRST, SPI_MODE0);
    uint8_t id;
    
    void setup() {
      Serial.begin(9600);
      pinMode(CS, OUTPUT);
      digitalWrite(CS, HIGH);    // not selected yet
      SPI.begin();
      SPI.beginTransaction(BME);
      digitalWrite(CS, LOW);
      SPI.transfer(0xD0);
      id = SPI.transfer(0x00);
      digitalWrite(CS, HIGH);
      SPI.endTransaction();
      Serial.println(id, HEX);   // prints 60
    }
    
    void loop() {}
  7. The mode: which edge reads

    The mode says when a bit is read. CPOL is the clock's resting level; CPHA picks the edge. Mode 0: the clock rests low, bits are read on the rising edge and changed on the falling edge. The BME280 accepts modes 0 and 3.

    mode  CPOL  CPHA  bits change  bits read
      0     0     0    falling      rising
      1     0     1    rising       falling
      2     1     0    rising       falling
      3     1     1    falling      rising
    
    mode 0: each read lands in the middle of a bit
    BME280: modes 0 and 3 only
  8. Bug: the wrong mode

    Type SPI_MODE1 by mistake and the Uno reads on the falling edge: the instant the sensor changes the bit. Old bit or new one? It depends on nanoseconds. The analyser shows the read marks on the edges. Fix: use a mode the datasheet allows.

    SPI_MODE1   CPOL 0, CPHA 1: read on the falling edge
    BME280  changes SDO on the falling edge
    same edge  ->  a race: the byte may be right on one
                  board and wrong on the next
    analyser   read marks sit on the bit edges
    fix        SPI_MODE0 (or SPI_MODE3)
  9. A second chip, its own CS

    Add an SD card. It shares SCK, MOSI and MISO but gets its own chip select, pin 9. setup() makes both CS pins outputs and drives them HIGH. Then only the chip whose CS is LOW drives MISO.

    shared   SCK, MOSI, MISO
    own      CS pin 10 (BME280), CS pin 9 (SD card)
    
    // in setup(), before talking to anyone
    const int SD_CS = 9;
    pinMode(SD_CS, OUTPUT);
    digitalWrite(SD_CS, HIGH);
    
    rule: at most one CS LOW at a time
  10. Bug: two chips selected

    Forget digitalWrite(CS, HIGH) and the sensor stays selected when the SD card is called. Both chips drive MISO at once, and the bytes are garbage. On the analyser the giveaway is two CS lines LOW at the same time.

    line 5   // CS HIGH forgotten
    CS 10    still LOW: BME280 still selected
    CS 9     LOW: SD card selected
    MISO     two outputs fight: the byte is garbage
    analyser two CS lines LOW together
    fix      raise CS before selecting another chip

اختبار يتاح بعد الخطوة الأخيرة.