Read a Datasheet

One bit in a sensor’s control register wakes the chip, and the datasheet says which. Flip the bits, send the write, and read the chip’s reply to every wrong guess.

Learn to read the documents that come with every chip: the register map, the timing diagram, the numbers table, the pinout and the errata.

The sensor below is asleep. Find the one bit that wakes it in the datasheet page, flip it, and press Write CTRL. Then read the temperature. We build, piece by piece, how to read every part of that page.

You need binary and hex (a byte is eight bits, and 0x2D means 2D in base 16) and the idea of a register (a small storage cell in a chip that you can read or write). We build the rest from zero.

Sources: the Bosch Sensortec BMP280 data sheet (BST-BMP280-DS001-26, revision 1.26, October 2021), the NXP I2C-bus specification UM10204 (Rev. 7.0, 1 October 2021) and the STMicroelectronics CMSIS device header for the STM32F407. The sensor in the hero is made up.

Wake the ZT-1 sensor

ZT-1 datasheet, register CTRL, address 0x02, read/write, reset 0x01
bits 7:4 RSVD, write 0   bit 3 ALERT_EN, 1 = alert pin on   bits 2:1 RATE, 00 = 1 Hz, 01 = 4 Hz, 10 = 16 Hz, 11 = reserved   bit 0 STBY, 1 = standby, 0 = measure

The ZT-1 is a made-up chip. Its register layout follows real datasheets such as the BMP280’s. Its sample values and temperatures are illustrative.

Chapter 0

The Chip That Only Says 0x80

See why a correctly wired chip can sit silent, and why the fix is one sentence in a document you have not read yet

You solder a small pressure sensor to a board. You write code that reads its pressure registers, and you upload it. The code reads three bytes: 0x80, 0x00, 0x00. It reads the same three bytes every time. The wiring is right, the code runs, and the chip does nothing.

Those three bytes are not a fault. They are a message. On a Bosch BMP280 pressure sensor, the pressure registers hold 0x80, 0x00 and 0x00 until the first measurement is stored. The chip is saying "I have measured nothing." (Source: the register map, Table 18 of the BMP280 data sheet.)

The chip waits to be told

Here is the idea before the name. A chip is a box that does nothing until you tell it to. You tell it by writing numbers into small storage cells inside it. Each cell holds one number, and each number switches something on or off, or sets a speed.

A small storage cell in a chip that you can read or write is a register. Your code does not call a function on the sensor. It writes a number to one register and reads a number from another.

The company that makes the chip writes a document that lists every register and every promise. That document is the datasheet. Think of it as a contract. It says what the chip promises to do, and what you must do first to get it.

For the BMP280 the contract has one line that explains the silent chip. Section 3.2 says: "After powering up, the sensor settles in sleep mode." Section 3.6.1 adds: "In sleep mode, no measurements are performed." The chip woke up asleep, and nothing in your code told it to wake.

Watch the first moments of a chip

The device below walks the BMP280 through its first moments. Drag the slider from power off to the first measurement. Watch the control register and the current the chip draws.

Walk through power-up

Three stages: off, asleep after power-on, and measuring after you write one byte to register 0xF4. The bar shows the supply current on a log scale.

1

Currents are from the BMP280 data sheet at 25 °C: sleep 0.1 µA typical (0.3 µA maximum), and a 720 µA typical peak during a pressure measurement (1,120 µA maximum). The value 0x27 is a common example, not a recommendation: it means temperature and pressure at x1 oversampling and normal mode.

At stage 1 the chip is powered and answering, but it draws only 0.1 µA. Nothing happens inside. At stage 2 one write changes the two lowest bits of register 0xF4 to 11, and the chip starts to measure. The difference between "silent" and "working" was one byte that your code did not send.

Why you read instead of remember

A real chip has hundreds of registers and dozens of pages of rules. The BMP280 data sheet is 49 pages, and it is a small one. The reference manual of an STM32F4 microcontroller runs well over a thousand pages. Nobody remembers that much.

So firmware engineers do not read a datasheet from page 1 to the end. They ask a question and look up the answer. This lesson teaches the lookup. It has three habits.

  1. Look up, never recall. A bit position you remember wrongly costs an afternoon. A bit position you read costs ten seconds.
  2. Write down the page and the revision. Documents change. "BMP280 data sheet, revision 1.26, October 2021, section 4.3.4" is a fact you can check. "I read it somewhere" is not.
  3. Test the claim on the wire. Documents have mistakes. The chip is the final judge, and a logic analyzer shows what it did.

One honest limit. Your browser is not a chip. Every device in this lesson is a model: a program that follows the datasheet's rules so you can see them act. Each core chapter ends with an "On real hardware" note that names a board and the measurement to repeat.

The road

The lesson follows one question: how do I get from a document to a working chip? Each chapter answers one part.

  1. The document stack: datasheet, reference manual, errata, application note and schematic each answer different questions.
  2. The register map: address, name, bits, reset value and access type, read cell by cell.
  3. Bit surgery: set, clear and test single bits without breaking the others.
  4. Turning a chip on: reset state, power modes, and writes that the chip ignores.
  5. Timing diagrams: read the wires of an I2C write with a virtual logic analyzer.
  6. The numbers table: minimum, typical and maximum, and why you design for the worst.
  7. Pins and schematics: the pin you misread, and the one you left floating.
  8. Errata and revisions: when the document is right and the silicon is not.
  9. From the page to a driver: the whole bring-up, in order, in C.
  10. Field guide: the numbers, a checklist and the core code on one page.

New to embedded systems? Embedded Systems Intro explains what a microcontroller is. This lesson starts one step later, with the paper that comes with the part.

The shape of a datasheet

Almost every chip document has the same bones, and knowing them makes the first lookup fast. The BMP280 data sheet is a clean example. Its index of contents runs: 1 Specification, 2 Absolute maximum ratings, 3 Functional description, 4 Global memory map and register description, 5 Digital interfaces, 6 Pin-out and connection diagram, then the package and the document history.

Map your questions to those parts. "Will it survive my supply?" is chapter 2. "What does sleep mode mean?" is chapter 3. "Which byte do I write?" is chapter 4. "How do I send it?" is chapter 5. "Where does each wire go?" is chapter 6. Each of the next chapters in this lesson visits one of these parts, in the order that a bring-up needs them.

You can also read the sheet in two passes. On the first pass, read only the headings and the first sentence of each section, and skim the figures. That takes ten minutes and gives you the map. On the second pass, read the sections that your task needs, slowly, with a pencil. The second pass is where bugs are avoided.

This lesson is the first one in the Firmware from Zero series for a reason. Every later lesson, from clocks to buses to drivers, starts by opening a document. Learning to read it once pays off in every one of them.

A BMP280 returns 0x58 from its ID register but 0x80, 0x00, 0x00 from its pressure registers, every time. What does the datasheet suggest?

Chapter 1

Five Documents, Five Kinds of Question

Learn which paper answers which question, so that you open the right page the first time

You need the address of the register that sets port D pin 12 high. You open the datasheet of the STM32F407. You search for "BSRR". You find nothing useful. You search again, and again. Twenty minutes pass.

The register is real and the document is real. You opened the wrong document. A chip does not come with one manual. It comes with a small stack, and each paper in the stack answers one kind of question.

The stack, from the chip outward

