STM32MP157 | 基于 Linux I2C 驱动读ap3216c传感器

一、ap3216c传感器简介

AP3216C是一个集成的ALS和PS模块,包括一个数字环境光传感器[ALS],一个接近传感器[PS]和一个红外LED在单个封装中。

特性:

  • I2C 接口 (FS 模式 @ 400k Hz)
  • 模式选择: ALS, PS+IR, ALS+PS+IR, PD, ALS once, SW Reset, PS+IR
  • 工作范围 (-30°C to +80°C)

1.ap3216c的常用寄存器列表如下:

STM32MP157 | 基于 Linux I2C 驱动读ap3216c传感器_第1张图片

2. 开发板原理图

STM32MP157 | 基于 Linux I2C 驱动读ap3216c传感器_第2张图片

二、 添加设备树的节点

1.设置引脚

首先设置I2C1引脚的复用功能,找到 pinctrl_i2c1 节点:

vi stm32mp15-pinctrl.dtsi
STM32MP157 | 基于 Linux I2C 驱动读ap3216c传感器_第3张图片

2. 找出控制器的设备树

stm32mp151.dtsi

i2c1: i2c@40012000 {
    compatible = "st,stm32mp15-i2c"; //这个是和i2c控制器驱动完成匹配
    reg = <0x40012000 0x400>;        //控制器的地址和长度
    interrupt-names = "event", "error";                                                                   
    interrupts-extended = <&exti 21 IRQ_TYPE_LEVEL_HIGH>,
                  <&intc GIC_SPI 32 IRQ_TYPE_LEVEL_HIGH>;
    clocks = <&rcc I2C1_K>;
    resets = <&rcc I2C1_R>;
    #address-cells = <1>;   //修饰子节点地址的个数
    #size-cells = <0>;      //修饰子节点长度的个数
    dmas = <&dmamux1 33 0x400 0x80000001>,//dam内存直取,可以把数据直接从一个地址搬移到另一个地址
           <&dmamux1 34 0x400 0x80000001>;
    dma-names = "rx", "tx";
    power-domains = <&pd_core>;
    st,syscfg-fmp = <&syscfg 0x4 0x1>;
    wakeup-source;
    i2c-analog-filter;
    status = "disabled";  //控制器没有使能
};

3. 根据内核帮助文档编写自己的设备树

/home/linux/linux-5.10.61/Documentation/devicetree/bindings/i2c/

&i2c1{//第0个成员工作状态,第1个休眠状态
    pinctrl-names = "default", "sleep";//这个就是列表
    pinctrl-0 = <&i2c1_pins_b>;//pinctrl-0 代表列表中第0个成员//i2c1_pins_b代表管脚复用
    pinctrl-1 = <&i2c1_sleep_pins_b>;//pinctrl-1 代表列表中第1个成员
    i2c-scl-rising-time-ns = <100>;//上升沿时间毫秒
    i2c-scl-falling-time-ns = <7>;//下降沿时间
    status = "okay";    //使能                                                                                          
    /delete-property/dmas;      //删除dma属性
    /delete-property/dma-names;
    
    si7006@40{ 	//添加的设备树节点
        compatible = "st,si7006";
        reg = <0x40>;//从机地址
    };
    ap3216c@1e{
        comptible = "st,ap3216c";
        reg = <0x1e>
    };
};

4. 重新编译设备树

make dtbs

重启开发板

安装驱动

三. 编写si7006设备驱动

1.先搭个I2C设备驱动框架

#include 
#include 
#include 

int ap3216c_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
	printk("%s:%d\n", __func__, __LINE__);
    return 0;
}
int ap3216c_remove(struct i2c_client *client)
{
    printk("%s:%d\n", __func__, __LINE__);
    return 0;
}

//通过设备树的形式匹配进入probe函数
const struct of_device_id oftable[] = {
    {
        .compatible = "st,ap3216c",
    },
    {},
};

//支持热插拔
MODULE_DEVICE_TABLE(of, oftable);

struct i2c_driver ap3216c = {
    .probe = ap3216c_probe,
    .remove = ap3216c_remove,
    .driver = {
        .name = "hello",
        .of_match_table = oftable,
    }};

module_i2c_driver(ap3216c);
MODULE_LICENSE("GPL");

2. 写个Makefile编译一下:

ifeq ($(arch),arm)
KERNELDIR :=/home/linux/linux-5.10.61
CROSS_COMPILE ?=arm-linux-gnueabihf-
else 
KERNELDIR :=/lib/modules/$(shell uname -r)/build
CROSS_COMPILE ?=
endif 

modname ?=
PWD :=$(shell pwd)

CC :=$(CROSS_COMPILE)gcc

all:
	make -C $(KERNELDIR) M=$(PWD) modules
	# $(CC) test.c -o test
clean:
	make -C $(KERNELDIR) M=$(PWD) clean
	# rm test

install:
	cp *.ko ~/nfs/rootfs/
	# cp test ~/nfs/rootfs/

help:
	echo "make arch = arm or x86 modname= dirvers file name"

