目录
- 1.脉冲编码器设备基类
- 2.脉冲编码器设备基类的子类
- 3.初始化/构造流程
- 3.1设备驱动层
- 3.2 设备驱动框架层
- 3.3 设备io管理层
 
- 4.总结
- 5.使用
 
 
 
1.脉冲编码器设备基类
此层处于设备驱动框架层。也是抽象类。
在/ components / drivers / include / drivers 下的pulse_encoder.h定义了如下脉冲编码器设备基类
struct rt_pulse_encoder_device
 {
 struct rt_device parent;
 const struct rt_pulse_encoder_ops *ops;
 enum rt_pulse_encoder_type type;
 };
脉冲编码器设备基类的方法定义如下
struct rt_pulse_encoder_ops
 {
 rt_err_t (*init)(struct rt_pulse_encoder_device *pulse_encoder);
 rt_int32_t (*get_count)(struct rt_pulse_encoder_device *pulse_encoder);
 rt_err_t (*clear_count)(struct rt_pulse_encoder_device *pulse_encoder);
 rt_err_t (*control)(struct rt_pulse_encoder_device *pulse_encoder, rt_uint32_t cmd, void *args);
 };
抽象出来共性成为脉冲编码器设备基类的方法。
2.脉冲编码器设备基类的子类
各个看脉冲编码设备基类的子类已经是在bsp的驱动层来实现了,例如
 / bsp / stm32 / libraries / HAL_Drivers / drivers 下的drv_pulse_encoder.c定义的stm32脉宽编码器类,这些都是可以实例化的终类。其他芯片厂家如此这般一样。
3.初始化/构造流程
以stm32为例,从设备驱动层、设备驱动框架层到设备io管理层从下到上的构造/初始化流程如下
3.1设备驱动层
此层是bsp层,可以实例化的终类地。
c文件:
 / bsp / stm32 / libraries / HAL_Drivers / drivers 下的drv_pulse_encoder.c。
定义了stm32脉宽编码器类
 struct stm32_pulse_encoder_device
 {
 struct rt_pulse_encoder_device pulse_encoder;
 TIM_HandleTypeDef tim_handler;
 IRQn_Type encoder_irqn;
 rt_int32_t over_under_flowcount; char *name;
 };
实例化了stm32的脉宽编码器设备:
 static struct stm32_pulse_encoder_device stm32_pulse_encoder_obj[] ;
重写了脉宽编码器设备基类的方法:
 static const struct rt_pulse_encoder_ops _ops =
 {
 .init = pulse_encoder_init,
 .get_count = pulse_encoder_get_count,
 .clear_count = pulse_encoder_clear_count,
 .control = pulse_encoder_control,
 };
hw_pulse_encoder_init中开启stm32脉宽编码器设备的初始化:
 调用/ components / drivers / misc /pulse_encoder.c的rt_device_pulse_encoder_register函数来初始化脉宽编码器设备基类对象:
 stm32_pulse_encoder_obj[i].pulse_encoder.ops = &_ops;
 rt_device_pulse_encoder_register(&stm32_pulse_encoder_obj[i].pulse_encoder, stm32_pulse_encoder_obj[i].name, RT_NULL) ;
注意,重写了脉宽编码器设备基类的方法。
3.2 设备驱动框架层
rt_device_pulse_encoder_register是脉宽编码器设备驱动框架层的入口,开启脉宽编码器设备基类的构造/初始化流程。
 其主要是重写设备基类对象的方法,如下
/ components / drivers / misc 下的pulse_encoder.c实现了设备驱动框架层接口。
 重写的脉宽编码设备基类的父类——设备基类——的方法如下
 #ifdef RT_USING_DEVICE_OPS
 device->ops = &pulse_encoder_ops;
 #else
 device->init = rt_pulse_encoder_init;
 device->open = rt_pulse_encoder_open;
 device->close = rt_pulse_encoder_close;
 device->read = rt_pulse_encoder_read;
 device->write = RT_NULL;
 device->control = rt_pulse_encoder_control;
 #endif
并最终调用设备基类的初始化/构造函数rt_device_register。
3.3 设备io管理层
rt_device_register是io管理层的入口。从框架章节可以知道所有设备类都继承自设备基类rt_device,自然都要实现设备基类rt_device的约束方法,上面已经重写。
 在/ components / drivers / core 下的device.c中实现了rt_device_register,由它将pin设备放到容器里管理。
4.总结
整个设备对象的构造/初始化流程其实是对具体设备对象也就是结构体进行初始化赋值,按照先调用子类构造/初始化函数,再调用父类的构造/初始化函数方式——其实也是子类构造/初始化函数调用父类构造/初始化函数的流程,来完成设备对象的初始化/构造。最终放到对象容器里来管理。
5.使用
文档