The datasheet describes the part as a product. It lists the pins, the package, the supply voltages, the speeds, the currents, and the limits that destroy the chip. For a simple sensor such as the BMP280, the datasheet also holds the registers, because the chip is small. For a microcontroller, the registers move to a second book.

The reference manual describes how every peripheral works inside a family of microcontrollers: the timers, the serial ports, the clock tree. It holds the memory map and the register tables. For the STM32F405, F407, F415, F417, F427, F429 and related parts the reference manual is called RM0090.

The programming manual describes the processor core itself: its instructions, its interrupt controller, its fault registers. It is shared by every chip that uses the same core, so it comes from the core designer or is repackaged by the chip maker.

The errata sheet lists known bugs in the silicon, with a workaround for each. ST publishes one for the F405 and F407 family as ES0182 ("STM32F405/407xx and STM32F415/417xx device limitations"), and it is revised from time to time. Chapter 8 is about it.

An application note teaches one task in depth, such as how to mount a microphone behind a gasket. And the schematic of your board, with its user manual, tells you what the chip is wired to. The chip maker does not know that. Only your board does.

A question has a home

The trick is to match the question to a paper before you search. Take the question that cost twenty minutes: which bit turns on the clock for port D? Follow it through the stack.

  1. Kind of question: how a peripheral is controlled. That is the reference manual, not the datasheet.
  2. Section: the reset and clock control block, called RCC. Its register table lists one enable register per bus.
  3. Register: RCC_AHB1ENR, at offset 0x30 from the RCC base address 0x40023800. The full address is 0x40023830.
  4. Bit: GPIODEN, bit 3. Writing 1 turns the port D clock on.

The numbers in steps 3 and 4 come from ST's own CMSIS device header for the STM32F407, stm32f407xx.h, which is generated from the same register data as the manual. A header like this is a machine-readable register map. It is handy, but the manual is where the rules are written: the header cannot tell you that a write is ignored or that a clock must be on first.

Now a different question: which pin has the green LED on the STM32F4 Discovery board? No chip document knows. The board's user manual, UM1472, says the green LED, LD4, is on PD12. That is pin 12 of port D. Only the schematic and the board manual can say it.

Try it: send each question to its paper

Open the right paper

Each card is a question a firmware engineer asks. Pick the document that holds the answer. A wrong pick shows why that paper does not have it.

The facts come from the sources named in the replies: ST's CMSIS header for the STM32F407, UM1472, the BMP280 data sheet, the NXP I2C specification and InvenSense note AN-1003 as quoted in the electroacoustic lesson. Where a reply says "usually", the split is the common one, so check your own part’s documents.

The pattern is simple. If the question starts with "what is this chip", open the datasheet. If it starts with "how do I control it", open the reference manual. If it starts with "why does it not match the manual", open the errata. If it starts with "what is it wired to", open the schematic.

One worked example from sound

Chapter 7 of Electroacoustic Transducers shows why the stack is bigger than registers. A team builds a robot head. The microphone is fine on the bench and honks inside the head. The datasheet of the microphone says nothing wrong, because the fault is mechanical. A gasket and a vent form a small resonator.

The answer sits in an application note from the microphone maker, InvenSense AN-1003. It gives the vent formula and says that a hole of 0.5 to 1 mm is typical. A firmware engineer who reads only registers misses it. A reader who knows the stack asks the right question: which paper covers the mounting?

Check that the paper matches your part

A reference manual covers a family, not one chip. The first page lists the parts it applies to. RM0090 covers the F405, F415, F407, F417, F427, F437, F429 and F439 parts. The errata sheet ES0182 covers a narrower set: the F405, F407, F415 and F417. If your part is an F429, that errata sheet is the wrong one, and a good-looking workaround in it means nothing.

Decode the part number to know where you stand. Take STM32F407VGT6. The F4 and 07 name the family and the line. The V means 100 pins. The G means 1 Mbyte of flash. The T means an LQFP package. The 6 means an operating temperature range of -40 to 85 °C. The datasheet's ordering information table is the source for this code. Match the part on your board to the part the paper names before you trust anything in it.

Your STM32 board does not toggle an LED. You want to know which port and pin the LED is wired to. Which paper has that answer?

Chapter 2

Reading a Register Map

Read one table row cell by cell, and compose the byte that the row describes

You open the BMP280 data sheet at section 4.2. A grid of boxes fills the page. Names, hex numbers, small labels, and a column of values at the right edge. It looks like a spreadsheet of secrets. It is, in fact, the most useful page in the document.

The page is the register map: a table of every register in the chip, with where it lives and what its bits mean. Think of a hotel directory. Each room has a number, a name, a list of what is inside, and a note about who may enter. A register map says the same about each register.

One row, cell by cell

Here are the rows that matter, copied in plain form from Table 18 of the data sheet (revision 1.26).

NameAddressBits (7 down to 0)ResetType
press_msb0xF7press_msb<7:0>0x80read only
config0xF5t_sb[2:0] filter[2:0] spi3w_en[0]0x00read / write
ctrl_meas0xF4osrs_t[2:0] osrs_p[2:0] mode[1:0]0x00read / write
status0xF3measuring[0] (bit 3), im_update[0] (bit 0)0x00read only
reset0xE0reset[7:0]0x00write only
id0xD0chip_id[7:0]0x58read only

Read the highlighted row from left to right. Each cell answers one question.

  1. Name, ctrl_meas. What the register is called. Use this exact name in your code, so a colleague can find it in the document.
  2. Address, 0xF4. The number you send over the bus to pick this register. On this chip a register is one byte.
  3. Bit layout. The byte is cut into fields. The notation osrs_t[2:0] means a field named osrs_t that is 3 bits wide. Bits 7, 6 and 5 hold it. The field osrs_p takes bits 4, 3 and 2. The field mode takes bits 1 and 0.
  4. Reset state, 0x00. The value the register holds just after power-on. It is the answer to "what is the chip doing before I touch it?" For ctrl_meas it is all zeros, so the mode is 00: sleep.
  5. Type, read / write. Who may use the register, in the next section.

Four kinds of register, and one trap

The type column matters. The BMP280 table colours its rows by type. Each type has a rule and a way to break it.

Read only registers show you the chip's state: the chip ID in 0xD0, the status in 0xF3 and the data bytes. A write to them does nothing. Read / write registers are your controls: ctrl_meas and config. Write only registers take a command. The reset register at 0xE0 is the example. Section 4.3.2 says you write 0xB6 to reset the chip, that other values have no effect, and that a read always returns 0x00. So you cannot read back a reset command to check it.

The trap is the fourth kind: reserved registers and bits. The data sheet says reserved registers hold no guaranteed value when read, and that you must not write them. A write to one may do nothing, or it may change a test mode. On STM32 parts the manuals usually ask you to keep reserved bits at their reset value. The safe habit: never write a bit you did not read about.

Compose a register from a table

Now build a byte from the table. The device below shows ctrl_meas with its three fields. Set each field, and the byte, in binary and hex, follows. Your goal is the byte the data sheet's own fields would give for temperature at x2, pressure at x16 and normal mode.

Fill in ctrl_meas

Set osrs_t, osrs_p and mode with the controls. The byte below updates. Try to make it match the goal.

skipped
skipped