obj-m:=$(modname).o
linux@ubuntu:~/linu/driver/csdn/ap3216c$ make arch=arm modname=ap3216c

3. 再写字符设备驱动框架

int ap3216c_open(struct inode *inode, struct file *file)
{
    printk("%s:%s:%d\n", __FILE__, __func__, __LINE__);
    return 0;
}

ssize_t ap3216c_read(struct file *file, char __user *ubuf, size_t size, loff_t *loff)
{
    return size;
}
ssize_t ap3216c_write(struct file *file, const char __user *ubuf, size_t size, loff_t *loff)
{
    return size;
}
int ap3216c_close(struct inode *inode, struct file *file)
{
    printk("%s:%s:%d\n", __FILE__, __func__, __LINE__);
    return 0;
}
const struct file_operations fops = {
    .open = ap3216c_open,
    .read = ap3216c_read,
    .write = ap3216c_write,
    .release = ap3216c_close,
};
int ap3216c_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
    int ret;
    gclient = client;
    // 1.分配对象
    cdev = cdev_alloc();
    if (cdev == NULL)
    {
        printk("alloc memory failed\n");
        ret = -ENOMEM;
        goto ERR1;
    }
    // 2.初始化对象
    cdev_init(cdev, &fops);

    // 3.申请设备号
    if (major > 0)
    {
        ret = register_chrdev_region(MKDEV(major, minor), count, CNAME);
        if (ret != 0)
        {
            printk("static:alloc device number failed!\n");
            goto ERR2;
        }
    }
    else if (major == 0)
    {
        ret = alloc_chrdev_region(&devno, 0, 1, CNAME);
        if (ret != 0)
        {
            printk("dynamic:alloc device number failed!\n");
            goto ERR2;
        }
        major = MAJOR(devno);
        minor = MINOR(devno);
    }
    // 4.注册对象
    ret = cdev_add(cdev, MKDEV(major, minor), count);
    if (ret)
    {
        printk("add cdev failed\n");
        goto ERR3;
    }
    // 5.向上层提交目录的信息
    cls = class_create(THIS_MODULE, "hello");
    if (IS_ERR(cls))
    {
        printk("create class failed\n");
        ret = PTR_ERR(cls);
        goto ERR4;
    }
    // 6.向上层提交设备的信息
    dev = device_create(cls, NULL, MKDEV(major, minor), NULL, CNAME);
    if (IS_ERR(dev))
    {
        printk("create device failed\n");
        ret = PTR_ERR(dev);
        goto ERR5;
    }
    
    return 0;
ERR5:
    class_destroy(cls);
ERR4:
    cdev_del(cdev);
ERR3:
    unregister_chrdev_region(MKDEV(major, minor), count);
ERR2:
    kfree(cdev);
ERR1:
    return ret;
}
int ap3216c_remove(struct i2c_client *client)
{
    device_destroy(cls,MKDEV(major,minor));
    class_destroy(cls);
    cdev_del(cdev);
    unregister_chrdev_region(MKDEV(major, minor), count);
    kfree(cdev);
    printk("%s:%d\n", __func__, __LINE__);
    return 0;
}

//通过设备树的形式匹配进入probe函数
const struct of_device_id oftable[] = {
    {
        .compatible = "st,ap3216c",
    },
    {},
};

//支持热插拔
MODULE_DEVICE_TABLE(of, oftable);

struct i2c_driver ap3216c = {
    .probe = ap3216c_probe,
    .remove = ap3216c_remove,
    .driver = {
        .name = "hello",
        .of_match_table = oftable,
    }};

module_i2c_driver(ap3216c);
MODULE_LICENSE("GPL");

4.封装i2c操作代码

全局变量中添加 i2c_client 成员:

struct i2c_client *gclient;

在ap3216c_probe函数中添加

	gclient = client;//获取从机设备信息结构体
    ret = ap3216c_board_init();//驱动加载时进行硬件的初始化
	if (ret < 0)
        printk("ap3216c_board_init fail\n");

(1)ap316c写寄存器时序如下

STM32MP157 | 基于 Linux I2C 驱动读ap3216c传感器_第4张图片

int ap3216c_write_reg(uint8_t reg, uint8_t val) //这是一个无符号的char
{
    int ret;
    struct i2c_msg msg;
    uint8_t send_buf[2];
    send_buf[0] = reg;
    send_buf[1] = val;

    msg.addr = gclient->addr;
    msg.flags = 0;
    msg.len = 2;
    msg.buf = send_buf;

    ret = i2c_transfer(gclient->adapter, &msg, 1);
    if (ret != 1)
    {
        printk("i2c read serial or firmware error\n");
        return -EAGAIN;
    }
    return 0;
}

(2)ap316c读寄存器时序如下

STM32MP157 | 基于 Linux I2C 驱动读ap3216c传感器_第5张图片

