A 640 by 480 RGB565 frame is 614,400 bytes, almost five times the SRAM an STM32F407 lets the DMA reach. Plan where every frame lives before the first pixel arrives.
Learn how a small chip catches a picture from a parallel camera, which memory holds it, and when JPEG makes the numbers fit.
Pick a memory, a pixel format and a resolution. Watch whole frames fit, or fail to fit. Then we build, piece by piece, the wires, the capture peripheral, the DMA, the buffers and the JPEG engine.
You need to know that a byte is 8 bits and that a pixel is one dot of a picture. We build the rest from zero.
Built from primary sources, not slides: the STM32F4 reference manual RM0090 (chapter 15, DCMI), ST’s HAL drivers, the OmniVision OV2640 datasheet, Espressif’s esp32-camera driver and ESP-IDF docs, and the OpenMV Cam H7 Plus page. Full list in the Field Guide.
Memory sizes: STM32F407 SRAM1 112 KB plus SRAM2 16 KB, the part the DMA can reach (RM0090 section 2.3); OpenMV Cam H7 Plus 1 MB SRAM and 32 MB SDRAM; ESP32 up to 4 MB of PSRAM (ESP-IDF docs). The JPEG size is illustrative: 0.15 bytes per pixel, which real scenes beat or miss. Firmware, stack and heap also need RAM, so real room is smaller.
Chapter 0
See why a small chip cannot read a camera one byte at a time, and what hardware takes that job
You hold a camera module the size of a coin. A flat ribbon of about twenty wires joins it to your board. You tell the chip: “Give me the picture.” The camera answers by sending one byte on eight wires, over and over, with no pause for you to catch up.
This lesson is about that moment. The camera does not wait. It sets a clock, and bytes leave at the speed of that clock. Your firmware must catch every byte, put each one in the right place, and still have time to do something with the picture.
A pixel is one dot of a picture. A frame is the whole grid of dots, one still image. A video is many frames in a row, so a camera that makes 15 frames per second sends 15 grids every second.
The camera chip in this lesson’s examples is the OmniVision OV2640. Its datasheet says it makes up to 15 frames per second at its largest size, UXGA, which is 1600 by 1200 pixels. The datasheet also lists a pixel clock of 36 MHz for that mode. A pixel clock (PCLK) is a wire that ticks once for every piece of data. At 36 MHz that is 36 million ticks every second.
With eight data wires, each tick carries one byte. So the camera pushes up to 36 million bytes every second into your chip. That is the firehose.
The CPU is the part of the chip that runs your code. Its clock is called HCLK in ST chips. An STM32F407 runs HCLK at up to 168 MHz. Divide 168 by 24 and you get 7. If the camera ticks at 24 MHz, the CPU has seven of its own clock cycles between two bytes.
Seven cycles is not much. Reading a byte from a register, storing it and moving a pointer already takes several. And if you use an interrupt (a signal that makes the CPU stop its work and run a short handler), the chip needs 12 cycles just to enter the handler on a Cortex-M core. The next byte has already come and gone.
Try it. Move the pixel clock and the CPU clock and watch the budget.
Each bar counts CPU clock cycles. The warm bar is the time between two bytes. The pink marks are the fixed cost of an interrupt. Drag the pixel clock up and see which bars win.
Cycle counts are arithmetic: HCLK divided by the pixel clock. The 12 cycle interrupt entry is the Arm Cortex-M3/M4 figure; the Cortex-M7 in the H743 is similar. The exit costs more cycles on top. 54 MHz is the DCMI limit in RM0090 section 15.5.
At 24 MHz the F407 has 7 cycles per byte. That is less than the 12 an interrupt needs to start. Even if you gather four bytes into one 32-bit word first, you get 28 cycles for the whole word. Enter plus exit would eat most of it, with nothing left for your code.
Two blocks do the catching so the CPU does not. The first is a camera interface: a peripheral that watches the camera wires and collects bytes into 32-bit words. On STM32 chips this is the DCMI, the Digital Camera Interface. RM0090 calls it “a synchronous parallel interface able to receive a high-speed data flow from an external 8-, 10-, 12- or 14-bit CMOS camera module.”
The second is DMA, Direct Memory Access. A DMA controller is a small engine that copies data from one place to another without the CPU. You tell it the source, the target and a count. After that it moves each word by itself. If DMA is new to you, Chapter 3 builds it from zero.
That leaves a new problem. DMA writes into memory, and a frame is large. A 640 by 480 picture at 2 bytes per pixel is 614,400 bytes. The F407 has 192 KB of SRAM in total. Where do the bytes go? That question is the hero at the top of this page, and most of the lesson answers it.
We follow the data from the wires to the stored file. Each chapter ends with one measurement you can repeat on a real board.
You will meet two prerequisites on the way. Timers and sampling explains clocks and ticks. Interrupts and DMA goes deeper than our short version. You can read this lesson first and visit them later.
Chapter 1
Read a camera’s wires like a logic analyzer, and see which two settings turn a good frame into blanking noise
Look at the ribbon on a small camera board. Most of its wires do one of three jobs. Some bring power. Some carry settings. A group of eleven or so carry the picture. This chapter is about that last group.
Picture a printer that sends a page to you, one row of dots at a time. It also tells you when a row starts, when the page starts, and when each dot is ready. A camera does the same, using separate wires for each message. That is what “parallel” means here: many wires side by side, each with its own job.
The standard name for this bus is DVP, the Digital Video Port. Here are the signals, with the names that ST uses for the STM32 DCMI pins (RM0090, Table 77 and 78).
| Wire | Direction | What it says |
|---|---|---|
| XCLK | MCU to camera | A clock that powers the sensor. The esp32-camera example uses 20 MHz. |
| PIXCLK (PCLK) | camera to MCU | Ticks once per piece of data. The camera makes it, so the camera sets the pace. |
| D0 to D7 | camera to MCU | One byte per tick. The DCMI can read 8, 10, 12 or 14 wires. |
| HSYNC (HREF on the sensor) | camera to MCU | Marks a line. Start and end of every row. |
| VSYNC | camera to MCU | Marks a frame. Start and end of the whole picture. |
| SCCB (two wires) | both ways | A slow two-wire bus like I2C. It sets the camera’s mode. The picture never uses it. |
RM0090 states that for the DCMI, “only the Slave mode is supported.” The camera is the master of the timing. Your chip listens. If the camera stops its pixel clock, nothing happens at all, and no interrupt tells you why.
Now follow one frame. VSYNC changes at the start of the frame and again at the end. Inside the frame, HSYNC changes for each line. During the active part of a line, every tick of PCLK puts one byte on D0 to D7. Between lines and between frames, the camera pauses. These pauses are called blanking. The data wires still carry something during blanking, but it is not picture.
The DCMI uses the sync wires as blanking markers. RM0090 says that data received while HSYNC or VSYNC is at its active level is ignored. So in DCMI words, active means “blanking, ignore the data.” Many sensors call their line wire HREF and drive it high while pixels are valid. That is the opposite meaning. You tell the DCMI which level is active with the polarity bits, and a wrong choice is a classic bring-up bug.
There is a second timing detail. Each data byte changes shortly after one edge of PCLK. You must sample on the other edge, when the byte holds still. The OV2640 datasheet (Table 10) gives the delay from the PCLK negative edge to new data as 0 to 5 ns. At 36 MHz the clock period is 27.78 ns, so half a period is 13.9 ns. The DCMI has a bit that picks the sampling edge. Pick the same edge as the one that moves the data and you read bytes in mid change.
This is a model of a tiny frame: 3 lines of 6 bytes. Drag the cursor along the clock. Then flip the DCMI settings and see what it captures.
Model, not a recording. The camera here drives its line wire high while pixels are valid, so the matching DCMI setting is active low. Real sensors differ: read the polarity in your camera’s datasheet and confirm it with a scope. Data timing follows the idea in OV2640 Table 10 (new data 0 to 5 ns after the PCLK negative edge).
You may not use all fourteen data inputs. RM0090 gives a firm rule for the spare ones: if fewer than 14 bits are used, “the unused data pins must not be assigned to DCMI interface through GPIO alternate functions.” An 8-bit camera uses D0 to D7. Leave D8 to D13 as ordinary pins.
The most common first failure is silence. The DCMI waits for a frame start that never comes. The symptom is simple: your frame callback never fires, and no error flag rises. The measurement is just as simple. Put a probe on PCLK.
No ticks means the camera has no clock on XCLK, has no power, or sits in power-down. Ticks with no VSYNC pulses mean the sensor has not been told to stream, so its SCCB table has not run. Ticks and VSYNC with no frame callback usually mean a polarity setting hides every frame. The fix follows the measurement: supply XCLK, run the init table, or flip a polarity bit. Each step has one probe and one answer.
Take a VGA frame in RGB565. A line has 640 pixels and each pixel is 2 bytes, so the line is 1,280 bytes. The sensor holds the line wire valid for 1,280 PCLK ticks. A frame has 480 lines, so 480 times 1,280 gives 614,400 bytes. The DCMI counts these ticks and packs them for you.
The totals on the wire are higher than that, because blanking takes extra ticks. This is why the camera datasheet, not your frame size, tells you the true pixel clock you need.
On real hardware. Board: an STM32 Nucleo or Discovery with a DCMI header (or an ESP32-CAM). Probe PCLK, VSYNC and HSYNC with a scope or a cheap logic analyzer. Measure the PCLK frequency, the number of PCLK ticks while HSYNC is valid in one line, and the number of lines between two VSYNC pulses. Compare them with your frame size.
Chapter 2
Turn a colour into bytes in four formats, then multiply to learn how much memory one frame needs
You photograph a bright orange traffic cone. The camera must send that orange to your chip as numbers. How many bytes does it use for one dot of orange? The answer changes your memory plan by a factor of three.
A camera can send the same picture in several pixel formats, which are rules for turning a colour into bytes. Each rule trades size against quality and against how much work your code does later.
Gray8 sends one byte per pixel: a brightness from 0 (black) to 255 (white). It is the smallest uncompressed format. Machine vision often uses it, because many algorithms only need brightness.
RGB565 packs a colour into 16 bits. RM0090 describes it as “a pixel coded in 16 bits (5 bits for blue, 5 bits for red, 6 bits for green)” that “takes two clock cycles to be transferred.” Green gets 6 bits because the eye is most sensitive to green. A pixel costs 2 bytes. A screen can show it directly.
YUV422 (also written YCbCr 4:2:2) stores brightness (Y) for every pixel but colour (Cb and Cr) for every second pixel. Two pixels share one pair of colour bytes, so the average is still 2 bytes per pixel. The trick works because the eye sees brightness detail more sharply than colour detail. The DCMI lists “YCbCr 4:2:2 progressive video” as a supported format.
Raw Bayer is what the sensor measured before any colour processing. Each pixel sits behind a red, green or blue filter and gives one number. The OV2640 can output 8-bit or 10-bit raw. At 8 bits it is the same size as Gray8, but your code must rebuild the colour.
The fifth option is JPEG. Here the camera compresses the frame before sending it. The size is no longer fixed. Chapter 7 covers it in full.
Uncompressed formats have a fixed number of bytes per pixel. So the frame size is a product.
640 × 480 × 2 = 614,400 bytes (VGA, RGB565)
| Size | Pixels | Gray8 | RGB565 | RGB888 |
|---|---|---|---|---|
| QVGA 320 x 240 | 76,800 | 76,800 | 153,600 | 230,400 |
| VGA 640 x 480 | 307,200 | 307,200 | 614,400 | 921,600 |
| SVGA 800 x 600 | 480,000 | 480,000 | 960,000 | 1,440,000 |
| UXGA 1600 x 1200 | 1,920,000 | 1,920,000 | 3,840,000 | 5,760,000 |
The OV2640 does not output RGB888; its listed formats are YUV, RGB565 or 555, raw RGB and compressed data. RGB888 appears only after your code or a helper block converts a frame, so the table shows what that costs.
Wider raw formats cost more than their bit count suggests. RM0090 says that with 10 data wires the DCMI “stores them as the 10 least significant bits of a 16-bit word,” and builds a 32-bit word every two pixel clocks. So a 10-bit raw pixel takes 2 bytes of memory, not 1.25. A VGA frame of 10-bit raw is 614,400 bytes, the same as RGB565. Check the width before you trust a bytes-per-pixel guess.
A 16-bit pixel travels as two bytes, one per PCLK tick. Which one comes first? The camera decides, and most sensors let you choose with a register. The DCMI then packs bytes by a fixed rule. RM0090 says the first captured byte lands in the lowest position of the 32-bit word, and only little-endian is supported.
If the camera sends the high byte first, then your code reading the memory as 16-bit numbers sees the two bytes swapped. The result is not noise. It is a clean picture with the wrong colours: a neat, confident error that wastes hours. Test it below with the cone colour.
Set a colour with the three sliders. The first swatch is the true colour. The second is what RGB565 keeps. The third is what your code decodes if the two bytes arrive in the wrong order.
Arithmetic you can check by hand. RGB565 keeps the top 5 bits of red, the top 6 of green and the top 5 of blue. The YUV values use the common full-range BT.601 weights (Y = 0.299 R + 0.587 G + 0.114 B); sensors differ in range and byte order, so read your datasheet.
For the orange (255, 128, 0) the work goes like this. Red 255 keeps its top 5 bits, 31. Green 128 keeps its top 6 bits, 32. Blue 0 stays 0. Packed, that is 31 × 2048 + 32 × 32 + 0 = 0xFC00. The two bytes are FC and 00. Swap them and the pixel reads 0x00FC, which decodes to a deep blue, (0, 28, 232). Same bytes, wrong order, wrong colour.
On real hardware. Board: an ESP32-CAM or a Nucleo with an OV2640. Capture one frame of a plain red card in RGB565. Dump the first 8 bytes. Red should read 0xF8 0x00 or 0x00 0xF8 depending on byte order. That one reading tells you the order your camera and code use.
Chapter 3
See how DCMI turns bytes into words, how DMA carries them away, and how a short stall costs a whole frame
Imagine a bucket under a tap. Water runs in at a steady rate that you cannot change. A helper empties the bucket into a barrel. As long as the helper keeps up, nothing spills. If the helper is busy for too long, the bucket overflows and water is lost.
The DCMI, the helper and the barrel work just like that. The tap is the camera. The bucket is a tiny queue inside the DCMI. The helper is the DMA. The barrel is your frame buffer in RAM. This chapter shows how small the bucket is.
The DCMI does not hand your code single bytes. It collects them into a 32-bit word, which is four bytes in one piece. RM0090: “The data are packed into a 32-bit data register (DCMI_DR) and then transferred through a general-purpose DMA channel.” With 8 data wires, the interface “takes four pixel clock cycles” to build one word. The first byte lands in the lowest position and the fourth in the highest.
When a word is complete, the DCMI raises a DMA request. RM0090 section 15.5.1: “A DMA request is generated each time the camera interface receives a complete 32-bit data block in its register.” At 24 MHz that is one request every 4 divided by 24 million seconds, or 166.7 ns.
A DMA controller is a small copy engine on the chip. You give it three facts. Where to read from: the DCMI data register, which has a fixed address. Where to write to: your buffer in RAM. How many items to move. After that, each time the DCMI raises a request, the DMA reads one word and writes it to the buffer. Then it moves its write pointer forward by four bytes and counts down.
The CPU is free the whole time. It only hears from the DMA when the count reaches zero, or when something goes wrong. On the STM32F4 the DCMI request is wired to DMA2, stream 1, channel 1 (RM0090, Table 44), and the HAL driver tells you to use exactly that. For the full picture of DMA and interrupts, see the interrupts and DMA lesson.
Between the DCMI register and the DMA there is a FIFO (first in, first out queue). RM0090 section 15.5.7: “A four-word FIFO is implemented to manage data rate transfers on the AHB.” Four words is 16 bytes. That is all the slack you have.
The manual then warns: “There is no overrun protection to prevent the data from being overwritten if the AHB interface does not sustain the data transfer rate. In case of overrun or errors in the synchronization signals, the FIFO is reset and the DCMI interface waits for a new start of frame.” An overrun means new data arrived before old data was read. In snapshot mode RM0090 adds: “In case of an overrun, the frame is lost and the CAPTURE bit is cleared.”
So a short delay costs you a whole picture. Anything that makes the DMA wait longer than the bucket lasts is fatal for that frame. A busy bus, a slow external RAM, an LCD that reads memory, or another DMA stream can all cause such a wait.
The line is how many of the four FIFO slots are full. At the dashed marker the bus stalls for the time you choose. The camera does not pause. Find the stall length that just overflows.
A model built from the RM0090 facts: 4 bytes per word at 8 bits, a 4-word FIFO, and a drain that is instant when the bus is free. Real FIFO behaviour adds a word in flight, so treat the limit as about four word times. 54 MB/s is the data rate RM0090 gives for the DCMI, and its minimum PIXCLK period is 2.5 HCLK periods.
Take PIXCLK at 24 MHz. One word takes 4 / 24 MHz = 166.7 ns. The FIFO holds four words, so it lasts about 4 × 166.7 = 667 ns. A stall of 400 ns fills 2.4 words and recovers. A stall of 800 ns needs 4.8 words of room and the FIFO overruns. Double the pixel clock to 48 MHz and the same bucket lasts only 333 ns.
Two more limits hide in the manual. The DCMI clock domain needs PIXCLK slower than HCLK: “the minimum PIXCLK period must be higher than 2.5 HCLK periods.” At 168 MHz that gives at most 67.2 MHz. And the interface is rated for “up to 54 Mbytes/s.” The lower of the two wins.
With the HAL, you pass the settings from Chapter 1 as one structure. These field names come from ST’s stm32f4xx_hal_dcmi.h.
chdcmi.Instance = DCMI; hdcmi.Init.SynchroMode = DCMI_SYNCHRO_HARDWARE; /* use HSYNC and VSYNC wires */ hdcmi.Init.PCKPolarity = DCMI_PCKPOLARITY_RISING; /* pick the edge where data holds still */ hdcmi.Init.VSPolarity = DCMI_VSPOLARITY_HIGH; /* active level = blanking */ hdcmi.Init.HSPolarity = DCMI_HSPOLARITY_LOW; hdcmi.Init.CaptureRate = DCMI_CR_ALL_FRAME; /* every frame (or every 2nd, 4th) */ hdcmi.Init.ExtendedDataMode= DCMI_EXTEND_DATA_8B; /* D0..D7: 4 PIXCLK ticks per word */ hdcmi.Init.JPEGMode = DCMI_JPEG_DISABLE; HAL_DCMI_Init(&hdcmi);
On real hardware. Board: STM32F4 or H7 Discovery with a camera. Enable the DCMI overrun interrupt (DCMI_IT_OVR) and toggle a GPIO in its handler. Raise the pixel clock until the pin toggles, then switch the buffer between internal SRAM and external RAM and repeat. The change in the PCLK where overrun starts is your measured margin.
Chapter 4
Choose how a frame reaches RAM, split a large frame across DMA transfers, and find the line where a shared buffer tears
Picture a whiteboard. You write a new page of text from top to bottom, line by line. A friend starts reading the board halfway through your writing. Her top lines are from the new page, and her bottom lines are still from the old one. She reads a sentence that never existed.
That is tearing: a picture made of parts of two different frames. It happens whenever one side writes a buffer while the other side reads it. The camera never stops writing, so this chapter is about the rules that keep a reader safe.
The DCMI has two capture modes (RM0090, section 15.5.4). In snapshot mode, one frame is captured. You set the CAPTURE bit, the interface waits for the start of a frame, grabs a whole frame, then clears CAPTURE by itself and raises the frame interrupt. In continuous mode, it keeps grabbing frame after frame until you clear CAPTURE, and then it finishes the frame in progress.
You can also thin the stream. In continuous mode the capture-rate bits keep every frame, every second one, or one in four (the HAL names are DCMI_CR_ALL_FRAME, DCMI_CR_ALTERNATE_2_FRAME and DCMI_CR_ALTERNATE_4_FRAME). Snapshot mode gives you control: the camera runs, you grab one frame when ready. Continuous mode gives you throughput, but you must have somewhere to put the next frame the moment this one ends.
A DMA stream counts items in a register that holds 1 to 65,535 (RM0090, section 10.3: the number of data items is “software-programmable from 1 to 65535”). For the DCMI the items are 32-bit words. So one plain transfer holds at most 65,535 words, which is 262,140 bytes.
A QVGA RGB565 frame is 153,600 bytes, or 38,400 words. It fits. A VGA RGB565 frame is 614,400 bytes, or 153,600 words. It does not. ST’s HAL handles this with the DMA double buffer mode, where the stream has two memory pointers and flips between them. In HAL_DCMI_Start_DMA the code halves the transfer size until it is at most 65,535:
153,600 → 76,800 (2 chunks) → 38,400 (4 chunks)
The frame becomes four chunks of 38,400 words, and the second memory pointer starts at the buffer address plus 4 × 38,400 bytes. Each chunk end re-aims the pointers, so the transfer runs on without you. The halving uses integer division, so pick a word count that halves cleanly, or crop the window until it does.
cstatic uint8_t frame[640 * 480 * 2] __attribute__((aligned(32))); /* 614,400 bytes, DMA reachable RAM */ uint32_t words = sizeof(frame) / 4; /* 153,600 words: the HAL splits it */ HAL_DCMI_Start_DMA(&hdcmi, DCMI_MODE_SNAPSHOT, (uint32_t)frame, words); void HAL_DCMI_FrameEventCallback(DCMI_HandleTypeDef *h) { /* one full frame is in RAM */ frame_ready = 1; }
Sometimes the frame does not need to live anywhere. A screen driver wants lines. A JPEG engine wants blocks of lines. A small tracker wants a few rows. In those cases you can run the DMA in a circular or double-buffer pattern over a line buffer: a small array that holds one line or a few. The DMA fills half while your code or another DMA empties the other half.
For VGA RGB565 one line is 1,280 bytes. Two of them take 2,560 bytes instead of 614,400. The price is time. At 24 MHz pixel clock, 1,280 bytes arrive in 53.3 µs of active data. In that window you must finish with the line you hold, or the next line will overwrite it. That is the same deadline idea as the FIFO, only slower.
Now the whiteboard on a time chart. The DMA writes line 0 to line H of frame k, one frame period long. Your reader reads line 0 to line H of the same buffer, one pass long. Each line holds the newest frame written to it so far. If the reader runs at the same speed as the camera, it stays behind the writer and sees one clean frame. Any other speed makes the two paths cross, and a tear appears at the crossing.
Left: time runs across, line number runs down. Coloured diagonals are the camera writing frames. The teal diagonal is your reader. Right: which frame each line came from. Change the buffers, the reader speed and the start time.
A timing model with 24 lines so the shape is visible; a real VGA frame has 480 lines. The camera writes line j of frame k at time k + j/24 frame periods. Reader speed 1.0 means it reads exactly as fast as the camera writes.
Set the reader to 1.00 and the tear vanishes. But two separate clocks never stay matched. That is why serious designs use two buffers. The DMA fills buffer A while you read buffer B, and at each frame end you swap. With two buffers, a reader that finishes within one frame period never tears. A slower reader still can, just later. The cost is one more buffer in RAM and up to one frame period of extra delay.
On real hardware. Board: an STM32 Discovery with a DCMI camera and an LCD. Fill the screen from the single capture buffer, then wave a bright card across the lens. A tear shows as a sideways cut in the card. Add the second buffer and swap in the frame callback, and the cut goes away.
Chapter 5
Plan a frame buffer against the real memory map, avoid the one RAM the DMA cannot see, and keep the CPU from reading stale pixels
You tape a map of your chip on the wall. It shows several blocks of RAM, each with its own address, size and rules. You must put a 614,400 byte frame somewhere on that map. Pick wrong and one of three things happens. The frame does not fit. The DMA cannot reach it. Or the CPU reads old data that looks fresh.
Start with arithmetic. The STM32F407 has SRAM1 of 112 KB and SRAM2 of 16 KB that the DMA can reach. That is 128 KB, or 131,072 bytes. Test the frames from Chapter 2 against it.
QVGA Gray8: 76,800 B → 1 frame (59% of the RAM)
QVGA RGB565: 153,600 B → does not fit (1.2 times the RAM)
QQVGA RGB565: 38,400 B → 3 frames
So on this chip even a small colour picture does not fit. You have four options. Use fewer pixels (crop or a smaller size). Use fewer bytes per pixel (Gray8). Do not store whole frames (line buffers, Chapter 4). Or add RAM. A related chip, the F429, has an SRAM3 block of 64 KB, which RM0090 says is “accessible by all AHB masters,” and it can also drive external SDRAM through its FMC.
The F407 has a fourth block: 64 KB of CCM (core coupled memory), mapped at address 0x1000 0000. It is fast for the CPU, which is why designers like it. But RM0090 says it is “not part of the bus matrix and can be accessed only through the CPU.” No DMA can read or write it. If you place a camera frame buffer there, the DMA has no path to it, and the frame never arrives. This is a classic mistake, because the linker happily puts large arrays into the biggest free block.
Three real boards show the range. The OpenMV Cam H7 Plus uses an STM32H743 with 1 MB of SRAM and adds 32 MB of external SDRAM, 32 bits wide at 100 MHz, which its page rates at 400 MB/s. Its camera sits on an 8-bit parallel port. At those numbers a 5 MB frame is easy, and the camera data (24 MB/s at 24 MHz) uses a small part of the memory bandwidth.
The ESP32 can map up to 4 MB of PSRAM into its address space (ESP-IDF docs). Two cautions from the same docs apply to frames. While the flash cache is off (for example when writing flash), PSRAM cannot be read or written at all. And for large chunks above 32 KB, “the cache can be insufficient, and speeds will fall back to the access speed of the external RAM.” The esp32-camera README adds that YUV or RGB frames “put a lot of strain on the chip because writing to PSRAM is not particularly fast,” so image data can go missing, mostly when Wi-Fi is on. It advises capturing JPEG.
| Memory | Size and place | Notes for frames |
|---|---|---|
| STM32F407 SRAM1 + SRAM2 | 112 KB + 16 KB, on chip | DMA can reach it. About 128 KB for buffers. |
| STM32F407 CCM | 64 KB at 0x1000 0000 | CPU only. Never a DMA target. |
| STM32H743 SRAM (OpenMV H7 Plus) | 1 MB, on chip | Roomy for line buffers and small frames. Has a data cache. |
| External SDRAM | 32 MB, 100 MHz, 32 bits (OpenMV H7 Plus) | 400 MB/s rated. Holds many large frames. |
| ESP32 PSRAM | up to 4 MB mapped | Slow writes for raw frames. Offline during flash writes. |
Placement is a decision you should be able to see in the source. Put DMA buffers in a named linker section, or declare them with an alignment attribute, and add a comment that says which memory you meant. When the next person moves a variable, the link step or a size check should fail loudly, not capture silence.
Chips with a CPU data cache, such as the Cortex-M7 in the STM32H7, add a quiet trap. The DMA writes new pixels into RAM, but the CPU may still hold old copies of those addresses in its cache. When your code reads the frame, the cache can answer with old data. The result is a blend of old and new lines. No error is raised.
The fix has two parts. Before the CPU reads a buffer the DMA wrote, invalidate those cache lines, which tells the cache to forget them. Before the DMA reads a buffer the CPU wrote, clean them, which pushes the CPU’s copy out to RAM. CMSIS provides SCB_InvalidateDCache_by_Addr() and SCB_CleanDCache_by_Addr(). Align buffers to the 32-byte cache line, or neighbouring variables get invalidated too.
Choose where the DMA buffer lives. Press Capture a frame. The right panel is what your code reads back. On a chip with a data cache, try the two toggles.
A model. CCM behaviour follows RM0090 (CPU access only). The cache toggles model a Cortex-M7 style data cache: stale lines mix an older frame into the read-back; invalidating removes them. The F407 has no data cache, so there only the CCM trap applies.
On real hardware. Board: STM32F4 Discovery or a Nucleo H7. Put the buffer first in CCM, then in SRAM, and read the DCMI error flags and the first 16 bytes after a snapshot. On the H7, enable the data cache and compare the first line before and after a call to SCB_InvalidateDCache_by_Addr().
Chapter 6
Size a pool of frame buffers against a slow consumer, and choose between old frames and fresh ones
A busy kitchen sends out plates on a fixed beat. One waiter carries them, and some trips take longer than the beat. The kitchen has a few trays on the pass. When every tray is full, the next plate has to go in the bin, or the oldest plate gets thrown out to make room. Which one do you throw away?
Your camera is the kitchen. Your code that sends, shows or analyses a frame is the waiter. The trays are frame buffers. The number of trays and the rule for a full pass decide your frame rate and how old each frame is.
The Espressif esp32-camera driver shows both ways clearly. Its README describes them. With one frame buffer, “the driver will wait for the current frame to finish (VSYNC) and start I2S DMA. After the frame is acquired, I2S will be stopped and the frame buffer returned to the application.” You get control, but it takes longer to get each frame, because the camera idles while you work.
With two or more buffers, “I2S is running in continuous mode and each frame is pushed to a queue that the application can access.” The README says this “allows for double the frame rate,” and asks you to use it only with JPEG, because the strain on CPU and memory is higher.
The API is a loop of two calls: take a buffer, give it back. Until you give it back, the driver cannot reuse it.
ccamera_config_t cfg = { .pixel_format = PIXFORMAT_JPEG, .frame_size = FRAMESIZE_SVGA, .jpeg_quality = 10, /* 0-63, lower means better quality */ .fb_count = 2, /* two trays: continuous capture */ .fb_location = CAMERA_FB_IN_PSRAM, .grab_mode = CAMERA_GRAB_WHEN_EMPTY, /* or CAMERA_GRAB_LATEST */ /* ...pin numbers and xclk_freq_hz = 20000000 omitted... */ }; esp_camera_init(&cfg); for (;;) { camera_fb_t *fb = esp_camera_fb_get(); /* waits for a finished frame */ send_or_process(fb->buf, fb->len); /* slow work happens here */ esp_camera_fb_return(fb); /* tray goes back to the camera */ }
Every tray is a whole frame. Two SVGA RGB565 trays cost 2 × 960,000 = 1,920,000 bytes. That is why the driver lets you choose with fb_location between PSRAM and internal DRAM, and why JPEG is the format it recommends for a pool of two or more. Two JPEG trays of 64 KB cost only 128 KB.
Other stacks use the same model with different names. The Zephyr driver for the STM32 DCMI works with video buffers that the application enqueues and dequeues. In its continuous mode it copies each finished frame out of the DMA buffer with memcpy into the application’s buffer. That copy costs one extra pass over the frame, but it frees the DMA buffer at once for the next capture. Its snapshot mode has a timeout; the devicetree binding sets a default of 1000 ms.
The header names two grab modes. CAMERA_GRAB_WHEN_EMPTY “fills buffers when they are empty,” uses fewer resources, and warns that “first fb_count frames might be old.” New frames are lost when all buffers are busy. CAMERA_GRAB_LATEST keeps “the last fb_count frames” in the queue, so the oldest waiting frame is replaced, except when there is only one buffer.
So WHEN_EMPTY favours completeness of the early frames. LATEST favours freshness. A robot that steers by what the camera sees wants LATEST: a frame that is three periods old is worse than none. A recorder that must not skip the first frame wants WHEN_EMPTY.
Take 15 frames per second, so one frame every 66.7 ms. Your processing takes 100 ms. One buffer: capture takes a frame period, then you hold the buffer for 100 ms, then the next capture can only start at the next VSYNC. Each cycle takes 66.7 + 100 rounded up to the next 66.7 ms boundary, which is 200 ms, so you see 5 frames per second. Two buffers: the camera keeps writing into the second tray while you work, and you can take about 1 frame in every 1.5 periods, up to 10 frames per second. The simulation below runs exactly this rule.
Now the failure mode. The symptom is a video that lags: the picture on your screen shows what happened a second ago. The measurement is the age of a frame when your work starts on it, which you get by comparing the frame’s capture time with the clock when you take it. If the age grows with the buffer count, the queue is full of old frames. The fix is either faster work, fewer buffers, or the LATEST mode. Try each in the simulation below and watch the average wait.
One shared time axis. The top row is camera frames: green if you got them, red if dropped. The lower row is your processing. Change the trays, the full-pass rule, the camera rate and your processing time.
A discrete model of the driver rules described in the esp32-camera README and header, over 36 frame periods. It ignores DMA start-up and cache effects. Age is the wait of a frame in the queue before your work starts on it.
On real hardware. Board: ESP32-CAM or an ESP32-S3 camera board. Count frames returned by esp_camera_fb_get() over 10 seconds for fb_count of 1, 2 and 3, with one fixed work delay. Compare the counts and the timestamps. The ratio shows how much of your loss was idle camera time.
Chapter 7
Learn what JPEG throws away, why its size is not known in advance, and how to size a buffer that must hold it
A VGA frame in RGB565 is 614,400 bytes. A photo of the same scene on a phone is a file of maybe 40 KB. The picture looks nearly the same. Where did 570 KB go? JPEG removed what your eyes would not miss.
For a small chip, this is the cure for most of the memory problems in Chapter 5. A compressed frame is about ten times smaller, which is why the esp32-camera README tells you to capture JPEG. But the cure brings a new problem: nobody knows the size of the frame before it arrives.
First, JPEG splits the picture into square blocks of 8 by 8 pixels. Second, it converts each block into frequencies using the DCT, the discrete cosine transform. A smooth block has one large number (its average brightness) and tiny others. A block with sharp edges has many large numbers. Third comes quantization: it divides each frequency by a step size and rounds. Small values become zero. This is the main step that loses information (cutting the colour detail is the other), and the quality setting controls how big the steps are. Fourth, an entropy coder writes the numbers using short codes for common values and long codes for rare ones.
Before these steps, JPEG usually shrinks the colour. It works in Y (brightness) and Cb, Cr (colour). With 4:2:0 subsampling, one pair of colour values covers a 2 by 2 square of pixels. The unit it then codes is the MCU (minimum coded unit): 16 by 16 pixels, made of four 8 by 8 brightness blocks plus one Cb block and one Cr block.
The OV2640 datasheet shows a compression engine inside the sensor with exactly three blocks: DCT, QZ (quantization) and an entropy encoder. So a sensor like it can hand your chip a finished JPEG on the same eight data wires.
A blue sky gives blocks of near-zero numbers, so the coder writes almost nothing. A brick wall or a leafy tree gives large numbers in every block. The same camera, the same quality setting and the same size can give 10 KB for one frame and 80 KB for the next. The quality setting changes the size, but the scene changes it too.
This shapes your firmware. You cannot compute the buffer size from the resolution. You choose a worst case and check at run time. If a frame needs more bytes than your buffer, it is cut off. A cut JPEG has no end marker, and most decoders refuse it or show a grey smear.
With the JPEG bit set in DCMI_CR, the interface changes how it reads the sync wires. RM0090: “VSYNC signal is used to start the capture while HSYNC serves as a data enable signal.” The camera sends the file in packets, with gaps whose length depends on the image. Two limits apply. The crop feature and embedded sync codes cannot be used in JPEG mode. And if the file length is not a multiple of 4, the last word is padded with zeros, so you find the real end by looking for the JPEG end marker, the bytes 0xFF 0xD9.
You also do not know the DMA count in advance. A common method is to give the DMA a buffer sized for the worst case, wait for the frame interrupt, and read how many words the DMA has left. The used length is the buffer size minus that remainder.
Some chips add a JPEG block to do the DCT work, so the CPU does not. ST’s H7 HAL driver describes it. For encoding, “the JPEG peripheral input should be organized in YCbCr MCU blocks. It is up to the application to perform the necessary RGB to YCbCr MCU blocks transformation before feeding the JPEG peripheral.” The quality parameter runs from 1 to 100, where higher means better quality and bigger files. The count of MCUs is a simple division: for 4:2:0 each MCU covers 16 by 16 pixels.
640 / 16 = 40 columns, 480 / 16 = 30 rows, 40 × 30 = 1,200 MCUs (the register holds 1,199)
In raw terms, one 4:2:0 MCU holds 6 blocks of 64 bytes, which is 384 bytes. Times 1,200 MCUs gives 460,800 bytes going in for a VGA frame. That is the size of the data you must feed it, before it shrinks.
cJPEG_ConfTypeDef conf = { .ColorSpace = JPEG_YCBCR_COLORSPACE, .ChromaSubsampling = JPEG_420_SUBSAMPLING, /* 16 x 16 pixel MCUs */ .ImageWidth = 640, .ImageHeight = 480, .ImageQuality = 75 /* 1..100, higher = better = bigger */ }; HAL_JPEG_ConfigEncoding(&hjpeg, &conf); HAL_JPEG_Encode_DMA(&hjpeg, ycbcr_mcu_in, 460800, jpeg_out, 64 * 1024); /* out buffer = your worst case */
The picture is a blocky preview of the chosen quality. The bar compares the JPEG size with your output buffer. Raise the busyness of the scene and see what a fixed buffer does.
Illustrative model, not a measurement: bits per pixel = (0.25 + 3.2 × busyness) × (0.25 + 1.75 × (quality / 100)2). Real sizes depend on the scene and the encoder; measure your own frames. Quality here follows the ST H7 HAL (1 to 100, higher is better). The esp32-camera driver uses 0 to 63 with lower meaning better quality.
On real hardware. Board: ESP32-CAM or an STM32H7 board with a JPEG sensor. Log the JPEG length of 100 frames while you walk the camera from a blank wall to a busy shelf. Plot the minimum, mean and maximum. Set your buffer above the maximum plus a safety margin.
Chapter 8
Match six classic camera faults to what you see, the one probe that proves each, and the one-line fix
You wire up the camera, flash the board, and the screen shows a picture. It is wrong. Colours are odd, or the bottom is missing, or the whole thing leans like a tower in a storm. You could change settings at random for an evening. Or you can learn that each fault leaves a different fingerprint.
The idea of this chapter is to treat the picture as a measurement. Each fault from Chapters 1 to 7 bends the image in its own way. If you know the bends, you know where to probe.
Judging a live scene is hard. You do not know what the right answer looks like. So first ask the sensor for a test pattern. The OV2640 has a colour bar test pattern: in register COM7 (address 0x12), bit 1 turns it on. Colour bars are fixed, sharp and easy to check: eight clean vertical stripes. If the stripes arrive wrong, the fault is in the wiring, the DCMI or the memory, not in the lens or the light. The sensor bring-up lesson covers configuring a sensor over SCCB, which is how you switch this bit on.
| You see | Likely cause | Measure | Fix |
|---|---|---|---|
| Random speckles, flickering colours | Sampling on the wrong PCLK edge (Chapter 1) | Scope PCLK against D0. Is D0 changing at your sample edge? | Flip the DCMI pixel clock polarity bit |
| Clean picture, wrong colours | Byte order swapped (Chapter 2) | Dump the first bytes of a plain red card | Swap in the sensor register or in code |
| Bottom of the picture missing | Buffer or DMA count too small (Chapters 4 and 5) | Compare DMA words with W × H × B / 4 | Enlarge the buffer or crop |
| Top is new, bottom is an old frame | Overrun, FIFO reset (Chapter 3) | Overrun flag, and a GPIO toggle in its handler | Cut bus contention, lower PCLK, move the buffer |
| Straight edges lean | Line length your code assumes differs from the camera’s | Count PCLK ticks while HSYNC is valid | Set the real width and stride |
| Fresh picture mixed with old lines | Stale cache lines (Chapter 5) | Read the first line before and after cache invalidate | Invalidate before reading |
Notice what is missing from the table: guessing. Every row names one probe. A scope, a logic analyzer, a flag, a byte dump or a counter gives a number, and the number points to the fix.
Order matters because each step depends on the one before. A lean picture and a missing clock look equally bad on a screen, but they sit at opposite ends of the list.
Left: what the camera saw. Right: what your code got. Choose a fault, then read the symptom, the probe and the fix.
A rendered model of each fault on a 64 by 48 test picture. The byte swap uses the exact RGB565 rule from Chapter 2. The other faults are drawn from their mechanism (noise, missing rows, stale rows, a stride error), not captured from a camera.
When several faults fit one symptom, test the cheapest cause first. A byte dump costs a minute. A scope probe costs ten. A change to the memory layout costs an afternoon. Work down that list and write down each result. A bring-up log with three numbers per attempt (clock frequency, ticks per line, bytes per frame) will save you from running the same test twice.
A VGA RGB565 line is 1,280 bytes. Suppose your display code assumes 1,296 bytes per line, because you added 16 bytes of padding for another project. Each line then starts 16 bytes, or 8 pixels, further along than it should. After 80 lines the shift equals the full picture width. Vertical edges become diagonals and the whole picture looks like it is sliding sideways. The fingerprint is a constant shift per line. A constant shift per line means a stride error, not noise and not the camera.
An overrun is the fault that looks most like a software bug. The top part of the picture is new, the lower part is whatever was in the buffer before, and the cut falls on a different line each time. That moving cut is the clue. A stride error or a small buffer cuts at the same line every frame. An overrun cuts where the stall happened, which depends on what the bus was doing. If the cut moves, turn on the overrun interrupt and look at the bus.
VGA RGB565 needs 614,400 bytes. Suppose your array holds 430,080 bytes because you copied the size from a QVGA project and scaled it wrong. 430,080 / 1,280 bytes per line gives 336 lines. The picture should have 480. So 144 lines, the bottom 30 percent, are missing. The number 336 is your fingerprint. It tells you the array size, not the camera, is at fault.
On real hardware. Board: STM32 Discovery or ESP32-CAM with an OV2640. Enable the colour bar pattern and capture one frame. Check byte 0 of every line, the number of lines, and the first eight bytes. Write the three numbers in your bring-up log. You will use them again.
Chapter 9
Keep the numbers, the checklist, the core code and the sources for the next time a camera shows up on your bench
A parallel camera sets its own pace with a pixel clock. The DCMI turns bytes into 32-bit words and the DMA carries them to RAM, but the FIFO between them holds only four words. So the bus must never stall for long. You plan where the frame goes before you write any code, and you hand each buffer to exactly one owner at a time. JPEG shrinks the frame about tenfold, at the price of a size you cannot predict.
| Quantity | Value | Source |
|---|---|---|
| DCMI data width | 8, 10, 12 or 14 bits | RM0090 15.2 |
| Bytes to build a word (8-bit) | 4 PIXCLK cycles per 32-bit word | RM0090 15.5.2 |
| DCMI FIFO | 4 words, no overrun protection | RM0090 15.5.7 |
| Minimum PIXCLK period | more than 2.5 HCLK periods | RM0090 15.4 |
| Rated data rate | up to 54 Mbytes/s | RM0090 15.5 |
| DMA items per transfer | 1 to 65,535 (262,140 bytes of words) | RM0090 10.3 |
| DCMI DMA request | DMA2 stream 1, channel 1 | RM0090 Table 44, HAL |
| Largest non-JPEG input | 2048 x 2048 pixels | RM0090 15.6.1 |
| Crop width unit | multiple of 4 pixel clocks | RM0090 15.5.5 |
| F407 DMA-reachable SRAM | 112 KB + 16 KB; CCM 64 KB is CPU only | RM0090 2.3 |
| OV2640 rates | UXGA 15 fps, SVGA 30 fps, CIF 60 fps; PCLK 36 MHz at 15 fps UXGA (27.78 ns) | OV2640 datasheet |
| OpenMV Cam H7 Plus | 1 MB SRAM, 32 MB SDRAM at 100 MHz (400 MB/s) | OpenMV product page |
| ESP32 PSRAM | up to 4 MB mapped; large accesses beyond 32 KB run at PSRAM speed | ESP-IDF external RAM guide |
| JPEG quality scales | ST HAL 1 to 100, higher is better; esp32-camera 0 to 63, lower is better | HAL header, esp_camera.h |
| JPEG MCU size | 4:2:0 is 16 x 16, 4:2:2 is 16 x 8, 4:4:4 is 8 x 8 pixels | ST H7 HAL driver |
c/* STM32F4, DCMI + DMA2 stream 1, two VGA RGB565 buffers in DMA-reachable SRAM (not CCM). */ #define W 640 #define H 480 #define WORDS ((W * H * 2) / 4) /* 153,600; HAL splits it below 65,535 */ static uint8_t buf[2][W * H * 2] __attribute__((aligned(32))); static volatile int ready = -1, cur = 0; static volatile uint32_t overruns; static void grab(void) { HAL_DCMI_Start_DMA(&hdcmi, DCMI_MODE_SNAPSHOT, (uint32_t)buf[cur], WORDS); } void HAL_DCMI_FrameEventCallback(DCMI_HandleTypeDef *h) { ready = cur; cur ^= 1; /* hand this buffer to the reader */ grab(); /* the camera writes the other one */ } void HAL_DCMI_ErrorCallback(DCMI_HandleTypeDef *h) { overruns++; /* the frame is lost; try again */ grab(); } int main(void) { /* clocks, GPIO alternate functions, DMA2 stream 1, HAL_DCMI_Init, sensor init over SCCB ... */ grab(); for (;;) { if (ready >= 0) { int r = ready; ready = -1; /* Cortex-M7 only: SCB_InvalidateDCache_by_Addr((uint32_t *)buf[r], sizeof buf[r]); */ use_frame(buf[r]); /* must finish within about one frame period */ } } }
Three exercises make this stick. First, take any camera board and write down, for your chosen size and format, the frame bytes, the DMA word count and the time to receive one frame at your pixel clock. Second, create each fault of Chapter 8 on purpose, one at a time, and record its fingerprint. Third, change the buffer count and the grab mode and measure the frame rate you receive. A number you measured yourself beats ten you read.
This lesson covers the small, cheap end: a parallel camera on a microcontroller. Bigger systems use a serial link (MIPI CSI-2) into an image signal processor and a Linux buffer queue. Those are different jobs with the same ideas: a clock the camera owns, a deadline for the receiver, a pool of buffers and a rule for dropped frames. Lessons on those topics are planned and are named here in words only.
No slides here. Every number comes from a primary source opened while writing. STM32F4 reference manual RM0090, chapter 15 (DCMI), chapter 10 (DMA) and section 2.3 (memory map); I read the text through a public mirror. ST HAL drivers: stm32f4xx_hal_driver (DCMI) and stm32h7xx_hal_driver (JPEG). The OmniVision OV2640 datasheet. Espressif esp32-camera README and header, and the ESP-IDF external RAM guide. The OpenMV Cam H7 Plus page. The Zephyr st,stm32-dcmi binding. ST application note AN5020 is good further reading; I could not open it, so no number here depends on it.
What is a model: every device on this page. The wire diagram, FIFO, tearing, buffer queue, JPEG size and fault pictures are small simulations of the mechanisms above, not recordings of a real board. Each chapter names a board and a measurement to repeat.
Now press Present or Teach and explain, from memory, how one byte travels from a camera pin to a stored frame, and what limits it at each stop. Then go back to the planner at the top, choose a memory and a format of your own, and explain why the numbers fit or fail.