Field codes from Tables 20 to 22 of the BMP280 data sheet: osrs 000 = skipped, 001 = x1, 010 = x2, 011 = x4, 100 = x8, and 101 or higher = x16; mode 00 = sleep, 01 and 10 = forced, 11 = normal. Goal: temperature x2, pressure x16, normal mode.

Work the goal by hand. Temperature x2 is code 010. Pressure x16 is code 101. Normal mode is 11. Put them in order from bit 7 down: 010, 101, 11. That is 0101 0111, which is hex 0x57. Check the device: it shows the same byte. The method never changes: write each field's code in its bit slot, join the slots, then convert to hex.

A shorter byte is common in sample code. One frequent starting value is 0x27: temperature x1 (001), pressure x1 (001), normal mode (11), which gives 0010 0111. It is a starting point, not a rule. The right oversampling for you depends on noise and power, which the data sheet discusses in section 3.3.

From one byte to thirty-two bits

A microcontroller reference manual uses the same table, scaled up. An STM32 register is 32 bits wide and the registers sit four bytes apart. The port D registers start at 0x40020C00: MODER at offset 0x00, OTYPER at 0x04, OSPEEDR at 0x08, PUPDR at 0x0C, IDR at 0x10, ODR at 0x14 and BSRR at 0x18 (ST CMSIS header). The next chapter does bit surgery on them.

When a value spans several registers

Some values are too wide for one byte. The BMP280 spreads each 20-bit result over three registers. The pressure sits at 0xF7 (msb), 0xF8 (lsb) and 0xF9 (xlsb). The most significant byte has the lowest address. The data sheet says to read all of them in one go, a burst read starting at 0xF7, so that the three bytes belong to the same measurement.

The order of bytes in memory is called byte order or endianness. A sensor may send its high byte first or last. The register map shows which, because the lower address holds one byte and the next address holds the other. Read the addresses, not the names. The next lesson, Bits, Fixed-Width Types, Endianness and the Memory Map, takes this up in full.

The register map says register 0xE0 "reset" is write only, and that 0xB6 resets the chip. After you write 0xB6, you read 0xE0 to confirm. What do you get, and what does it mean?

Chapter 3

Bit Surgery on a Register

Change one field of a 32-bit register without damaging its neighbours

The reference manual says: to use pin PD12 as an output, put the binary value 01 in bits 25 and 24 of the port D mode register. You write one line of C. The LED lights, and the other LED on PD13 goes dark. A line that was meant to touch two bits has changed thirty-two.

Registers hold many fields side by side, as one byte held three fields in the last chapter. A write replaces the whole register. To change one field, you must keep the rest. That needs four small operations, called bit manipulation.

Four operations and a mask

A mask is a number with 1 in the bits you care about and 0 elsewhere. You build one by shifting: the C expression 1u << 3 is 0000 1000, the mask for bit 3. A field of width w that starts at bit n has the mask ((1u << w) − 1) << n. For the PD12 field, width 2 starting at bit 24, the mask is 3u << 24, which is 0x03000000.

  1. Set bits: reg |= mask. OR turns on the bits in the mask and leaves the others alone. It never turns a bit off.
  2. Clear bits: reg &= ~mask. AND with the inverted mask turns off the bits in the mask and keeps the rest.
  3. Toggle bits: reg ^= mask. XOR flips them.
  4. Test a bit: (reg & mask) != 0. AND keeps only the bit you ask about.

To write a multi-bit field, use two steps. First clear the whole field, then set the value you want, shifted into place: reg = (reg & ~mask) | (value << n). Reading the register, changing some bits and writing it back is called read-modify-write.

Why the clear step is not optional

It is tempting to use only OR. Suppose pin PD12 was already set up for another job, with field value 10 (an alternate function; the manual lists 00 input, 01 output, 10 alternate function, 11 analog). OR with 01 gives 11. That is analog mode, not output. The OR turned on a bit and could not turn off the other. The field needs the clear step first.

Make PD12 an output

The register starts with PD13 already an output (field 01). Choose what PD12 held before, then choose a way to write. The goal: PD12 = 01 and PD13 still 01.

The register layout is real: GPIOD_MODER at 0x40020C00 with two bits per pin, so PD12 is bits 25 to 24 and PD13 is bits 27 to 26 (ST CMSIS header; field codes from RM0090). The starting values are illustrative, since the real reset value and your startup code decide what the register holds.

Take the case "PD12 was 10". The register starts as 0x06000000: PD13 field 01 in bits 27 and 26 gives 0x04000000, and PD12 field 10 in bits 25 and 24 gives 0x02000000. Try each method with the value 0x01000000.

  1. Assign: MODER = 0x01000000 gives 0x01000000. PD12 is 01, but PD13 became 00. It lost its job.
  2. OR: MODER |= 0x01000000 gives 0x07000000. PD13 is safe, but PD12 is 11, the analog mode.
  3. Clear, then OR: 0x06000000 and ~0x03000000 gives 0x04000000, and OR 0x01000000 gives 0x05000000. Both fields are right.

The clock comes first, and BSRR avoids the risk

Two more facts complete the picture. First, a peripheral needs its clock before it listens. For port D the enable bit is in RCC_AHB1ENR (bit 3, GPIODEN, at 0x40023830). Chapter 1 found it. Write it first, then touch the port registers. The manual of your part says whether a short wait is needed after the enable.

Second, read-modify-write has a hidden risk. If an interrupt changes the same register between your read and your write, your write puts back the old value and the change is lost. For output pins, STM32 gives a safer door: the bit set/reset register, BSRR. Writing a 1 in its low half (bits 0 to 15) sets that pin. Writing a 1 in its high half (bits 16 to 31) clears it. Writing 0 changes nothing. So BSRR = 1u << 12 sets PD12 and BSRR = 1u << 28 clears it, in one write, with no read.

Here is the whole recipe in C. The word volatile tells the compiler that the value can change by itself, so it must really read and write the address each time. Reset to main() and the next lesson, Bits, Types and the Memory Map, explain why.

c#include <stdint.h>
#define RCC_AHB1ENR  (*(volatile uint32_t *)0x40023830u)  /* RCC base 0x40023800 + 0x30 */
#define GPIOD_MODER  (*(volatile uint32_t *)0x40020C00u)  /* GPIOD base + 0x00          */
#define GPIOD_BSRR   (*(volatile uint32_t *)0x40020C18u)  /* GPIOD base + 0x18          */

void led_init(void) {
    RCC_AHB1ENR |= (1u << 3);                                    /* GPIODEN: port D clock on first */
    GPIOD_MODER  = (GPIOD_MODER & ~(3u << 24)) | (1u << 24); /* PD12 field = 01, output */
}
void led_on(void)  { GPIOD_BSRR = (1u << 12); }   /* BS12: set PD12   */
void led_off(void) { GPIOD_BSRR = (1u << 28); }   /* BR12: reset PD12 */

Read the code against the manual and every number has a source. 0x40023830 is the RCC base plus 0x30. The shift 3 is GPIODEN. The shift 24 is PD12's field start. The shifts 12 and 28 are BS12 and BR12. Nothing is a guess.

Reading the manual’s bit notation