int ap3216c_board_read_data(void)
{
    uint8_t low_val, high_val;
    // IR红外led
    ap3216c_read_reg(0x0A, &low_val);
    ap3216c_read_reg(0x0B, &high_val);
    if (low_val & 0x80)
    {
        data.ir = 0;
    }
    else
    {
        data.ir = ((uint16_t)high_val << 2 | (low_val & 0x03));
    }
    // ALS环境光传感器
    ap3216c_read_reg(0x0C, &low_val);
    ap3216c_read_reg(0x0D, &high_val);
    data.als = ((uint16_t)high_val << 8) | low_val;

    // ps接近光传感器
    ap3216c_read_reg(0x0E, &low_val);
    ap3216c_read_reg(0x0F, &high_val);
    if (low_val & 0x40)
    {
        data.ps = 0;
    }
    else
    {
        data.ps = ((uint16_t)(high_val & 0x3F) << 4) | (low_val & 0x0F);
    }
    return 0;
}

5.ap3216c的初始化

//ap3216c的初始化
int ap3216c_board_init(void)
{
    int ret;
    uint8_t val;
    // 设置AP3216C系统模式,软复位
    ret = ap3216c_write_reg(0x00, 0x04);
    if (ret < 0)
    {
        printk("ap3216 soft reset fail\n");
        return -1;
    }
    // 软复位后至少等待10ms
    mdelay(150);
    // 设置AP3216C系统模式,ALS+PS+IR单次模式
    ret = ap3216c_write_reg(0x00, 0x03);
    if (ret < 0)
    {
        printk("ap3216 activate fail\n");
        return -1;
    }
    mdelay(150);
    // 读模式寄存器,确认模式写入成功
    ret = ap3216c_read_reg(0x00, &val);
    if (ret < 0)
    {
        printk("ap3216 read mode fail\n");
        return -1;
    }
    printk("ap3216 mode :%d\n", val);
    return 0;
}

6.ap3216c读取数据

int ap3216c_board_read_data(void)
{
    uint8_t low_val, high_val;
    // IR红外led
    ap3216c_read_reg(0x0A, &low_val);
    ap3216c_read_reg(0x0B, &high_val);
    if (low_val & 0x80)
    {
        data.ir = 0;
    }
    else
    {
        data.ir = ((uint16_t)high_val << 2 | (low_val & 0x03));
    }
    // ALS环境光传感器
    ap3216c_read_reg(0x0C, &low_val);
    ap3216c_read_reg(0x0D, &high_val);
    data.als = ((uint16_t)high_val << 8) | low_val;

    // ps接近光传感器
    ap3216c_read_reg(0x0E, &low_val);
    ap3216c_read_reg(0x0F, &high_val);
    if (low_val & 0x40)
    {
        data.ps = 0;
    }
    else
    {
        data.ps = ((uint16_t)(high_val & 0x3F) << 4) | (low_val & 0x0F);
    }
    return 0;
}

7.字符设备驱动的实现

头文件引入

#include 
#include 
#include 
#include 

open

int ap3216c_open(struct inode *inode, struct file *file)
{
    printk("%s:%d\n", __func__, __LINE__);
    return 0;
}

read

ssize_t ap3216c_read(struct file *file, char __user *ubuf, size_t size, loff_t *loff)
{
    uint16_t rdata[3];
    int ret;

    ap3216c_board_read_data();
    rdata[0] = data.ir;
    rdata[1] = data.als;
    rdata[2] = data.ps;
    //printk("ir:%d ,als:%d, ps:%d\n", rdata[0], rdata[1], rdata[2]);
    ret = copy_to_user(ubuf, rdata, sizeof(rdata));
    if (ret)
    {
        printk("copy data to user error\n");
        return -EIO;
    }
    return size;
}

write

ssize_t ap3216c_write(struct file *file, const char __user *ubuf, size_t size, loff_t *loff)
{
    return size;
}

close

int ap3216c_close(struct inode *inode, struct file *file)
{
    printk("%s:%s:%d\n", __FILE__, __func__, __LINE__);
    return 0;
}

四、测试驱动模块

1.加载驱动,查看驱动

STM32MP157 | 基于 Linux I2C 驱动读ap3216c传感器_第6张图片

2.编写app测试程序

#include 
#include 
#include 
#include 


#define PRINT_ERR(msg) \
    do                 \
    {                  \
        perror(msg);   \
        return -1;     \
    } while (0)

int main(int argc, const char *argv[])
{
    int fd, ret;
    uint16_t data_buf[3] = {0};

    if ((fd = open("/dev/ap3216c", O_RDWR)) == -1)
        PRINT_ERR("open error");

    while (1)
    {
        ret = read(fd, data_buf, sizeof(data_buf));
        if (ret < 0)
        {
            printf("read fail\n");
        }
        else
        {
            printf("ir:%d ,als:%d, ps:%d\n", data_buf[0], data_buf[1], data_buf[2]);
        }
        sleep(1);
    }
    close(fd);
    return 0;
}

STM32MP157 | 基于 Linux I2C 驱动读ap3216c传感器_第7张图片

成功读取读到红外,环境光,接近传感器数据

你可能感兴趣的:(STM32MP157A,stm32,linux)