Using the framebuffer

This is a quick note on how to draw to the screen using the framebuffer on Linux. The example below builds on the previous post and runs on a Raspberry Pi equipped with a 320×480 TFT display. The code just fills the entire screen with red color:

First we open “/dev/fb1”, which is the framebuffer assigned to the TFT display (“/dev/fb0” is the primary framebuffer assigned to the HDMI display on the Pi). Next we use two ioctl calls to retrieve information about the display. The first one gives us smem_len, which is the size of the framebuffer in bytes. The second one gives us  xres and yres, which are the screen dimensions in pixels. Next we call mmap to map the framebuffer into memory at an arbitrary address chosen by the kernel and save the address on variable p. The display depth is 16-bits (5 bits for red, 6 bits for green and 5 bits for blue), so p is conveniently declared as uint16_t. Next we fill the entire buffer with value 0xf800, or 1111 1000 0000 0000 in binary: only the first 5 bits corresponding to red are 1. Now that we are done, we unmap the memory and close the device. The display will remain in this state even after the program exits:

Once you know the screen dimensions, it is easy to calculate pixel positions and set the right bytes to show lines, circles, bitmaps, etc.

One thought on “Using the framebuffer

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s