Reference manuals describe each field with short codes. The common ones in STM32 manuals are r (read only), w (write only), rw (read and write) and rc_w1 (read, and clear by writing 1). A flag with rc_w1 clears when you write a 1 to it, so writing back what you read can clear flags you did not mean to clear. Check the legend at the start of the register chapter of your own manual.

A worked mask from the BMP280. The field osrs_t is 3 bits wide and starts at bit 5. Its mask is ((1 << 3) − 1) << 5 = 7 << 5 = 0xE0. To read the field from a register value v, shift down after masking: (v & 0xE0) >> 5. To test one flag, such as the status bit measuring (bit 3), use (status & 0x08) != 0. The same four tools from this chapter do all of it.

PD12's field holds 10. You run GPIOD_MODER |= (1u << 24) to make it an output. What does the field hold afterwards?

Chapter 4

Turning a Chip On

Follow a sensor from power-up to its first result, and learn which sentences in the document hide the bugs

You power the BMP280 and, in the first line of code, you read its ID. The bus returns a NACK, a "not acknowledged" signal. You wire it again. Same result. Then you add a delay of a few milliseconds before the first read, and it works.

Nothing was wrong with the wire. The data sheet says it in its table of electrical characteristics: the start-up time, "time to first communication" after both supplies are up, is 2 ms. Before that, the chip does not listen. The number was in the document the whole time.

Three modes, one default

After start-up, the BMP280 sits in sleep mode. Section 3.6 defines three power modes, chosen by the two mode[1:0] bits of register 0xF4.

mode[1:0]NameWhat the chip doesWhen to use it
00SleepNo measurements. All registers can be read.The state after power-up. Configure here.
01 or 10ForcedOne measurement, then back to sleep.Low sample rates, or when the host sets the timing.
11NormalMeasure, wait, measure again, in a loop.Steady streams, and when you use the IIR filter.

This table is the shape of almost every sensor datasheet. A default state that does nothing. A mode that does one thing and stops. A mode that does it forever. Once you see the shape, a new chip takes minutes.

The sentences where the bugs live

The register tables are precise. The prose around them holds the rules that break code. Three sentences from the BMP280 data sheet are worth a highlighter. Read the small words.

  1. "Writes to the config register in normal mode may be ignored. In sleep mode writes are not ignored." (section 4.3.5.) The word "may" means: do not depend on it. Put the chip to sleep before you write config.
  2. "If the device is currently performing a measurement, execution of mode switching commands is delayed until the end of the currently running measurement period." (section 3.6.4.) A mode write can be late. It is not lost.
  3. Forced mode returns to sleep. (section 3.6.2.) "For a next measurement, forced mode needs to be selected again." A loop that writes the mode once will read one sample and then stale data.

A fourth rule sits in the timing advice of section 3.9: in forced mode, read the data only after the maximum measurement time of Table 13. For the lowest oversampling setting (temperature x1, pressure x1) the typical time is 5.5 ms and the maximum is 6.4 ms. Chapter 6 explains why you wait for the maximum.

Talk to a model of the chip

The device below models the BMP280's rules. Every button is a bus transaction or a wait. Read the chip's reply after each one. Two goals: first, read a pressure that is not 0x80, 0x00, 0x00. Second, try to change config while the chip is in normal mode, and see what happens.

Poke the virtual BMP280

The chip just powered up. Try a read right now, then wait, then follow the datasheet. The diagram shows its mode.

A model of BMP280 rules from the data sheet: 2 ms start-up, sleep after reset, forced returns to sleep, config writes may be ignored in normal mode, and the 0x80 0x00 0x00 value before a measurement. Measurement times are set between the typical and maximum of Table 13 (6 ms for x1, x1). The sample bytes are made up.

Work the first goal in order. Wait 2 ms. Write 0xF4 = 0x25: both oversampling fields x1 (001 and 001), mode 01, forced. The chip starts a measurement. Wait 10 ms, which is longer than the 6.4 ms maximum. Read 0xF7. The bytes are no longer the "nothing measured" value. Read again with the chip now asleep, and the same data are still there until you start another measurement.

The second goal teaches the order of a configuration. Write 0xF4 = 0x27 (normal mode), then try 0xF5 = 0x10. The chip replies that it ignored the write. The fix is the sequence: write 0xF4 = 0x00 to go to sleep, write config, then write ctrl_meas again. Section 4.3.5 gives you this order in one sentence.

Reset is a command, not a state

If the chip is in an unknown state, a soft reset returns it to the start. Section 4.3.2 says writing 0xB6 to register 0xE0 resets the chip with the complete power-on-reset procedure. Any other value has no effect. After a reset, the registers hold their reset values and the chip sleeps again, so your bring-up code starts from a known place.

Read back what you wrote

One habit finds many bugs: after you write a register, read it back and compare. If you wrote 0x10 to config and read 0x00, the write was ignored, whatever the ACK said. Do this in early bring-up code, and remove it once the driver is trusted. Read back only registers that are read and write. A write only register such as reset always reads 0x00.

The power-up rules also have good news. Section 3.2 says there are no limits on the slope or the order in which VDD and VDDIO rise. It also says that if VDDIO is present but VDD is not, the interface pins stay at high impedance, so the bus is free for other chips. You do not need a special supply sequence for this part. Other chips, such as audio codecs, do need one, and their data sheets list the order.

Your driver sets the BMP280 to normal mode (0xF4 = 0x27) and then writes a new filter setting to config (0xF5). The ACK comes back each time, but the filter does not change. What does the data sheet suggest?

Chapter 5

Reading a Timing Diagram

Read two wires like a score, and decode an I2C write one clock at a time

Your code writes a byte to the sensor. Nothing happens. You clip a logic analyzer to the two wires and see a picture of two lines that jump up and down. The picture holds the answer, if you can read it.

A logic analyzer records whether each wire is high or low, many millions of times a second, and draws the result. A timing diagram in a datasheet is the same kind of picture, drawn by the chip maker to show what the wires should do. Reading one is like reading sheet music: each wire has its own staff, and time moves from left to right.

The four things to look for

  1. Lanes. Each wire gets one horizontal lane, named at the left. High is up and low is down.
  2. Order, not scale. Time runs left to right, but the drawing is not to scale. Only the order of edges is exact. The numbers are in a table.
  3. Edges that matter. Someone samples a wire on a specific edge. The diagram shows which one.
  4. Dimension lines. Short arrows between two edges, with a name such as tLOW or tSU;DAT. The table of timings gives that name a minimum or a maximum.

I2C in four rules

I2C (say "I squared C") is a two-wire bus. One wire, SCL, carries the clock. The other, SDA, carries the data. The controller (your microcontroller) drives SCL. The rules, from the NXP I2C-bus specification UM10204, are short.

  1. A bit is valid while SCL is high. SDA must stay stable during the high period of the clock. It may change only while SCL is low.
  2. START: SDA falls while SCL is high. It begins a transaction.
  3. STOP: SDA rises while SCL is high. It ends a transaction.
  4. The ninth clock is the answer. After eight data bits, the receiver pulls SDA low for one clock. That is an ACK, "acknowledge". If SDA stays high, that is a NACK.

A write to the BMP280 follows the pattern of Figure 7 in its data sheet: START, the address byte, an ACK, the register address, an ACK, the data byte, an ACK, STOP. The address byte is the 7-bit address followed by one bit for direction, 0 for a write. With the SDO pin tied to ground, the chip's address is 0x76, which is 1110110. With the direction bit that gives 11101100 = 0xEC.

