linux 开发mipi摄像头示例代码
时间: 2023-07-26 14:23:55 浏览: 127
Gstreamer硬解码rtsp流 和 读mipi csi摄像头源码
在Linux下开发mipi摄像头,需要用到V4L2框架,以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
#define CAM_DEV "/dev/video0"
#define WIDTH 640
#define HEIGHT 480
int main()
{
int fd;
int ret;
struct v4l2_capability cap;
struct v4l2_format fmt;
struct v4l2_requestbuffers reqbuf;
struct v4l2_buffer buf;
fd = open(CAM_DEV, O_RDWR);
if (fd < 0) {
printf("open %s failed\n", CAM_DEV);
return -1;
}
ret = ioctl(fd, VIDIOC_QUERYCAP, &cap);
if (ret < 0) {
printf("VIDIOC_QUERYCAP failed\n");
close(fd);
return -1;
}
memset(&fmt, 0, sizeof(fmt));
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = WIDTH;
fmt.fmt.pix.height = HEIGHT;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
ret = ioctl(fd, VIDIOC_S_FMT, &fmt);
if (ret < 0) {
printf("VIDIOC_S_FMT failed\n");
close(fd);
return -1;
}
memset(&reqbuf, 0, sizeof(reqbuf));
reqbuf.count = 4;
reqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
reqbuf.memory = V4L2_MEMORY_MMAP;
ret = ioctl(fd, VIDIOC_REQBUFS, &reqbuf);
if (ret < 0) {
printf("VIDIOC_REQBUFS failed\n");
close(fd);
return -1;
}
for (int i = 0; i < reqbuf.count; i++) {
memset(&buf, 0, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
ret = ioctl(fd, VIDIOC_QUERYBUF, &buf);
if (ret < 0) {
printf("VIDIOC_QUERYBUF failed\n");
close(fd);
return -1;
}
void *addr = mmap(NULL, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buf.m.offset);
if (addr == MAP_FAILED) {
printf("mmap failed\n");
close(fd);
return -1;
}
buf.m.userptr = (unsigned long)addr;
ret = ioctl(fd, VIDIOC_QBUF, &buf);
if (ret < 0) {
printf("VIDIOC_QBUF failed\n");
close(fd);
return -1;
}
}
enum v4l2_buf_type type;
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
ret = ioctl(fd, VIDIOC_STREAMON, &type);
if (ret < 0) {
printf("VIDIOC_STREAMON failed\n");
close(fd);
return -1;
}
while (1) {
memset(&buf, 0, sizeof(buf));
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
ret = ioctl(fd, VIDIOC_DQBUF, &buf);
if (ret < 0) {
printf("VIDIOC_DQBUF failed\n");
close(fd);
return -1;
}
// 这里可以对buf.m.userptr指向的数据进行处理或保存
ret = ioctl(fd, VIDIOC_QBUF, &buf);
if (ret < 0) {
printf("VIDIOC_QBUF failed\n");
close(fd);
return -1;
}
}
return 0;
}
```
这个示例代码中,首先打开摄像头设备文件(CAM_DEV),然后调用VIDIOC_QUERYCAP查询驱动功能,调用VIDIOC_S_FMT设置摄像头采集格式,调用VIDIOC_REQBUFS请求内存,调用mmap将内存映射到用户空间,调用VIDIOC_QBUF将内存缓冲区入队列,最后调用VIDIOC_STREAMON开始采集。然后进入循环,每次采集完成后,调用VIDIOC_DQBUF将内存缓冲区出队列,进行处理或保存,然后调用VIDIOC_QBUF将内存缓冲区再次入队列,继续采集。
阅读全文