11 | USB Cameras: Capture a Frame with V4L2

Identify the capture node, list its supported formats, and capture an image through memory-mapped streaming.

1. Identify the USB camera and its capture node

Connect the camera and install v4l-utils.

lsusb
lsusb -t
v4l2-ctl --list-devices

lsusb -t shows the USB interface driver. A USB Video Class camera typically uses uvcvideo. Use v4l2-ctl --list-devices to map the camera to its /dev/videoN nodes.

A camera may expose multiple nodes. Choose one advertising Video Capture and Streaming, substituting its path for /dev/video0.

v4l2-ctl -d /dev/video0 --all
v4l2-ctl -d /dev/video0 --list-formats-ext

2. Capture the first image

If the camera supports 640×480 MJPEG, run the following.

v4l2-ctl -d /dev/video0 \
  --set-fmt-video=width=640,height=480,pixelformat=MJPG \
  --get-fmt-video \
  --stream-mmap=4 \
  --stream-count=1 \
  --stream-to=frame.jpg

file frame.jpg

Check that the negotiated format is MJPG, confirm that file identifies a JPEG, and open it to inspect the image. For a YUYV-only camera, use a supported resolution and format, save as frame.raw, and decode using the actual resolution and pixel format.

3. Reimplement the capture in C

Start with the single-planar V4L2 interface.

Step Calls Purpose
1 open(), VIDIOC_QUERYCAP Open the node and check capture and streaming capabilities
2 VIDIOC_S_FMT Request a format and check the negotiated resolution and pixel format
3 VIDIOC_REQBUFS, VIDIOC_QUERYBUF, mmap() Request buffers, query offsets, and map them
4 VIDIOC_QBUF, VIDIOC_STREAMON Queue empty buffers and start capture
5 poll(), VIDIOC_DQBUF Wait for a frame and dequeue its filled buffer
6 Process the frame or save it, then VIDIOC_QBUF if continuing Use bytesused for the payload length and requeue when finished
7 VIDIOC_STREAMOFF, munmap(), close() Stop capture and release resources

After QBUF, the driver owns the buffer. A successful DQBUF gives the application access again. Process the frame before requeuing its buffer.

4. Exercises

  1. Capture one MJPEG frame in C and verify that it opens like frame.jpg.
  2. Capture 100 frames, requeuing each buffer after processing it. Measure elapsed time and calculate the frame rate.
  3. Set a finite poll() timeout. Unplug the camera during capture and verify that a timeout or device error exits the loop and releases resources.

5. Integrate with Yocto

Enable V4L2 and UVC support in the target kernel. Include v4l-utils and verify a capture with v4l2-ctl on the target before packaging the C program. This gives you separate checkpoints for the node, format, and application.

Reference V4L2 Memory-Mapped Streaming I/O