To set ctrl_meas to 0x27, the master sends three bytes: 0xEC, 0xF4 and 0x27. That is 27 clock pulses, nine for each byte. At the Fast-mode limit of 400 kHz each clock takes 2.5 µs, so the three bytes take 67.5 µs. At the 100 kHz limit of Standard-mode they take 270 µs.

Decode a capture

Now be the logic analyzer's decoder. The capture below shows SCL and SDA for a three-byte transaction. The shaded band marks the byte you are decoding. Read SDA at each rising edge of SCL, which is where the receiver samples, and enter the eight bits you read, most significant first.

Decode the wires

Pick a capture and a byte. Set the bits you read from SDA at each SCL rising edge, then press Check. The ninth slot of each byte is the ACK.

Waveforms are drawn from the I2C rules in UM10204 and the BMP280 write format (data sheet Figure 7), with ideal edges and one sample per clock. Real edges are slower because the bus has a pull-up resistor. The second capture sends 0xEE, the address 0x77 with the write bit, to a chip wired for 0x76, so nobody answers.

Try the first capture, byte 1. At each of the eight rising edges SDA reads 1, 1, 1, 0, 1, 1, 0, 0. That is 11101100, hex 0xEC: address 0x76, direction write. Byte 2 is 11110100, 0xF4, the register. Byte 3 is 00100111, 0x27, the value. In the second capture the first byte is 0xEE, and the ninth slot stays high: a NACK. The controller sent the address of a chip that is not there. The picture alone says the address is wrong.

Setup and hold: the shutter rule

The two small timings in every such diagram are best seen as a camera. Setup time is how long SDA must be still before the clock edge that samples it. Hold time is how long it must stay still after that edge. A subject who moves just before or after the shutter makes a blurred photo. The BMP280 table 27 gives, for Standard and Fast mode, a minimum setup time (tSU;DAT) of 160 ns and a minimum hold time (tHD;DAT) of 80 ns for a bus load of 100 pF or less. Your controller must meet both.

The same chip also speaks SPI, and its data sheet gives a timing diagram for that too, with CSB, SCK, SDI and SDO. The method of reading is the same: find the lanes, find the sampling edge, find the dimension lines, then find the numbers in the table.

The read transaction, and a setup margin

A read has two phases (Figure 8 of the data sheet). First the master writes the register address: START, 0xEC, ACK, 0xF6, ACK. Then it sends a repeated START or a STOP, and addresses the chip again in read mode: 0x76 with a read bit of 1 is 0xED. The chip then sends bytes from rising register addresses. The master ACKs each byte except the last. It answers the last with a NACK and then a STOP. The NACK here is not an error. It means "no more bytes, please".

A margin example. The BMP280 asks for a data setup time of at least 160 ns. Suppose your controller changes SDA 300 ns before the rising edge of SCL. The margin is 300 − 160 = 140 ns, so it passes. If a slow edge on a long wire eats 200 ns of that time, the margin is 100 − 160 = −60 ns and bits will flip. Margins, not just pass and fail, tell you how close you are.

On a logic analyzer capture, the address byte goes by, and on the ninth clock SDA stays high. What does that mean?

Chapter 6

Min, Typ, Max: Reading the Numbers Table

Learn what each column promises, and why you design for the worst column, not the typical one

Your sensor works for a week on the bench. You ship ten of them in a cold warehouse. Two of them stop returning data after an hour, and one of them fails the first time you hot-plug it. The sensor is the same part. The bench was gentler than the world.

The data sheet predicted all three. It held numbers, with columns for minimum, typical and maximum, and conditions. The numbers table is where a chip says what it guarantees and what it only hopes. You read it with three questions: what is promised, under what conditions, and in which direction does it hurt?

What the three columns mean

Look at the head of the BMP280 specification tables. The sheet states how it fills the columns. Typical values of currents and state machine timings are measured at 25 °C. Minimum and maximum values of currents are measured on corner lots over the full temperature range. A corner lot is a batch of chips made on purpose at the edge of the factory's tolerance, so that the printed limits hold for the worst chips that ship.

  1. Typical is a good chip at a comfortable temperature. It is a fact about the average, not a promise.
  2. Minimum and maximum are the promise. Any chip you receive stays inside them, over the stated conditions.
  3. Empty or "tbd" means no promise. The BMP280 table lists a maximum sampling rate of "tbd". Do not design with a number the maker has not given.

The direction of danger depends on the number. For a current, the maximum hurts, because it drains your battery. For a time that you must wait, the maximum hurts, because you may read too soon. For a minimum setup time, the minimum is the limit your controller must meet. So you design against the column that hurts, not the typical one.

Two ratings that people mix up

A data sheet gives limits of two kinds. Operating values say where the chip meets its specification. The BMP280 supply VDD runs from 1.71 V to 3.6 V (typically 1.8 V), and the interface supply VDDIO from 1.2 V to 3.6 V. Inside those ranges the chip works as described.

Absolute maximum ratings say where the chip may be damaged. Table 3 gives -0.3 V to 4.25 V at any supply pin, and -0.3 V to VDDIO + 0.3 V at any interface pin. Between 3.6 V and 4.25 V the chip is outside its specification but not yet destroyed. Beyond 4.25 V, it may be. A rating is not a target. You never operate there.

The second rule bites often. If VDDIO is 1.8 V, an interface pin may not go above 2.1 V. A 3.3 V or 5 V signal from another board breaks the rating. The fix is a level shifter. The datasheet's pin limits tell you that before you smell smoke.

Where is this supply voltage?

Drag the supply voltage on VDD. The bands are the data sheet's: the operating range and the absolute maximum rating.

3.30 V

Limits from the BMP280 data sheet (revision 1.26): VDD 1.71 V minimum, 1.8 V typical, 3.6 V maximum (Table 2), and -0.3 V to 4.25 V at a supply pin as the absolute maximum (Table 3).

Worked example: a coin cell, typical against maximum

You want to run the sensor at one sample per second from a small battery. The table gives a supply current for that case: IDD,LP at 1 Hz forced mode, pressure and temperature, lowest power. The typical value is 2.8 µA. The maximum is 4.2 µA.

Take a battery that holds 220 mAh, which is 220,000 µAh. The life in hours is the capacity divided by the current. At the typical current: 220,000 / 2.8 = 78,571 hours, or about 8.97 years. At the maximum current: 220,000 / 4.2 = 52,381 hours, or about 5.98 years. The same chip gives a three-year difference between a hopeful plan and a safe plan.

Plan the battery

Slide the battery capacity. Watch how far apart the typical column and the maximum column land.

220 mAh

Currents are the data sheet’s IDD,LP at 25 °C: 2.8 µA typical, 4.2 µA maximum. The capacities are illustrative. The sensor is only one part of a board. The microcontroller usually draws far more, so a real budget adds every part.

A time you must respect

The same habit protects your code. Section 3.8.1 gives the measurement time for the lowest oversampling as 5.5 ms typical and 6.4 ms maximum. A driver that waits 6 ms looks fine on the bench, where the chip finishes in 5.5. On a cold chip that takes 6.4, the read happens early and returns the old data. Wait for the maximum. The data sheet says so: readout in forced mode should respect the maximum measurement times.

