SPI in firmware: modes and chip select
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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"
اقرأ الدرس خطوة بخطوة
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"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);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 busSend 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 0xD0Clock 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']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() {}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 onlyBug: 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)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 timeBug: 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
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Your driver calls SPI.transfer(0x00) right after sending a read command. Why send 0x00 at all?
SPI.transfer() is a simultaneous send and receive. The peripheral never makes the clock, so the controller sends a dummy byte to clock the 8 bits of the reply in on MISO.
02The BME280 uses bit 7 of the first byte as read/write. Which byte reads register 0xF7?
Only the low 7 bits pick the register (0x77), and bit 7 = 1 means read, so the byte is 0xF7. A write would send 0x77. This is the datasheet's own example.
03In SPI mode 0, when does the receiver read each bit?
Mode 0 is CPOL 0 and CPHA 0: SCK rests low, data changes on the falling edge and is read on the rising edge, in the middle of each bit.
04The BME280 accepts modes 0 and 3. What happens if your SPISettings say SPI_MODE1?
Reading on the edge where the other side changes the line is a race. It can work on one board and fail on another, which is why you copy the mode from the datasheet.
05A logic analyser shows CS (pin 10) and SD CS (pin 9) LOW at the same time, and the bytes on MISO are garbage. What is the likely bug?
Only one chip may be selected at a time. A missing digitalWrite(CS, HIGH) leaves the first chip talking while the second one is selected, and their outputs fight on MISO.
المسرد
- SPI
- Serial Peripheral Interface: a bus where a controller makes a clock (SCK) and swaps bits with one peripheral at a time over MOSI and MISO.
- Controller and peripheral
- The controller (here the Uno) makes the clock and starts every transfer; the peripheral (a sensor, an SD card) answers. Older documents say master and slave.
- MOSI and MISO
- Controller out, peripheral in (also called COPI) and controller in, peripheral out (CIPO): one data wire for each direction.
- Chip select (CS)
- One wire per peripheral. It is active low: the chip takes part only while its CS is LOW.
- SPISettings
- The Arduino object holding three settings for a chip: the top clock speed, the bit order and the SPI mode.
- SPI mode (CPOL, CPHA)
- CPOL is the clock's resting level, CPHA picks the edge on which data is read. Modes 0 to 3 are the four combinations.
- Dummy byte
- A byte sent only to keep the clock running so the peripheral can shift its answer back.
- Logic analyser
- A tool that records several digital lines over time, so you can see CS, SCK, MOSI and MISO bit by bit.
الملاحظات والمصادر
- The BME280 runs its interface at 3.6 V at most, and an Uno's pins are 5 V, so use a breakout board with level shifting (or a 3.3 V board). The lesson "3.3 V and 5 V: level shifting" shows how.
- The analyser view draws the two bytes back to back. On a real Uno the CPU needs a few instructions between bytes, so a short gap appears between them. 16 clocks at 1 MHz is 16 µs of clocking.
- MISO is drawn at half height where the sensor sends no data (nobody drives the line); a real analyser shows it floating or pulled to one level.
- On a 16 MHz Uno, SPISettings picks the fastest clock at or below the one you ask for: 16 MHz / 2, / 4, / 8 and so on. Asking for 1 MHz gives exactly 16 MHz / 16. The BME280 allows up to 10 MHz.
- Pin 10 is the AVR's own SS pin. If it ever becomes a LOW input, the SPI hardware switches itself into peripheral mode, which is why it must stay an output. SPI.begin() sets it as an output and HIGH.
- Arduino language reference: SPI (Uno pins), source of docs.arduino.cc
- Arduino language reference: SPISettings, SPI.begin(), beginTransaction(), transfer(), endTransaction()
- Arduino: Serial Peripheral Interface (SPI), modes table and chip select (source of docs.arduino.cc/learn/communication/spi)
- Arduino AVR core: SPI library, SPI.h (clock divider and transfer)
- Arduino AVR core: SPI library, SPI.cpp (begin() and the SS pin)
- Bosch Sensortec BME280 datasheet (BST-BME280-DS001), section 6.3 SPI interface and register 0xD0
اختبار يتاح بعد الخطوة الأخيرة.