The double buffer technique helps to show smooth images or data updates without flickering or tearing.
0
0
Double buffer technique in Embedded C
Introduction
When drawing graphics on a screen to avoid flickering.
When updating data that is read and written at the same time.
When you want to prepare new data while the old data is still being used.
When working with animations to make them look smooth.
When handling input/output buffers in embedded systems to prevent glitches.
Syntax
Embedded C
char buffer1[SIZE]; char buffer2[SIZE]; char *frontBuffer = buffer1; char *backBuffer = buffer2; // Write to backBuffer // Swap pointers to display new data
You use two buffers: one to show data (front buffer) and one to prepare new data (back buffer).
After preparing data in the back buffer, you swap the buffers to update the display or output.
Examples
This example fills the back buffer with numbers and then swaps the buffers to update the front buffer.
Embedded C
char buf1[100]; char buf2[100]; char *frontBuffer = buf1; char *backBuffer = buf2; // Fill backBuffer with new data for(int i = 0; i < 100; i++) { backBuffer[i] = i; } // Swap buffers char *temp = frontBuffer; frontBuffer = backBuffer; backBuffer = temp;
Using a struct for the buffer, this example prepares pixel data and swaps the buffers.
Embedded C
typedef struct {
int pixels[50];
} FrameBuffer;
FrameBuffer bufferA, bufferB;
FrameBuffer *front = &bufferA;
FrameBuffer *back = &bufferB;
// Prepare back buffer
for(int i = 0; i < 50; i++) {
back->pixels[i] = i * 2;
}
// Swap
FrameBuffer *temp = front;
front = back;
back = temp;Sample Program
This program fills the back buffer with letters, swaps the buffers, and prints the front buffer to show the updated data.
Embedded C
#include <stdio.h> #define SIZE 5 int main() { char buffer1[SIZE] = {0}; char buffer2[SIZE] = {0}; char *frontBuffer = buffer1; char *backBuffer = buffer2; // Prepare backBuffer with data for(int i = 0; i < SIZE; i++) { backBuffer[i] = 'A' + i; // Fill with letters A, B, C, ... } // Swap buffers char *temp = frontBuffer; frontBuffer = backBuffer; backBuffer = temp; // Print frontBuffer content printf("Front buffer content: "); for(int i = 0; i < SIZE; i++) { printf("%c ", frontBuffer[i]); } printf("\n"); return 0; }
OutputSuccess
Important Notes
Always swap pointers, not the whole buffer data, to save time and memory.
Make sure to prepare the back buffer fully before swapping to avoid showing incomplete data.
Summary
Double buffering uses two buffers to avoid flickering and tearing.
Prepare data in the back buffer while the front buffer is displayed.
Swap buffers to update the display smoothly.