A last use of the maximum is the I2C clock itself. At 400 kHz one clock lasts 2.5 µs. The I2C specification asks for a low period of at least 1.3 µs and a high period of at least 0.6 µs, which together take 1.9 µs. The 0.6 µs left over must hold the rising and falling edges. At 1 MHz Fast-mode Plus the budget is 1.0 µs against 0.76 µs. The slack shrinks as the clock rises, which is why long wires and big pull-ups limit the speed.

Conditions, footnotes and units

A number without its condition is half a fact. The same parameter can have two rows. The BMP280 gives an SPI output delay of at most 30 ns for a 25 pF load with VDDIO of 1.6 V, and at most 40 ns with VDDIO of 1.2 V. The lower supply makes the chip slower. If you run at 1.2 V and design with 30 ns, you are 10 ns short.

Small superscript numbers beside a name point to footnotes. The sleep current and the standby current both carry one. Read them. A footnote often says "only valid at 25 °C" or "tested on a sample". Revision 1.12 of this data sheet changed the min and max values for the standby current and added exactly such a limit. Last, check the units. A confusion of µA and mA is a factor of 1,000, and a confusion of ns and µs is the same.

The data sheet lists a measurement time of 5.5 ms typical and 6.4 ms maximum. Your driver must be sure the result is ready. How long should it wait?

Chapter 7

Pins, Schematics and the Pin You Misread

Read a pinout from the correct side, and wire the strap pins that choose a chip’s address and interface

You wire a new breakout board. The I2C scan finds nothing. You check SDA and SCL three times. They are right. Then you notice a pin on the chip that you never connected. It was not on your list, because the datasheet said it was optional. It was not.

A pin is the smallest part of a chip and the cheapest place to lose a day. Three habits stop most of the losses: read the pinout from the correct side, read the name of every pin, and decide what every pin does, even the quiet ones.

Which side are you looking at?

The BMP280 is a tiny metal-lid package with pads underneath, so you cannot see the pads from the top. Its data sheet shows two pictures side by side: a top view, where the pads are not visible, and a bottom view, where they are. A pin marker shows pin 1 in both. The two views are mirror images. Pin 1 is on the right in the top view and on the left in the bottom view.

That is a classic misread. A designer copies the pin order from the top view onto a circuit board footprint, which is drawn from the top. The pads mirror, and the supply lands on the clock. The rule: before you trust any pinout, find the words "top view" or "bottom view" and the pin 1 marker.

The name hides the rule

Pin names carry meaning. A trailing B, a bar over the name, an "n" prefix or a "#" suffix all mean active low: the pin does its job when it is low. The BMP280 pin CSB, chip select, is an example. The data sheet says SPI communication starts when CSB goes low.

The names in the "Connect to" columns of Table 29 also differ by interface. The same pin 3 is SDI in 4-wire SPI, SDI/SDO in 3-wire SPI and SDA in I2C. Pin 5 is SDO in 4-wire SPI, "DNC" in 3-wire SPI (do not connect) and the address strap in I2C.

The two strap pins

Two pins of the BMP280 act as switches, not as signals. A pin that you tie to a fixed level to choose a behaviour is a strap pin.

  1. CSB picks the interface. The data sheet says: CSB must be connected to VDDIO to select the I2C interface.
  2. SDO picks the address. Tied to GND, the I2C address is 0x76. Tied to VDDIO, it is 0x77 (the same as the BMP180). The data sheet adds: the SDO pin cannot be left floating. If it floats, the address is unspecified.

One more fact: SDI, the data pin, is open drain. It can pull low but cannot drive high. It needs an external pull-up resistor to VDDIO, or the line never rises. And the sheet gives a warning that matters on a test bench: holding any interface pin high while VDDIO is switched off can permanently damage the device.

Wire it, then scan the bus

Choose where each strap pin goes, press Scan, and read the reply. Flip between top and bottom view to see how the pin numbers mirror.

Pin numbers and the top and bottom views follow Figure 14 and Table 29 of the BMP280 data sheet. The scan results model the sheet’s statements about CSB, SDO and the pull-up. A floating SDO gives an unspecified address, so the model answers differently each scan. What a real chip does with CSB low or floating is not fully described there, so the model only says it is not in I2C mode.

Try the wiring that the data sheet describes for I2C: CSB to VDDIO, SDO to GND, pull-ups present. The scan finds a device at 0x76. Move SDO to VDDIO and it moves to 0x77. Leave SDO floating and the scan result changes from one scan to the next. That is what "unspecified" looks like.

Two more habits for schematics

A schematic is a drawing of nets, the names of wires. Two pins with the same net name are connected, even if no line joins them. Search a net name across the pages to find every part that touches it. And read the microcontroller side too. A pin of an STM32 has a package number and a port name. Pin PD12 is not pin 12 of the package. The alternate function table in the microcontroller datasheet says which peripheral signal, such as I2C1_SCL, can appear on which port pin, and which alternate function number selects it.

Last, a trap from the software side. The STM32 HAL asks for the 7-bit address shifted left by one bit. The data sheet's 0x76 becomes 0xEC in the call, the same byte that went on the wire in chapter 5. Use the shifted value, or the scan misses the chip.

The mechanical page matters as much as the electrical one. Chapter 7 of Electroacoustic Transducers showed a microphone whose port, gasket and vent made a resonator. The pin and the port are both places where the chip meets the board. Embedded Hardware Interfacing goes further into buses and levels.

Start from the connection diagram

Chapter 6 of the data sheet gives three connection diagrams: 4-wire SPI, 3-wire SPI and I2C. Each marks pin 1. They show which pins go to the supplies, which go to the bus, and which strap pins are tied where. When you draw your own schematic, copy the diagram for your interface first. Change only what your board forces you to change. Most pin mistakes come from improving a design that you have not yet understood.

An I2C scan finds the BMP280 at 0x76 on some boots and at 0x77 on others, with the same code and the same board. What should you check first?

Chapter 8

Errata: When the Document Is Right and the Silicon Is Not

Match a symptom to a known bug by silicon revision, and learn when the bug is yours

You follow the reference manual line by line. The peripheral still misbehaves, on one board and not on its twin. You rewrite the driver twice. A colleague asks one question: which revision of the chip is on that board? The two boards carry different revisions. One has a bug that the other does not.

No chip is perfect. After a chip ships, its makers find mistakes in the silicon and mistakes in the documents. They publish both in a list called the errata (the plural of "erratum", a Latin word for a printing error). Some makers call the list "device limitations". Reading it is part of the job, and it is the part most beginners skip.

Two kinds of error, two kinds of paper

A silicon erratum says the chip does not do what its manual says. For example, a flag sets late, or a peripheral fails in one mode. The errata sheet lists it with the parts and revisions it touches, and often a workaround: a change in your code that avoids the bug.

A documentation error says the manual is wrong and the chip is fine. A bit number is off, a unit is wrong, a diagram is mislabelled. Makers fix these in the next revision of the document. Every datasheet carries a revision number and a date. The BMP280 sheet in this lesson is revision 1.26 from October 2021, and it says the data may change without notice. Write the revision down when you quote it.

The ST errata sheet for the STM32F405, F407, F415 and F417 parts is ES0182, "device limitations". ST revises it from time to time, so read the latest revision. It lists limitations by function and by silicon revision, and it warns that a workaround may depend on your application and may bring restrictions of its own.

How to use an errata sheet

  1. Find your revision. The chip's top marking shows a revision code. Many microcontrollers also report their device and revision numbers in a debug register. Your reference manual names it in the debug chapter. Read it from your own board, not from a spec.
  2. Read the whole list once, early. Read it before you write the driver, not after the third failure. A list of ten items takes ten minutes.
  3. Filter by revision and by feature. An entry applies only if it names your revision and a feature you use.
  4. Put the erratum number in a code comment next to its workaround. The next engineer can then see the reason and can remove the workaround when the board changes revision.

One more rule keeps you honest. If no erratum matches, the bug is probably yours. Chip bugs are rare and documented. Your own bugs are common. Look in your code first, and use the errata to rule the chip out, not to blame it.

Match the symptom to the sheet

The device below uses a made-up errata sheet for the made-up ZT-1 sensor from the top of the page. Choose your silicon revision. Then choose a symptom from your bug log. The device tells you whether an erratum explains it, and what the workaround is.

ZT-1 errata sheet (made up)
No.LimitationAffectsWorkaround
E1The first write that clears STBY after power-up is ignored.Rev AWrite CTRL twice.
E2After a RATE change, the first sample is stale.Rev A, BDiscard one sample after a RATE write.

Is this a chip bug?

Pick the revision printed on your chip, then a symptom from your log. The verdict says whether the sheet explains it.

The ZT-1 and its errata are made up for practice. The method is real: match the revision, then the feature, then read the workaround, and only then blame the chip.

Try revision A with the first symptom. The sheet has E1 for exactly that, and the workaround is to write twice. On revision C the same symptom has no entry, so the bug is in your code. The reverse trap also exists: you apply a workaround on a revision that never had the bug, and the extra write hides a real mistake.

When two documents disagree

Sometimes the datasheet and the reference manual disagree, or either disagrees with the chip. The order of trust is this: the errata sheet (it is the newest), then the reference manual, then the datasheet, then examples. Whatever the order, the chip has the last word. A logic analyzer capture or a register dump settles an argument that no reader of the PDF can. Note the difference in your code and, if you can, report it to the maker.

The BMP280 sheet itself shows the habit. It says SDO cannot be left floating (chapter 7), that config writes in normal mode may be ignored (chapter 4), and it marks one value "tbd". Each is a caution from people who have seen the failure. Treat such sentences as small errata written into the text.

Worked example: the document history

Every good document carries a history of its own changes. Section 10 of the BMP280 data sheet is a table of revisions with dates. It shows that revision 1.1, dated 10 February 2014, changed the osrs_p settings. Revision 1.11, dated 25 June 2014, modified the text about writing in normal mode. Revision 1.12, dated 12 July 2014, changed the standby current limits.

Read the second entry carefully. The rule about config writes in normal mode, which broke the driver in chapter 4, was rewritten in 2014. Code and blog posts older than that may describe a different rule. If you copy a driver from the web, check its date against the history of the document. The older the code, the more likely it follows a sentence that the maker has since changed.

A peripheral misbehaves on your board. The errata sheet lists a limitation for that peripheral, but it names revision A and your chip is revision C. What do you conclude?

Chapter 9

From the Page to a Driver

Turn the data sheet into a short, ordered program, and break it three ways to see which sentence each fault ignores

You have read the stack, the register map, the bits, the modes, the timing, the numbers, the pins and the errata. Now you write the first driver. Each line of it should point back to a sentence in the data sheet. If a line cannot, it is a guess.

A driver is the small piece of firmware that knows how to talk to one chip. Its job is to hide the registers: the rest of your program asks for a pressure, and the driver does the writes and reads. The next lesson in the series, From Register Map to Driver, builds driver layers in depth. This chapter writes the simplest correct one.

The bring-up order

Put the chapters' facts in order, with the section that justifies each step.

  1. Wait 2 ms after power, the start-up time (specification table). Chapter 4.
  2. Read the ID at 0xD0 and compare it with 0x58 (section 4.3.1). A wrong value means a wrong address or a wiring fault. Chapter 7.
  3. Soft reset by writing 0xB6 to 0xE0 (section 4.3.2), if the chip may be in an unknown state.
  4. Configure while asleep: write config (0xF5) first. Config writes in normal mode may be ignored (section 4.3.5).
  5. Start a measurement: write ctrl_meas (0xF4) with the oversampling bits and a mode. For one shot, forced mode (01).
  6. Wait for the maximum measurement time, 6.4 ms for temperature x1 and pressure x1 (Table 13), or poll status bit 3 (measuring).
  7. Burst read six bytes from 0xF7 to 0xFC (section 3.9), then combine them.

One more step is needed for real values: read the calibration bytes (0xA1 down to 0x88) and compute with the sheet's compensation formulas in section 3.11. The sheet strongly recommends the Bosch API for this part. Raw counts are not pascals.

Six bytes become two 20-bit numbers

The data registers hold pressure and temperature, each in three bytes: msb, lsb and xlsb. The register map shows that only the top four bits of the xlsb byte carry data, since its low four bits are fixed at 0. The data sheet says the readout is an unsigned 20-bit number. So you shift each byte into place and add them.

Take the sample bytes 0x65, 0x5A, 0xF0. The msb shifted left by 12 is 0x65 × 4096 = 413,696. The lsb shifted left by 4 is 0x5A × 16 = 1,440. The xlsb shifted right by 4 is 0xF0 / 16 = 15. The sum is 415,151. In code that is (b[0]<<12) | (b[1]<<4) | (b[2]>>4). If the pressure measurement is skipped, the bytes are 0x80, 0x00, 0x00 and the result is 0x80000, which is 524,288. That is the value from chapter 0.

c/* BMP280 on I2C, STM32 HAL. Each line cites the data sheet (BST-BMP280-DS001-26). */
#define BMP_ADDR  (0x76u << 1)   /* SDO low: 7-bit 0x76; HAL wants it shifted left by one */

static void wr(I2C_HandleTypeDef *h, uint8_t reg, uint8_t val) {
    HAL_I2C_Mem_Write(h, BMP_ADDR, reg, I2C_MEMADD_SIZE_8BIT, &val, 1, 10);
}

int bmp_read_raw(I2C_HandleTypeDef *h, int32_t *adc_p, int32_t *adc_t) {
    uint8_t id, b[6];
    HAL_Delay(2);                                   /* t_startup 2 ms                         */
    HAL_I2C_Mem_Read(h, BMP_ADDR, 0xD0, I2C_MEMADD_SIZE_8BIT, &id, 1, 10);
    if (id != 0x58) return -1;                      /* chip_id, 4.3.1: wrong address or wiring */
    wr(h, 0xE0, 0xB6); HAL_Delay(2);                /* soft reset, 4.3.2                      */
    wr(h, 0xF5, 0x10);                           /* config while asleep, 4.3.5             */
    wr(h, 0xF4, 0x25);                           /* osrs_t x1, osrs_p x1, mode 01 forced   */
    HAL_Delay(7);                                   /* above the 6.4 ms maximum, Table 13     */
    HAL_I2C_Mem_Read(h, BMP_ADDR, 0xF7, I2C_MEMADD_SIZE_8BIT, b, 6, 10); /* burst 0xF7..0xFC, 3.9 */
    *adc_p = (b[0] << 12) | (b[1] << 4) | (b[2] >> 4);  /* unsigned 20-bit           */
    *adc_t = (b[3] << 12) | (b[4] << 4) | (b[5] >> 4);
    return 0;                                          /* raw counts: compensation comes next    */
}

The listing ignores return codes from the HAL to stay short. A real driver checks each one. Now run it against the model, and then break it.

Run the driver, then break it

Press Run. Each line runs against the virtual chip. Then tick a fault and run again to see which sentence of the data sheet the fault ignores.

A model of the BMP280 rules (data sheet BST-BMP280-DS001-26). The sample bytes 0x65 0x5A 0xF0 and 0x7E 0xED 0x00 are made up; the formula for combining bytes follows the register map. Compensation from raw counts to pascals and degrees uses the chip’s calibration bytes and is not shown.

Run it clean first: the log shows an ACK at each step and the raw pressure 415,151. Tick Skip the 2 ms start-up: the first read gets a NACK, the ID check fails, and the driver returns an error. That fault ignores the start-up time. Tick Wait only 3 ms: the driver reads 0x80, 0x00, 0x00, which is 524,288, the value for nothing measured. That fault ignores Table 13. Tick Config after normal mode: every write gets an ACK, but the config byte never changes. That fault ignores section 4.3.5.

The three faults are three different reading failures. The first misses a number in a table. The second trusts the typical column. The third skims over the word "may". The point of the lesson sits here: the data sheet already knows your bug, and the sentence is a few paragraphs from the one you read.

What a good first driver returns

The listing returns 0 on success and -1 on a bad ID. A real driver goes further. It checks every HAL return code, uses a time limit on each bus call, and returns a different code for each failure: no ACK, wrong ID, timeout, data not ready. Each code points back to one chapter of this lesson, so a support engineer can find the cause from the number.

It also splits the work in two. One thin layer knows how to read and write registers on the bus. The layer above knows what the registers mean. With that split, you can swap the bus layer for a fake and test the logic on your laptop. The model on this page is exactly such a fake: it answers like the chip, with no hardware. The lesson From Register Map to Driver builds the layers in full.

Your driver reads the BMP280 pressure registers in forced mode and gets 0x80, 0x00, 0x00 on every call, although the ID check passes and the write was acknowledged. Which fix does the data sheet support?

Chapter 10

Field Guide: Reading Any Chip

Keep the numbers, the checklist and the core code from this lesson on one page

A chip is a box that does nothing until you write the right bits in the right order. The documents tell you which bits and which order. You pick the right paper, read the register map, change single bits safely, respect the modes, decode the timing, plan with the worst column, check the pins, look up the errata, and then write the driver one cited line at a time.

The numbers and terms

ItemValueWhere it comes from
BMP280 start-up time2 msBMP280 data sheet, specification table
Chip ID (register 0xD0)0x58Section 4.3.1
I2C address, SDO low or high0x76 or 0x77Section 5.2; write bytes 0xEC and 0xEE
Soft reset word (register 0xE0)0xB6Section 4.3.2
Main registersctrl_meas 0xF4, config 0xF5, status 0xF3, data 0xF7 to 0xFCTable 18
Measurement time, x1 and x15.5 ms typical, 6.4 ms maximumTable 13
Sleep current0.1 µA typical, 0.3 µA maximumSpecification table, 25 °C
Supply VDD, operating and absolute maximum1.71 V to 3.6 V; 4.25 VTables 2 and 3
I2C Fast-mode clock, low and high periods400 kHz; 1.3 µs and 0.6 µs minimumNXP UM10204, timing characteristics table
STM32F407 RCC base, AHB1ENR address0x40023800; 0x40023830ST CMSIS header stm32f407xx.h
GPIOD base, BSRR address0x40020C00; 0x40020C18Same header
PD12 field in MODER; GPIODEN bitbits 25:24; bit 3Same header

Three terms to keep: a register is a cell you read or write, a mask is a number of ones over the bits you mean, and a strap pin is a pin you tie to a level to pick a setting.

The checklist

Tick what you have done on your last chip. The count is yours alone.

Before you write the driver

A personal checklist: nothing is stored or sent. It follows the chapters of this lesson.

The core code

c/* 1. Write one field of a register without touching the rest (width must be less than 32). */
static inline void reg_set_field(volatile uint32_t *r, uint32_t pos, uint32_t width, uint32_t val) {
    uint32_t mask = ((1u << width) - 1u) << pos;
    *r = (*r & ~mask) | ((val << pos) & mask);      /* clear the field, then set the value */
}
/* PD12 as output: reg_set_field(&GPIOD_MODER, 24, 2, 1);  needs RCC_AHB1ENR bit 3 first. */

/* 2. Pack the BMP280 ctrl_meas byte from its three fields (Table 20). */
static inline uint8_t ctrl_meas(uint8_t osrs_t, uint8_t osrs_p, uint8_t mode) {
    return (osrs_t << 5) | (osrs_p << 2) | mode;         /* ctrl_meas(2, 5, 3) == 0x57 */
}

/* 3. Combine three data bytes into the unsigned 20-bit raw value (data sheet 3.9). */
static inline int32_t raw20(const uint8_t *b) { return (b[0] << 12) | (b[1] << 4) | (b[2] >> 4); }

Where it sits in the field

Reading documents is the first skill in firmware, and every later lesson uses it. Next in this series, Bits, Fixed-Width Types, Endianness and the Memory Map goes deeper into the registers you touched. First Light puts the clock, the pin and the LED in one bring-up. I2C, SPI, UART on the wire extends chapter 5 to the other buses, and From Register Map to Driver grows chapter 9 into layers.

The same skill opens the sensor tracks. What an IMU really measures reads noise density and output rate from an IMU datasheet. Codec chips reads power sequencing from a codec datasheet. For the mechanical side of a sensor, see Electroacoustic Transducers. Background: Embedded Systems Intro, Embedded C Programming, Embedded Hardware Interfacing, and Reset to main().

Sources and credit

This lesson has no course behind it. It is built from primary documents, which are the ones to open yourself.

  1. Bosch Sensortec, BMP280 Digital Pressure Sensor data sheet, document BST-BMP280-DS001-26, revision 1.26, October 2021.
  2. NXP Semiconductors, I2C-bus specification and user manual UM10204, Rev. 7.0, 1 October 2021.
  3. STMicroelectronics, CMSIS device header stm32f407xx.h for the STM32F407; the register chapters of RM0090 for the same parts; ES0182 (STM32F405/407xx and STM32F415/417xx device limitations, latest revision); and UM1472 for the STM32F4 Discovery board and its LED pins.
  4. InvenSense AN-1003 on microphone mounting, as used in chapter 7 of Electroacoustic Transducers.

The ZT-1 sensor and its errata sheet are made up for practice. Sample data bytes and all battery capacities are illustrative.

The takeaway. A datasheet is a contract. The chip keeps its side only if you read your side: the page, the bit, the order, the time, the pin and the revision.

Now press Teach and explain from memory how to wake a chip you have never seen. Then go back to the ZT-1 at the top and wake it in one write.

Read a Datasheet and Reference Manual
Back to Embedded Systems Intro · Back to Gleams