commit 8c6429f05a63c422b419a1a09abf91d4dda881de Author: TuxMonkey <8196772+tuxmonkey@user.noreply.gitee.com> Date: Sat Jan 17 14:06:59 2026 +0800 first commit diff --git a/.Doc/Bug_Report.md b/.Doc/Bug_Report.md new file mode 100644 index 0000000..ee0936c --- /dev/null +++ b/.Doc/Bug_Report.md @@ -0,0 +1,69 @@ +# 异常报告 + +已知可能出现的bug将会列在此处,并指明修复期限和任务执行者。 + +使用中遇到的bug和错误放在此处。参照下列格式: + +## 标题用简短的一句话描述 + +### 出现问题的application/module/bsp + +描述你的使用方法,应该贴上图片或代码块,以及硬件连线等 + +### 尝试解决的方案 + +你的尝试,以及猜测可能的错误 + +### 如何复现问题 + +问题能否稳定复现?描述复现方法等 + +### 紧急程度 + +这里用⭐表示。最大5颗⭐。 + +如果不修复,会有何种其他牵连情况发生? + +--- + +不同的问题用 --- 分隔开 + +你还可以使用Stepsize插件在代码出现问题(可能出现问题)的地方添加issues并详尽描述。或在gitee上增加issues。 + +当然,最快的方法是在群里提问。 + +## 使用LK电机并挂载在hcan2上时会出现HardFault + +> 已修复此问题。修复日志请查看当前目录下的“如何定位bug.md”。 + +使用MF9025v2电机,并将其配置在CAN2上。经过一次LKMotorControl,第二次进入时hcan->instance会在HAL_CAN_Add_Tx_Message()结束时被未知的语句修改成奇怪的值,造成HardFault + +### 尝试解决的方案 + +单步调试无果,在HAL_CAN_Add_Tx_Message()返回的那一步hcan->instance会莫名其妙变成0,hcan2也会被修改到一个0x8000xxx的地址上(hcan是HAL库自定的全局变量) + +### 如何复现问题 + +使用LK电机并将其挂载在CAN2上,连接电机后直接运行。在第二次进入MotorTAsk中的LKMotorControl时,于检查空闲CAN邮箱时,由于hcan2被修改,访问CAN2外设状态时会访问野指针导致HardFault。 + +### 紧急程度 + +⭐⭐⭐⭐⭐ + +## 总线挂载多个电机后,pitch和yaw的GM6020电机出现编码器反馈值跳动 + +> 已修复,详细信息见“如何定位bug.md” + +CAN1总线挂载5个电机,4\*3508+1\*6020,控制报文发送频率为500Hz,电机的反馈频率皆为1kHz.云台在控制时会出现突然跳动.添加到Ozone graph查看发现ECD(编码器)值在静止状态下也会出现突然抖动,并且幅度超过4000.但不会出现超过编码器反馈值范围的值. + +### 尝试解决的方案 + +若使用单个6020电机,不会出现此问题. 曾认为是指针越界导致`motor_measure->ecd`值被修改, 需要进一步观察其他反馈值是否出现问题. 且反馈值始终在编码器范围之内. + +### 如何复现问题 + +同时启用CAN1和CAN2,并在单条CAN总线上挂载超过5个电机. + +### 紧急程度 + +⭐⭐⭐ \ No newline at end of file diff --git a/.Doc/TODO.md b/.Doc/TODO.md new file mode 100644 index 0000000..d7a9a79 --- /dev/null +++ b/.Doc/TODO.md @@ -0,0 +1,183 @@ +# Work To be done & optimized + +- **待完成**:不完成可能导致整车功能不完整 +- **待优化**:对已有的功能进行性能提高/模块解耦/可维护性增强 +- **待添加**:不紧急的/锦上添花的功能 + +**==标为黄色高亮的代表紧急程度高。==** + +## assorted + +- [ ] 由于我们读写和传递的数据结构都不大,基本不会发生读写时任务切换的情况。典型的数据读写时间都是~μs,故没有对数据访问的接口添加互斥锁或关闭全局中断。后续有需求(如大量数据复制)可以添加。可以新增一个bsp_mutex或者module层的ds,提供相应支持。实际上freertos提供了一些供线程(任务)间进行数据交互的类型和函数,请查阅对应文档。 + +最简单的防止重入或数据竞争的方式是创建一个bool类型值实现互斥访问。当一个线程或中断要访问某个变量时,先检查这个变量对应的bool锁是否为1,若不为1则赋值为1表明当前有线程访问变量,之后可以开始对该变量的操作,结束读写后释放锁即赋0。不像osSemaphore或osMessageQueue等只允许在中断中添加消息或释放信号量/互斥量,这种变量锁可以在任意处加锁解锁。 + +若锁获取失败,则直接退出,或将当前线程挂起等待下一次唤醒。最常见的情况是一个线程需要从一块数据区或缓冲区读取数据而某个中断会向这个区域写入数据,线程在读取的时候很可能会被中断打断。那么中断进入时发现该数据已经被上锁,就不会强行写入。为了保证数据的实时性,你可以选择将数据存入队列或启动一个新的任务,当锁释放时再写入数据。如果数据量较小,你不在乎开销,则可以使用freerots提供的osMessageQueue或osMessageMailbox。 + +目前,我们在bsp_dwt中添加了一个位锁,防止中断中调用DWTGetDeltaT或DWTGetTimeline函数更新DWT维护的时间时打断任务中的相同函数导致计数被重复更新,或引起错误的DWT溢出检测。 + +## BSP + +### 待完成 + + + +### 待优化 + +#### bsp_pwm + +- [ ] 是否允许修改预分频计数器? + +### 待添加 + +#### bsp_iic + +- [ ] 添加10位地址的支持 + +#### bsp_blueteetch + +- [ ] 增加蓝牙功能,方便调试和测试 + +#### bsp_wifi + +- [ ] 增加无线局域网功能,方便调试和测试 + +--- + +## Module + +### 待完成 + +Unicom + +- [ ] 为键鼠/遥控器/ps手柄/视觉上位机等各种控制器提供一套统一的接口,把发来数据转化为标准的控制数据,包括底盘速度云台角度等等 + +- [ ] 给每个模块增加调试的条件编译,并增加bsp log的输出。或直接在运行时添加log等级,输出不同的信息。 + +#### ==servo_motor== + +舵机模块,需要预先定义90/180/360连续旋转的电机类型,并且能够设定max和min位置。 + +- [x] 编写舵机模块(待测试和优化) +- [ ] 可能需要串口舵机的支持? + +#### imu + +- [ ] 完善bmi088模块和算法的交互,添加异步量测更新的SO3上的IEKF + +> 继续使用四元数(S3)也许是一个更好的选择,改动较小且运算开销也较小。后续考虑修改一套ESKF_INS并移植到框架中。 + +#### ==master_machine== + +- [ ] 增加IMU数据的时间戳 +- [ ] 增加加速度计数据 +- [ ] 重构seasky protocol的接口 +- [ ] 增加数据未更新的处理 + +需要一个更简单的协议以加快速度。若有必要,可能需要重新编写一个简单的调试上位机UI。 + + +### 待优化 + +#### buzzer + +> 是否需要在module层就和**daemon**模块配合? + +当前实现为buzzer是单独的module,若需要蜂鸣器警报的module可以自行包含buzzer.h以创建不同情况下的警报,如电机离线、堵转、遥控器离线等。 + +也许还有其他方式提醒离线和异常。 + +目前急需一个无线遥控继电器,防止机器人的急停模式失效。 + +#### BMI088 + +- [ ] 完善和SO3 IEKF的交互,增加异步任务的唤醒和数据传递(IMU中断唤起任务) + +根据BMI088的datasheet在初始标定完成后将gyro和acc都设置为中断触发,当数据准备好时传感器会在对应的引脚输出跳变,通过EXTI捕获跳变并触发中断,在回调函数中启动SPI DMA传输。陀螺仪数据来到时进行姿态的预测即propagation,加速度计数据到来时进行量测更新(correct)。 + +也许需要找到一种更好的方式构建INS任务以方便和其他模块、应用的交互。 + +另外,若要进一步提升自瞄效果,在姿态得到更新时(陀螺仪和imu的数据到来时),需要额外的引脚连接到相机上完成硬触发采集,以获得更好的时间对齐效果,防止视觉得到的姿态数据发生漂移。目前视觉端假设姿态更新的频率是1khz(当前每次完成姿态解算都会向上位机发送当前的姿态) + +#### remote_control + +- [ ] 增加长按/短按检测 (是否有必要?) + +#### message_center + +- [ ] 增加队列剩余信息和数据时间戳的支持 +- [ ] 提供直接传递指针的接口? + +#### can_comm + +- [ ] 增加can_comm数据未更新的处理 + +#### controller + +- [ ] 将PID的初始化改写为PIDRegister的形式,在controller统一分配内存. + +#### dji_motor + +- [ ] 增加3508和2006的开环零位校准函数 +- [ ] 为实例增加低通滤波系数变量,使不同电机有不同的配置 + +#### LKmotor + +- [ ] 正反转标志位设置,需要修改反馈量和pid计算 + +#### HTmotor + +- [ ] 正反转标志位设置,需要修改反馈量和pid计算 + +### 待添加 + +#### unicomm + +- [ ] 完成初版构建 + +#### step_motor + +- [ ] 增加步进电机模块 + +#### referee_communication + +- [ ] 增加裁判系统多机通信功能 + +#### controller + +- [ ] 增加扰动观测器,可能需要新增模块 +- [ ] 增加基于模型的控制器,可能需要新增模块 + +#### ws2816 + +- [ ] 通过bsp_pwm添加支持 + +--- + +## APP + +### 待完成 + +#### all app + +- [ ] 增加调试的条件编译,使得在没有连接其他应用时也可以假装有那些应用而正常调试运行 + +#### ==shoot== + +- [ ] 增加卡弹检测和反转 + +### 待优化 + +#### robot_cmd + +- [ ] 优化消息发布和接收性能(若皆为异步并在robottask中执行,实际上可以只传递指针) + +#### gimbal + +- [x] 增加底盘速度前馈控制 + +#### chassis + +- [x] 根据电机的实际速度计算底盘的真实运动(轮式里程计) +- [ ] 若为双板,根据IMU的数据对电机实际速度进行融合 + diff --git a/.Doc/VSCode+Ozone使用方法.md b/.Doc/VSCode+Ozone使用方法.md new file mode 100644 index 0000000..68b37a3 --- /dev/null +++ b/.Doc/VSCode+Ozone使用方法.md @@ -0,0 +1,1052 @@ +# VSCode+Ozone开发STM32的方法 + +
+
+以上是C语言常见的内存模型,即C语言的代码块以及运行时使用的内存(包括函数、变量等)的组织方式。
+
+> 有些平台的图与此相反,栈在最下面(内存低地址),其他区域都倒置,不影响我们理解
+
+**代码段**即我们编写的代码,也就是前面说的编译和链接之后最终生成的可执行文件占据的空间。一些常量,包括字符串和使用`const`关键字修饰的变量被放在常量存储区。`static`修饰的静态变量(包括函数静态变量和文件静态变量)以及全局变量放在常量区上面一点的全局区(也称静态区)。
+
+然后就是最重要的**堆**和**栈**。在一个代码块内定义的变量会被放在栈区,一旦离开作用域(出了它被定义的`{}`的区域),就会立刻被销毁。在调用函数或进入一个用户自定义的`{}`块,都会在栈上开辟一块新的空间,空间的大小和内存分配由操作系统或C库自动管理。**一般来说,直接通过变量访问栈内存,速度最快**(对于单片机)。而堆则是存储程序员自行分配的变量的地方,即使用`malloc(),realloc() ,new`等方法获取的空间,都被分配在这里。
+
+> 在CubeMX初始化的时候,Project mananger标签页下有一个Linker Setting的选项,这里是设置最小堆内存和栈内存的地方。如果你的程序里写了大规模的数组,或使用`malloc()`等分配了大量的空间,可能出现栈溢出或堆挤占栈空间的情况。需要根据MCU的资源大小,设置合适的stack size和heap size。
+
+RTOS创建任务的时候也会为每个任务分配一定的栈空间,它会替代MCU的硬件裸机进行内存的分配。可以在CubeMX中设置。如果一个任务里定义了大量的变量,可能导致实时系统运行异常,请增大栈空间。
+
+> 开发板C型使用F407IG芯片,片上RAM的大小为1MB。
+
+### C language标准和编译器
+
+不同的C语言标准(一般以年份作代号)支持的语法特性和关键字不同,拥有的功能也不同。一般来说语言标准都是向前兼容的,在更新之后仍然会保存前代的基本功能支持(legacy support)。不过,为了程序能够正常运行,我们还需要一些硬件或平台支持的组件。比如`malloc()`这个函数,在linux平台和windows平台上的具体实现就相去甚远,跟单片机更是差了不止一点。前两者一般和对应的操作系统有关,后者在裸机上则是直接通过硬件或ST公司提供的硬件抽象层代码实现。
+
+然而,不同编译器提供的代码实现也不尽相同,比如使用clang和gcc这两种c语言编译器,他们对于一些标准库(也称C库,包括stdio,stdlib,string等在内的实现)的函数的实现就不太一样。再如`__packed`是arm-cc提供的一个字节不对齐关键字,在一些其他编译器中就不支持这种实现。
+
+以前大家常用的KEIL使用的是ARM提供的arm-cc工具链(非常蛋疼,甚至不支持uint8_t=0b00001111这种二进制定义法),而该教程选用的是开源的**Arm GNU Toolchain**。在非目标机且和目标机平台不同的平台上进行开发被成为**跨平台开发**,进行的编译也被成为**交叉编译**(在一个平台上生成另一个平台上的 可执行代码)。
+
+> 工具链包含了编译器,链接器以及调试器等开发常用组件。我们使用的Arm GNU toolchain中,编译器是`arm-none-eabi-gcc.exe`,链接器是`arm-none-eabi-ld.exe`,调试器则是`arm-none-eabi-gdb.exe`。通过跨平台调试器和j-link/st-link/dap-link,我们就可以在自己的电脑上对异构平台(即单片机)的运行进行调试了。
+
+==***特别注意,在新框架中我们使用的是arm-none-eabi-gcc,此编译器不支持`__packed`关键字,若要进行字节压缩(不对齐字节),应该使用预编译指令`#pragma pack(1)`***==。
+
+### Debug外设工作原理
+
+
+
+DBG支持模块(红框标注部分,也可以看作一个外设)通过一条专用的AHB-AP总线和调试接口相连(Jtag或swd),并且有与**数据**和**外设**总线直接相连的桥接器。它还同时连接了中断嵌套管理器(因此同样可以捕获中断并进行debug)和ITM、DWT、FPB这些调试支持模块。因此DBG可以直接获取内存或片上外设内的数据而不需要占用CPU的资源,并将这些数据通过专用外设总线发送给调试器,进而在上位机中读取。
+
+FPB是flash patch breakpoint闪存指令断点的缩写,用于提供代码断点插入的支持,当CPU的指令寄存器读取到某一条指令时,FPB会监测到它的动作,并通知TPIU暂停CPU进行现场保护。
+
+DWT是data watch trace数据观察与追踪单元的缩写,用于比较debug变量的大小,并追踪变量值的变化。当你设定了比较断点规则(当某个数据大于/小于某个值时暂停程序)或将变量加入watch进行查看,DWT就会开始工作。DWT还提供了一个额外的计时器,即所有可见的TIM资源之外的另一个硬件计时器(因为调试其他硬件定时器的计时由于时钟变化可能定时不准,而DWT定时器是始终正常运行的)。它用于给自身和其他调试器模块产生的信息打上时间戳。我们的bsp中也封装了dwt计时器,你可以使用它来计时。
+
+ITM是instrument trace macrocell指令追踪宏单元的缩写,它用于提供非阻塞式的日志发送支持(相当于大家常用的串口调试),SEGGER RTT就可以利用这个模块,向上位机发送日志和信息。这个硬件还可以追踪CPU执行的所有指令,这也被称作**trace**(跟踪),并将执行过的指令全部通过调试器发送给上位机。当debug无法定位bug所在的时候,逐条查看cpu执行的指令是一个绝佳的办法,特别是你有大量的中断或开启了实时系统时。
+
+以上三个模块都需要通过TPIU(trace port interface unit)和外部调试器(j-link等)进行连接,TPIU会将三个模块发来的数据进行封装并通过DWT记录时间,发送给上位机。
+
+### GDB调试MCU原理
+
+
+
+不论使用MDK(KEIL)还是VSCode还是Ozone,实际上背后的流程相同。首先GDB会建立TCP/IP端口并提供接口,调试服务器(Server)作为硬件调试器和GDB软件的桥梁,将硬件调试器的相关功能(也就是DBG外设支持的那些功能)映射到GDB的接口上(通过连接到GDB建立的端口)。之后启动调试,将可执行文件下载到目标MCU上,然后从main开始执行
+
+> 当然你也可以选择从其他启动点开始执行,调试器开始执行的位置叫做**entry point**。同样,在MCU已经正在运行程序的时候,可以**attach**到程序上开始监控(attach=附加,贴上;很形象了)。
+
+> 而对于直接运行在电脑上的程序(.exe),就不需要GDBserver和物理调试器,GDB程序可以直接访问电脑上运行的程序和CPU的寄存器等。
+
+### 字节对齐
+
+这是内存硬件设计和汇编语言设计的结果。在使用结构体的时候,如果你不做任何事情,编译器会自动帮助你完成字节对齐以提高内存访问的效率。stm32是4字节地址和数据总线的设计,单词可以传输32位数据,因此,访问4字节数据(也就是stm32的“字”,“字长”)效率最高。然而,历史的缘由导致一个内存地址只存储8位的数据,如果你要访问float数据,则一次需要读取4个地址。当这四个地址是连续的时候,你只需要一次就可以将数据读出。然而,如果一个float数据被存放在0x03-0x07这四个地址,cpu首先要读出0x00-0x03这四个连续的地址,然后再取出最后一个字节;随后读取0x04-0x07这四个连续的字节,再取出前三个字节;最后将最后一个字节和前三个字节拼接在一起,形成我们需要的float数据。
+
+`#pragma`可能是最复杂的预编译指令,不同的编译器支持不同的`#pragma`指令,如常用的`#pragma once`可以替代header guard。arm gnu gcc编译器支持通过`#pragma pack()`来设置字节对齐,支持的对齐参数包括空/1/2/4/8,会启动对应长度的对齐方式。用于通信的结构体(串口/CAN/spi等外设接收数据的时候都是连续的,不会像结构体一样被编译器对齐)在声明时,采用如下的方式:
+
+```c
+#pragma pack(1) // 从这句话开始,使用字节对齐(1),即紧凑,关闭对齐
+
+typedef struct
+{
+ uint8_t id;
+ // ...
+
+} CANInstance;
+
+#pragma pack() // 从这里开始,恢复默认配置,一般来说默认配置是 pack(4),如果遇到double/longlong等也会变为8字节对齐
+// 使用两个#pragma包裹你的结构体声明
+```
+
+如果您有兴趣,可以了解一下内存硬件的组织和连接方式,包括奇偶地址/片选/行列扩展等,可以帮助你更好地理解字节对齐。
+
+## 环境配置
+
+> ***所有需要编辑的配置文件都已经在basic_framework的仓库中提供,如果不会写,照猫画虎。***
+
+- **软件安装**
+
+队伍NAS和资料硬盘内提供了所有必要的依赖,安装包和插件,目录是`/EC/VSCode+Ozone环境配置`,请以公共账号登陆网盘,ip地址为`49.123.113.2:5212`,账号`public@rm.cloud`,密码`public`。
+
+对于非队内的开发者,我们提供了网盘下载方式。所有安装包也可以在此百度网盘链接下获得:[archive.zip](https://pan.baidu.com/s/1sO_EI4cToyIAcScOQx-JSg?pwd=6666)
+
+```shell
+# 网盘中的文件:
+basic_framework.zip # 本仓库文件,注意为了保证最新,建议从仓库clone并定时pull(或自动fetch)
+daplink_register_license.rar # daplink license注册机
+gcc-arm-none-eabi-10.3-2021.10-win32.zip # arm-gnu-toolchain,注意,这个版本太老,编译最新的框架可能出现一些编译参数不支持的情况。请通过Msys2直接安装或到arm官网下载最新的12.x版本。
+JLinkARM.dll # 修改过的jlink运行链接库
+JLink_Windows_V722b.exe # JLink软件包
+mingw-get-setup.exe # mingw工具链(更推荐的方式是使用msys2安装)
+OpenOCD.zip # OpenOCD
+Ozone_doc.pdf # Ozone使用手册
+Ozone_Windows_V324_x86.exe # Ozone安装包
+VSCodeUserSetup-x64-1.73.1.exe # VSCode安装包
+# 最佳实践是下载msys2并在mingw64中安装软件包!!!
+# 如果你喜欢clang,可以使用clang下的arm工具链。
+```
+
+> 2022-12-01更新:
+>
+> **VSCode上线了一款新的插件:**
+>
+> 
+>
+> 支持一键配置Arm GNU工具链、MinGW64(make工具)和OpenOCD!可以尝试使用这个插件替代下面的配置流程。并且,此插件还提供了一键下载、一键调试的支持,只需要选择合适的下载器配置即可,全部都是图形化界面的操作!
+>
+> 你可以尝试使用这个插件进行环境的配置。当然,环境变量仍然需要手动添加。
+>
+> ==**另外,如果你不想配置太多东西也不想了解底层的信息,可以尝试Embedded IDE插件。它支持直接在VSCode中编辑KEIL MDK的项目,相关信息请自行查阅,或直接查看EIDE的项目网站:**==[https://em-ide.com](https://em-ide.com/)
+
+- 安装STM32CubeMX,并安装F4支持包和DSP库支持包
+
+- 安装VSCode,并安装以下插件:
+
+ - **C/C++**:提供C/C++的调试和代码高亮支持
+ - **Better C++ Syntax**:提供更丰富的代码高亮和智能提示
+ - **C/C++ Snippets**:提供代码块(关键字)补全
+ - **Cortex-Debug**,**Cortex-Debug: Device Support Pack - STM32F4**:提供调试支持。cortex debug还会自动帮助你安装一些调试相关的插件,包括RTOS支持和内存查看等。
+ - **IntelliCode**,**Makfile Tools**:提供代码高亮支持。喜欢clang的同学可以使用clangd。
+
+ 
+
+ 
+
+ 
+
+ 
+
+ 
+
+ > MinGW、Arm GNU toolchain和OpenOCD也可以通过**MSYS2**使用pacman包管理器(和apt/yum类似)直接安装,这种方法一步到位,**==这是更推荐使用的方式==**,请参看[附录5](##附录5:利用MSYS2安装依赖环境)。
+ >
+ > **当然,你也可以直接按照下面的方法安装这两个工具。**不过,强烈推荐使用附录5中的方法。下面的方法将在发布完整版更新的时候被删除。
+
+- 安装MinGW,等待界面如下:(will be deprecated soon,请注意这种方法将会在主分支发布正式版的时候删除)
+
+ 
+
+ 安装好后,打开MinGW后将所有的支持包勾选,然后安装:
+
+ 
+
+ 
+
+ 安装完以后,将MinGW的bin文件夹添加到环境变量中的path下,按下菜单键搜索**编辑系统环境变量**打开之后:
+
+ 
+
+ 图片看不清请打开原图。验证安装:
+
+ 打开命令行(win+R,cmd,回车),输入`gcc -v`,如果没有报错,并输出了一堆路径和参数说明安装成功。
+
+ 安装完之后,建议将ming的bin文件夹下的mingw32-make.exe复制一份,并将copy更名为make.exe
+
+ > 当然,更推荐的方式是将MinGW终端集成到VSCode中,防止类linux环境和Win的环境冲突,特别是你的电脑中安装了其他工具链的时候,如MSVC、LLVM等。
+
+- 配置gcc-arm-none-eabi环境变量,**把压缩包解压以后放在某个地方**,然后同上,将工具链的bin添加到PATH:(will be deprecated soon,请注意这种方法将会在主分支发布正式版的时候删除)
+
+ 
+
+
+
+### 运行任务
+
+
+
+### 初始化流程
+
+~~~mermaid
+graph TD
+HAL库初始化 --> BSP初始化 --> Application初始化 --> app调用其拥有模块的初始化 --> 启动操作系统
+~~~
+
+**注意,应用初始化不得放入其对应任务中,即使是在死循环前,否则可能导致一些需要定时器的任务初始化异常**。
+
+APP会调用其所有的模块的初始化函数(注册函数),这是因为本框架的设计思想是任何模块在被注册(构造/初始化)之前,都是不存在的,当且仅当定义了一个模块结构体(也称实例)的时候,才有一个实体的概念。
+
+main函数唯一需要的函数是app层的`robot.c`中的`RobotInit()`函数,它首先会调用BSP初始化,然后进行所有应用的初始化;每个应用会调用对应模块的初始化;一些依赖通信外设的模块会将通信支持相关的bsp进行初始化。初始化结束之后实时系统启动。
+
+### 程序运行流程
+
+
+
+### 程序数据流
+
+
diff --git a/.Doc/让VSCode成为更称手的IDE.md b/.Doc/让VSCode成为更称手的IDE.md
new file mode 100644
index 0000000..10861fb
--- /dev/null
+++ b/.Doc/让VSCode成为更称手的IDE.md
@@ -0,0 +1,136 @@
+# 让VSCode变成你熟悉的形状
+
+VSCode的各种配置如快捷键、高亮颜色、主题、界面形状和位置等(也包括各种插件的设置)可以通过在`ctrl+,`打开的设置页面修改,更好的方式是你已经尝试过的——通过xxx.json文件进行配置。VSCode的配置系统同样通过`.json`文件完成,且存在继承和覆盖的关系。VSCode的底层配置`setting.json`是针对整个VSCode进行设置的,而工作区目录下创建的`.vscode/setting.json`则可以覆盖底层配置。了解了基本的配置结构后,这里将介绍一些入手必备的设置和推荐安装的插件。
+
+[TOC]
+
+## 快捷键
+
+不管使用什么软件,基本的快捷键一定可以帮助你提高效率,更专注于当前正在做的事——减少双手离开主键盘区的频率和时间。
+
+常用的快捷键已经在[VSCode的基础操作](VSCode+Ozone使用方法.md)中介绍,这里推荐一些shortcuts的组合,可以直接`ctrl+k&s`打开快捷键设置或进入`setting.json`手动修改。当然,你不一定要和我们的建议完全一致,**根据自己的习惯定制才是最好的!**
+
+- `ctrl+;`设置为移动到行尾,同时保留`end`,这样在输完函数参数之后不用按`→`或使用鼠标
+- `alt+j/k`设置为向左向右移动,这样在修改的时候不用按方向键;可以设置组合键达到”移动到符号末尾”的功能实现按符号或单词移动
+- `tab`改为移动到下一个建议(智能提示),`enter`设置为接受当前建议。如果只有一个建议,`tab`直接接受;`alt+tab`移动到上一个建议。
+- 设置一个组合键用于选中当前单词
+- 记住当前文件查找和全局查找的组合,最好再学习一下**正则表达式**。还有”选中当前所有出现“,可以快速定位当前文件有哪些地方用了这个变量/函数。
+- 熟练使用`ctrl+tab`切换当前已经打开的文件
+- 可以在`setting.json`中将`task.json`中的任务绑定成你需要的快捷键,比如默认`ctrl+shift+b`是构建任务。把一些常用的命令行操作写成task,通过快捷键瞬间触发。
+- 善用右键菜单中的peek xxx功能、展开调用层级和头文件/源文件跳转,以及git查看文件差异的功能,这在理清代码结构、查看之前的更改的时候非常有用。当然,不是让你按右键,是使用快捷键。如果你的键盘上有一个像文件一样的图标,当你聚焦在编辑区的时候可以按下它来替代右键(展开菜单)。
+- more...
+
+*若你使用触控板和笔记本电脑,也可以利用触控板实现一些实在找不到的快捷键功能。*一开始你可能会决定快捷键难记又难按,当你熟练之后,却会在无形之中极大提升你的效率。
+
+
+
+## 代码高亮
+
+虽然VSCode默认的语法高亮已经吊打KEIL和CubeIDE之流,但你是否发现变量全是浅蓝色,字符串、数值字面量内部也无法区分?无出其右,我们可以自定义各种entity的颜色!
+
+建议让copilot协助你完成,打开`setting.json`开始设置吧:
+
+- global、private member、public member、local设置为不同的颜色
+- 私有函数和公开函数设置为不同的颜色
+- static函数设置特殊的颜色?
+- 函数参数变量设置不同的颜色?
+
+
+
+## 终端工具
+
+你至少应该学习bash(msys2中会集成一套类linux的bash工具)的基础指令,如果有可能,也学习一下powershell。在chatGPT或者Copilot的帮助下,这易如反掌。当它们无能为力时请务必查阅**官方文档**,而不是在CSDN中💩里淘🪙。
+
+为你的终端配置好看的颜色、字体和背景,但不要花太多时间。一定要让你的终端具有补全和历史记录记忆功能。
+
+学会在命令行中使用一些常用的git操作,虽然vscode中已经提供了强大的图形化集成。
+
+务必学习vi/vim/nano的基础操作。
+
+熟悉在终端中创建/追加/移动/复制/删除文件和文件夹。
+
+学习gnu工具链的简单指令,协助你与编译报错信息一起定位bug和错误(常常是undefined reference或未定义函数、未定义就使用)。
+
+也许,了解一下shell的工作原理,或者更多,现代操作系统的运行架构?
+
+> 为basic_framework通过串口/SWD建立一套简单的cmd?有很多开源代码的实现,期待你的PR!
+
+
+
+## 进一步提高效率
+
+首先,快捷键一定要按的顺手,最好能让双手处于标准指法的起始状态就可以轻松触发。一定不要超过三个键,否则按起来手掌大开大合。
+
+建议打开函数的自动括号补全(一般在对应语言的插件设置中寻找),同时习惯snippets的使用,并根据自己的需要自定义一些方便的snippets。
+
+如果你认为vim很酷,那它确实很酷。vscode中有fake-vim插件,喜欢折腾的话,vim会让你在双手始终保持在键盘区,劈里啪啦地编码,只不过学习成本较高,曲线复杂。
+
+你最好升级一下默认的shell,windows下有好看的posh,linux则有广为流传的zsh。具体如何配置,自行查阅**官方文档**。
+
+记住,最好将不同软件开发使用的环境隔离开,所以你需要把msys2集成到vscode中!(macOS和linux用户忽略)
+
+把开发中常用但又繁琐的流程自动化,积累一套你自己的脚本库。
+
+....
+
+
+
+## 插件
+
+> 学习一个插件的使用,最好的方式是阅读插件的wiki和说明文档,而不是在搜索引擎里面搜索!询问ChatGPT或者Copilot Chat也是一个比较好的办法,初级的问题它们几乎不会犯错。
+
+- **Better C++ Syntax**
+
+用于静态解析C++代码,为intellisense以及language server提供代码高亮和完整的智能提示选项。
+
+- **Blockman**
+
+为代码分块。不同的作用域会被浅色背景边框包围,同时高亮当前focus的代码块,方便在大段代码中定位程序控制流。
+
+- **Bookmarks**
+
+为代码添加书签,可以在左侧tab页中跳转到对应位置,方便阅读代码时往复查看,也有助于阅读理解。右键点击代码行号左侧(即打断点的地方)可以添加书签或带label的书签。
+
+- **C/C++ Snippets**
+
+为基本的语句(关键字)提供代码补全,如输入`for`自动生成下面的代码:
+
+```c
+for (size_t i = 0; i < count; i++)
+{
+ /* code */
+}
+```
+
+补全之后,按下tab会进入不同的位置,方便进一步修改snippet。你也可以在VSCode中自定义常用的snippet补全。
+
+- **Code Issue Manager**
+
+可以在代码的任意地方插入“便签”和“评注”,支持多人协作。是一个比注释更好的TODO list和注意事项提醒。插入的issue支持markdown格式。
+
+- **Doxygen Documention Generator**
+
+为你的代码生成doxygen文档格式的注释。同时也支持一些基本的注释块生成。输入`/**`再按下回车会根据当前注释的位置自动生成合适的注释块。本框架中的注释均通过该插件生成。
+
+- **Github Copilot / Copilot Labs / Copilot Chat**
+
+体验大模型的威力。尤其是Copilot Chat非常适合为你提供一门语言的入门级咨询。
+
+- **Gitlens**
+
+方便地通过图形化的方式管理你的git仓库。
+
+- **HexEditor & Hex Hover Converter**
+
+以十六进制编辑文件 & 鼠标悬停在任意数值类型上时自动提供2/8/16进制的转换。
+
+- **Live Share**
+
+和你的伙伴一起coding。
+
+- **SonarLint**
+
+VSCode上最强大的静态检查工具,在VSCode自动静态检查的基础上提供更严格的代码建议,尽可能降低出错的可能。其中也包含了不同语言的最佳实践。
+
+cmake可以通过添加`DCMAKE_EXPORT_COMPILE_COMMANDS=True` 的指令(直接在cmakelists中通过`set()`设定也可以),makefile则通过Makefile Tools插件设置生成`compile_commands.json`的路径。
+
diff --git a/.assets/00937839b59a4c039ee8ecb8a5136e3c.png b/.assets/00937839b59a4c039ee8ecb8a5136e3c.png
new file mode 100644
index 0000000..a890de4
Binary files /dev/null and b/.assets/00937839b59a4c039ee8ecb8a5136e3c.png differ
diff --git a/.assets/CANcomm.png b/.assets/CANcomm.png
new file mode 100644
index 0000000..b4a0a76
Binary files /dev/null and b/.assets/CANcomm.png differ
diff --git a/.assets/allrobot.jpg b/.assets/allrobot.jpg
new file mode 100644
index 0000000..6b8c991
Binary files /dev/null and b/.assets/allrobot.jpg differ
diff --git a/.assets/balance.gif b/.assets/balance.gif
new file mode 100644
index 0000000..1667114
Binary files /dev/null and b/.assets/balance.gif differ
diff --git a/.assets/dataflow.svg b/.assets/dataflow.svg
new file mode 100644
index 0000000..a2af8bf
--- /dev/null
+++ b/.assets/dataflow.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/.assets/engineering.gif b/.assets/engineering.gif
new file mode 100644
index 0000000..6fb86fd
Binary files /dev/null and b/.assets/engineering.gif differ
diff --git a/.assets/image-20221112145717063.png b/.assets/image-20221112145717063.png
new file mode 100644
index 0000000..1dd4f1b
Binary files /dev/null and b/.assets/image-20221112145717063.png differ
diff --git a/.assets/image-20221112160213066.png b/.assets/image-20221112160213066.png
new file mode 100644
index 0000000..69b81ca
Binary files /dev/null and b/.assets/image-20221112160213066.png differ
diff --git a/.assets/image-20221112172051589.png b/.assets/image-20221112172051589.png
new file mode 100644
index 0000000..cb5d993
Binary files /dev/null and b/.assets/image-20221112172051589.png differ
diff --git a/.assets/image-20221112172157533.png b/.assets/image-20221112172157533.png
new file mode 100644
index 0000000..9308765
Binary files /dev/null and b/.assets/image-20221112172157533.png differ
diff --git a/.assets/image-20221112172208749.png b/.assets/image-20221112172208749.png
new file mode 100644
index 0000000..db2d3f9
Binary files /dev/null and b/.assets/image-20221112172208749.png differ
diff --git a/.assets/image-20221112172221756.png b/.assets/image-20221112172221756.png
new file mode 100644
index 0000000..72d1c45
Binary files /dev/null and b/.assets/image-20221112172221756.png differ
diff --git a/.assets/image-20221112172239386.png b/.assets/image-20221112172239386.png
new file mode 100644
index 0000000..8c74f9d
Binary files /dev/null and b/.assets/image-20221112172239386.png differ
diff --git a/.assets/image-20221112172254809.png b/.assets/image-20221112172254809.png
new file mode 100644
index 0000000..d587ada
Binary files /dev/null and b/.assets/image-20221112172254809.png differ
diff --git a/.assets/image-20221112172348408.png b/.assets/image-20221112172348408.png
new file mode 100644
index 0000000..7f202c6
Binary files /dev/null and b/.assets/image-20221112172348408.png differ
diff --git a/.assets/image-20221112172420037.png b/.assets/image-20221112172420037.png
new file mode 100644
index 0000000..ed9e9d2
Binary files /dev/null and b/.assets/image-20221112172420037.png differ
diff --git a/.assets/image-20221112172716320.png b/.assets/image-20221112172716320.png
new file mode 100644
index 0000000..59286af
Binary files /dev/null and b/.assets/image-20221112172716320.png differ
diff --git a/.assets/image-20221112172858593.png b/.assets/image-20221112172858593.png
new file mode 100644
index 0000000..703615d
Binary files /dev/null and b/.assets/image-20221112172858593.png differ
diff --git a/.assets/image-20221112173534670.png b/.assets/image-20221112173534670.png
new file mode 100644
index 0000000..504cd6e
Binary files /dev/null and b/.assets/image-20221112173534670.png differ
diff --git a/.assets/image-20221112174211802.png b/.assets/image-20221112174211802.png
new file mode 100644
index 0000000..5f2da6f
Binary files /dev/null and b/.assets/image-20221112174211802.png differ
diff --git a/.assets/image-20221112180103750.png b/.assets/image-20221112180103750.png
new file mode 100644
index 0000000..6908be1
Binary files /dev/null and b/.assets/image-20221112180103750.png differ
diff --git a/.assets/image-20221112191712534.png b/.assets/image-20221112191712534.png
new file mode 100644
index 0000000..cf1953f
Binary files /dev/null and b/.assets/image-20221112191712534.png differ
diff --git a/.assets/image-20221112192133103.png b/.assets/image-20221112192133103.png
new file mode 100644
index 0000000..5fb211b
Binary files /dev/null and b/.assets/image-20221112192133103.png differ
diff --git a/.assets/image-20221112192509718.png b/.assets/image-20221112192509718.png
new file mode 100644
index 0000000..c73da28
Binary files /dev/null and b/.assets/image-20221112192509718.png differ
diff --git a/.assets/image-20221112192610543.png b/.assets/image-20221112192610543.png
new file mode 100644
index 0000000..245cb4e
Binary files /dev/null and b/.assets/image-20221112192610543.png differ
diff --git a/.assets/image-20221113125439857.png b/.assets/image-20221113125439857.png
new file mode 100644
index 0000000..cdd69c2
Binary files /dev/null and b/.assets/image-20221113125439857.png differ
diff --git a/.assets/image-20221113131044191.png b/.assets/image-20221113131044191.png
new file mode 100644
index 0000000..b74ab20
Binary files /dev/null and b/.assets/image-20221113131044191.png differ
diff --git a/.assets/image-20221113133624273.png b/.assets/image-20221113133624273.png
new file mode 100644
index 0000000..deabf6a
Binary files /dev/null and b/.assets/image-20221113133624273.png differ
diff --git a/.assets/image-20221113133904084.png b/.assets/image-20221113133904084.png
new file mode 100644
index 0000000..103ee21
Binary files /dev/null and b/.assets/image-20221113133904084.png differ
diff --git a/.assets/image-20221113134252407.png b/.assets/image-20221113134252407.png
new file mode 100644
index 0000000..fe2ed0f
Binary files /dev/null and b/.assets/image-20221113134252407.png differ
diff --git a/.assets/image-20221113134605331.png b/.assets/image-20221113134605331.png
new file mode 100644
index 0000000..fc69e89
Binary files /dev/null and b/.assets/image-20221113134605331.png differ
diff --git a/.assets/image-20221113142448939.png b/.assets/image-20221113142448939.png
new file mode 100644
index 0000000..84e0755
Binary files /dev/null and b/.assets/image-20221113142448939.png differ
diff --git a/.assets/image-20221113152513343.png b/.assets/image-20221113152513343.png
new file mode 100644
index 0000000..d3a217a
Binary files /dev/null and b/.assets/image-20221113152513343.png differ
diff --git a/.assets/image-20221113212706633.png b/.assets/image-20221113212706633.png
new file mode 100644
index 0000000..58a6cdb
Binary files /dev/null and b/.assets/image-20221113212706633.png differ
diff --git a/.assets/image-20221115215531879.png b/.assets/image-20221115215531879.png
new file mode 100644
index 0000000..484cbce
Binary files /dev/null and b/.assets/image-20221115215531879.png differ
diff --git a/.assets/image-20221116150122397.png b/.assets/image-20221116150122397.png
new file mode 100644
index 0000000..3e7195b
Binary files /dev/null and b/.assets/image-20221116150122397.png differ
diff --git a/.assets/image-20221116150901418.png b/.assets/image-20221116150901418.png
new file mode 100644
index 0000000..263d1c1
Binary files /dev/null and b/.assets/image-20221116150901418.png differ
diff --git a/.assets/image-20221116152032104.png b/.assets/image-20221116152032104.png
new file mode 100644
index 0000000..27ec34e
Binary files /dev/null and b/.assets/image-20221116152032104.png differ
diff --git a/.assets/image-20221116193340770.png b/.assets/image-20221116193340770.png
new file mode 100644
index 0000000..e71f1fa
Binary files /dev/null and b/.assets/image-20221116193340770.png differ
diff --git a/.assets/image-20221117121323757.png b/.assets/image-20221117121323757.png
new file mode 100644
index 0000000..bd64745
Binary files /dev/null and b/.assets/image-20221117121323757.png differ
diff --git a/.assets/image-20221119173731119.png b/.assets/image-20221119173731119.png
new file mode 100644
index 0000000..08d19eb
Binary files /dev/null and b/.assets/image-20221119173731119.png differ
diff --git a/.assets/image-20221119173918340.png b/.assets/image-20221119173918340.png
new file mode 100644
index 0000000..7775198
Binary files /dev/null and b/.assets/image-20221119173918340.png differ
diff --git a/.assets/image-20221119174445067.png b/.assets/image-20221119174445067.png
new file mode 100644
index 0000000..719019e
Binary files /dev/null and b/.assets/image-20221119174445067.png differ
diff --git a/.assets/image-20221119222946103.png b/.assets/image-20221119222946103.png
new file mode 100644
index 0000000..c482f16
Binary files /dev/null and b/.assets/image-20221119222946103.png differ
diff --git a/.assets/image-20221119223148604.png b/.assets/image-20221119223148604.png
new file mode 100644
index 0000000..651b6e1
Binary files /dev/null and b/.assets/image-20221119223148604.png differ
diff --git a/.assets/image-20221201134906999.png b/.assets/image-20221201134906999.png
new file mode 100644
index 0000000..0212df4
Binary files /dev/null and b/.assets/image-20221201134906999.png differ
diff --git a/.assets/image-20221201150945052.png b/.assets/image-20221201150945052.png
new file mode 100644
index 0000000..9f6193e
Binary files /dev/null and b/.assets/image-20221201150945052.png differ
diff --git a/.assets/image-20221201152530558.png b/.assets/image-20221201152530558.png
new file mode 100644
index 0000000..c1c8208
Binary files /dev/null and b/.assets/image-20221201152530558.png differ
diff --git a/.assets/image-20221201152904044.png b/.assets/image-20221201152904044.png
new file mode 100644
index 0000000..9e65a2a
Binary files /dev/null and b/.assets/image-20221201152904044.png differ
diff --git a/.assets/image-20221201155228196.png b/.assets/image-20221201155228196.png
new file mode 100644
index 0000000..00e389a
Binary files /dev/null and b/.assets/image-20221201155228196.png differ
diff --git a/.assets/image-20230202151939109.png b/.assets/image-20230202151939109.png
new file mode 100644
index 0000000..39981bc
Binary files /dev/null and b/.assets/image-20230202151939109.png differ
diff --git a/.assets/image-20230723132711865.png b/.assets/image-20230723132711865.png
new file mode 100644
index 0000000..7607573
Binary files /dev/null and b/.assets/image-20230723132711865.png differ
diff --git a/.assets/image-20230725152433502.png b/.assets/image-20230725152433502.png
new file mode 100644
index 0000000..2daf96e
Binary files /dev/null and b/.assets/image-20230725152433502.png differ
diff --git a/.assets/image-20230725153133419.png b/.assets/image-20230725153133419.png
new file mode 100644
index 0000000..6a802f6
Binary files /dev/null and b/.assets/image-20230725153133419.png differ
diff --git a/.assets/image-20230725153635454.png b/.assets/image-20230725153635454.png
new file mode 100644
index 0000000..3785972
Binary files /dev/null and b/.assets/image-20230725153635454.png differ
diff --git a/.assets/image-20230725154910307.png b/.assets/image-20230725154910307.png
new file mode 100644
index 0000000..a4104db
Binary files /dev/null and b/.assets/image-20230725154910307.png differ
diff --git a/.assets/ozone.png b/.assets/ozone.png
new file mode 100644
index 0000000..e419317
Binary files /dev/null and b/.assets/ozone.png differ
diff --git a/.assets/sentry_infantry12.gif b/.assets/sentry_infantry12.gif
new file mode 100644
index 0000000..a7dcfc0
Binary files /dev/null and b/.assets/sentry_infantry12.gif differ
diff --git a/.assets/v2-2797ea99d0d38eb9996993bb0ad77ab2_720w.webp b/.assets/v2-2797ea99d0d38eb9996993bb0ad77ab2_720w.webp
new file mode 100644
index 0000000..63a0078
Binary files /dev/null and b/.assets/v2-2797ea99d0d38eb9996993bb0ad77ab2_720w.webp differ
diff --git a/.assets/vscodedebug.png b/.assets/vscodedebug.png
new file mode 100644
index 0000000..e76fb36
Binary files /dev/null and b/.assets/vscodedebug.png differ
diff --git a/.assets/yuelu_badge.png b/.assets/yuelu_badge.png
new file mode 100644
index 0000000..ffbedf5
Binary files /dev/null and b/.assets/yuelu_badge.png differ
diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml
new file mode 100644
index 0000000..77afb9c
--- /dev/null
+++ b/.github/workflows/c-cpp.yml
@@ -0,0 +1,25 @@
+name: C/C++ CI
+
+on:
+ push:
+ branches: [ "master" ]
+ pull_request:
+ branches: [ "master" ]
+
+jobs:
+ build:
+
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: carlosperate/arm-none-eabi-gcc-action@v1
+ - run: arm-none-eabi-gcc --version
+
+ - uses: actions/checkout@v3
+ - name: make
+ run: make -j12
+
+ - uses: seanmiddleditch/gha-setup-ninja@master
+ - name: ninja
+ run: cd build && cmake -G Ninja .. && ninja
+
\ No newline at end of file
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0c7a57c
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,121 @@
+# Prerequisites
+*.d
+
+# Object files
+*.o
+*.ko
+*.obj
+*.elf
+
+# Linker output
+*.ilk
+*.map
+*.exp
+
+# Precompiled Headers
+*.gch
+*.pch
+
+# Libraries
+*.la
+*.lo
+
+# Shared objects (inc. Windows DLLs)
+*.dll
+*.so
+*.so.*
+*.dylib
+
+# Executables
+*.exe
+*.out
+*.app
+*.i*86
+*.x86_64
+
+# Debug files
+*.dSYM/
+*.su
+*.idb
+*.pdb
+
+# Kernel Module Compile Results
+*.mod*
+*.cmd
+.tmp_versions/
+modules.order
+Module.symvers
+Mkfile.old
+dkms.conf
+build
+./idea
+.vscode/.cortex-debug.peripherals.state.json
+.vscode/.cortex-debug.registers.state.json
+*.jdebug*
+settings.json
+
+# VSCode files
+*.vscode/
+
+#stm32env file
+*.stm32env
+
+#STM32Make.make file
+STM32Make.make
+
+# Duplicate files
+*(*)*
+
+# MATLAB files
+*/slprj/
+*/codegen/
+*.prj
+
+#build files
+./build
+
+# Keil v5 files
+*.bak
+*.lst
+*.lnp
+*.obj
+*.tmp
+*.TMP
+*.__i
+*.crf
+*.o
+*.d
+*.axf
+*.dep
+*.uvopt
+*.htm
+*.hsc
+~*
+*.map
+*uvgui*
+*.uvoptx
+*.sct
+*JLinkLog.txt
+*.dbgconf
+.vscode/tags
+.vscode/
+*.hex
+*.lnk
+
+*.scvd
+*.iex
+*.ini
+
+build/debug/Balance-9025test.bin
+build/debug/Balance-9025test.elf
+build/debug/Balance-9025test.elf.in
+build/debug/Balance-9025test.lss
+build/debug/Balance-9025test.elf.in
+STM32-for-VSCode.config.yaml
+.vscode/c_cpp_properties.json
+.vscode/launch.json
+.vscode/tasks.json
+openocd.cfg
+
+.idea
+.cmake-build-debug
\ No newline at end of file
diff --git a/.mxproject b/.mxproject
new file mode 100644
index 0000000..1490176
--- /dev/null
+++ b/.mxproject
@@ -0,0 +1,22 @@
+[PreviousGenFiles]
+HeaderPath=..\Inc
+HeaderFiles=gpio.h;FreeRTOSConfig.h;adc.h;can.h;crc.h;dac.h;dma.h;i2c.h;rng.h;rtc.h;spi.h;tim.h;usart.h;usb_device.h;usbd_conf.h;usbd_desc.h;usbd_cdc_if.h;stm32f4xx_it.h;stm32f4xx_hal_conf.h;main.h;
+SourcePath=..\Src
+SourceFiles=gpio.c;freertos.c;adc.c;can.c;crc.c;dac.c;dma.c;i2c.c;rng.c;rtc.c;spi.c;tim.c;usart.c;usb_device.c;usbd_conf.c;usbd_desc.c;usbd_cdc_if.c;stm32f4xx_it.c;stm32f4xx_hal_msp.c;stm32f4xx_hal_timebase_tim.c;main.c;
+
+[PreviousLibFiles]
+LibFiles=Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_pcd.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_pcd_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_usb.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rcc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rcc_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_bus.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_rcc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_system.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_utils.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_flash.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_flash_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_flash_ramfunc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_gpio.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_gpio_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_gpio.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_dma_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_dma.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_dma.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_dmamux.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_pwr.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_pwr_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_pwr.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_cortex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_cortex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal.h;Drivers\STM32F4xx_HAL_Driver\Inc\Legacy\stm32_hal_legacy.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_def.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_exti.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_exti.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_adc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_adc_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_adc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_can.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_crc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_crc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_dac.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_dac.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_dac_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_i2c.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_i2c.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_i2c_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rng.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_rng.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rtc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_rtc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rtc_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_spi.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_tim.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_tim_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_tim.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_uart.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_usart.h;Middlewares\Third_Party\FreeRTOS\Source\include\croutine.h;Middlewares\Third_Party\FreeRTOS\Source\include\deprecated_definitions.h;Middlewares\Third_Party\FreeRTOS\Source\include\event_groups.h;Middlewares\Third_Party\FreeRTOS\Source\include\FreeRTOS.h;Middlewares\Third_Party\FreeRTOS\Source\include\list.h;Middlewares\Third_Party\FreeRTOS\Source\include\message_buffer.h;Middlewares\Third_Party\FreeRTOS\Source\include\mpu_prototypes.h;Middlewares\Third_Party\FreeRTOS\Source\include\mpu_wrappers.h;Middlewares\Third_Party\FreeRTOS\Source\include\portable.h;Middlewares\Third_Party\FreeRTOS\Source\include\projdefs.h;Middlewares\Third_Party\FreeRTOS\Source\include\queue.h;Middlewares\Third_Party\FreeRTOS\Source\include\semphr.h;Middlewares\Third_Party\FreeRTOS\Source\include\stack_macros.h;Middlewares\Third_Party\FreeRTOS\Source\include\StackMacros.h;Middlewares\Third_Party\FreeRTOS\Source\include\stream_buffer.h;Middlewares\Third_Party\FreeRTOS\Source\include\task.h;Middlewares\Third_Party\FreeRTOS\Source\include\timers.h;Middlewares\Third_Party\FreeRTOS\Source\include\atomic.h;Middlewares\Third_Party\FreeRTOS\Source\CMSIS_RTOS\cmsis_os.h;Middlewares\Third_Party\FreeRTOS\Source\portable\GCC\ARM_CM4F\portmacro.h;Middlewares\ST\STM32_USB_Device_Library\Core\Inc\usbd_core.h;Middlewares\ST\STM32_USB_Device_Library\Core\Inc\usbd_ctlreq.h;Middlewares\ST\STM32_USB_Device_Library\Core\Inc\usbd_def.h;Middlewares\ST\STM32_USB_Device_Library\Core\Inc\usbd_ioreq.h;Middlewares\ST\STM32_USB_Device_Library\Class\CDC\Inc\usbd_cdc.h;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pcd.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pcd_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_ll_usb.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rcc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rcc_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_flash.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_flash_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_flash_ramfunc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_gpio.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dma_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dma.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pwr.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pwr_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_cortex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_exti.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_adc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_adc_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_ll_adc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_can.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_crc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dac.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dac_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_i2c.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_i2c_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rng.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rtc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rtc_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_spi.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_tim.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_tim_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_uart.c;Middlewares\Third_Party\FreeRTOS\Source\croutine.c;Middlewares\Third_Party\FreeRTOS\Source\event_groups.c;Middlewares\Third_Party\FreeRTOS\Source\list.c;Middlewares\Third_Party\FreeRTOS\Source\queue.c;Middlewares\Third_Party\FreeRTOS\Source\stream_buffer.c;Middlewares\Third_Party\FreeRTOS\Source\tasks.c;Middlewares\Third_Party\FreeRTOS\Source\timers.c;Middlewares\Third_Party\FreeRTOS\Source\CMSIS_RTOS\cmsis_os.c;Middlewares\Third_Party\FreeRTOS\Source\portable\MemMang\heap_4.c;Middlewares\Third_Party\FreeRTOS\Source\portable\GCC\ARM_CM4F\port.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_core.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_ctlreq.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_ioreq.c;Middlewares\ST\STM32_USB_Device_Library\Class\CDC\Src\usbd_cdc.c;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_pcd.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_pcd_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_usb.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rcc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rcc_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_bus.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_rcc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_system.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_utils.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_flash.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_flash_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_flash_ramfunc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_gpio.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_gpio_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_gpio.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_dma_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_dma.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_dma.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_dmamux.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_pwr.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_pwr_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_pwr.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_cortex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_cortex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal.h;Drivers\STM32F4xx_HAL_Driver\Inc\Legacy\stm32_hal_legacy.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_def.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_exti.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_exti.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_adc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_adc_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_adc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_can.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_crc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_crc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_dac.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_dac.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_dac_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_i2c.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_i2c.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_i2c_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rng.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_rng.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rtc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_rtc.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_rtc_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_spi.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_tim.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_tim_ex.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_tim.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_hal_uart.h;Drivers\STM32F4xx_HAL_Driver\Inc\stm32f4xx_ll_usart.h;Middlewares\Third_Party\FreeRTOS\Source\include\croutine.h;Middlewares\Third_Party\FreeRTOS\Source\include\deprecated_definitions.h;Middlewares\Third_Party\FreeRTOS\Source\include\event_groups.h;Middlewares\Third_Party\FreeRTOS\Source\include\FreeRTOS.h;Middlewares\Third_Party\FreeRTOS\Source\include\list.h;Middlewares\Third_Party\FreeRTOS\Source\include\message_buffer.h;Middlewares\Third_Party\FreeRTOS\Source\include\mpu_prototypes.h;Middlewares\Third_Party\FreeRTOS\Source\include\mpu_wrappers.h;Middlewares\Third_Party\FreeRTOS\Source\include\portable.h;Middlewares\Third_Party\FreeRTOS\Source\include\projdefs.h;Middlewares\Third_Party\FreeRTOS\Source\include\queue.h;Middlewares\Third_Party\FreeRTOS\Source\include\semphr.h;Middlewares\Third_Party\FreeRTOS\Source\include\stack_macros.h;Middlewares\Third_Party\FreeRTOS\Source\include\StackMacros.h;Middlewares\Third_Party\FreeRTOS\Source\include\stream_buffer.h;Middlewares\Third_Party\FreeRTOS\Source\include\task.h;Middlewares\Third_Party\FreeRTOS\Source\include\timers.h;Middlewares\Third_Party\FreeRTOS\Source\include\atomic.h;Middlewares\Third_Party\FreeRTOS\Source\CMSIS_RTOS\cmsis_os.h;Middlewares\Third_Party\FreeRTOS\Source\portable\GCC\ARM_CM4F\portmacro.h;Middlewares\ST\STM32_USB_Device_Library\Core\Inc\usbd_core.h;Middlewares\ST\STM32_USB_Device_Library\Core\Inc\usbd_ctlreq.h;Middlewares\ST\STM32_USB_Device_Library\Core\Inc\usbd_def.h;Middlewares\ST\STM32_USB_Device_Library\Core\Inc\usbd_ioreq.h;Middlewares\ST\STM32_USB_Device_Library\Class\CDC\Inc\usbd_cdc.h;Drivers\CMSIS\Device\ST\STM32F4xx\Include\stm32f407xx.h;Drivers\CMSIS\Device\ST\STM32F4xx\Include\stm32f4xx.h;Drivers\CMSIS\Device\ST\STM32F4xx\Include\system_stm32f4xx.h;Drivers\CMSIS\Device\ST\STM32F4xx\Source\Templates\system_stm32f4xx.c;Drivers\CMSIS\Include\cmsis_armcc.h;Drivers\CMSIS\Include\cmsis_armclang.h;Drivers\CMSIS\Include\cmsis_compiler.h;Drivers\CMSIS\Include\cmsis_gcc.h;Drivers\CMSIS\Include\cmsis_iccarm.h;Drivers\CMSIS\Include\cmsis_version.h;Drivers\CMSIS\Include\core_armv8mbl.h;Drivers\CMSIS\Include\core_armv8mml.h;Drivers\CMSIS\Include\core_cm0.h;Drivers\CMSIS\Include\core_cm0plus.h;Drivers\CMSIS\Include\core_cm1.h;Drivers\CMSIS\Include\core_cm23.h;Drivers\CMSIS\Include\core_cm3.h;Drivers\CMSIS\Include\core_cm33.h;Drivers\CMSIS\Include\core_cm4.h;Drivers\CMSIS\Include\core_cm7.h;Drivers\CMSIS\Include\core_sc000.h;Drivers\CMSIS\Include\core_sc300.h;Drivers\CMSIS\Include\mpu_armv7.h;Drivers\CMSIS\Include\mpu_armv8.h;Drivers\CMSIS\Include\tz_context.h;
+
+[ThirdPartyIp]
+ThirdPartyIpNumber=1
+ThirdPartyIpName#0=STMicroelectronics.X-CUBE-ALGOBUILD.1.3.0
+
+[ThirdPartyIp#STMicroelectronics.X-CUBE-ALGOBUILD.1.3.0]
+library=..\Middlewares\ST\ARM\DSP\Lib\libarm_cortexM4lf_math.a;
+header=..\Middlewares\ST\ARM\DSP\Inc\arm_math.h;
+
+[PreviousUsedMakefileFiles]
+SourceFiles=Src\main.c;Src\gpio.c;Src\freertos.c;Src\adc.c;Src\can.c;Src\crc.c;Src\dac.c;Src\dma.c;Src\i2c.c;Src\rng.c;Src\rtc.c;Src\spi.c;Src\tim.c;Src\usart.c;Src\usb_device.c;Src\usbd_conf.c;Src\usbd_desc.c;Src\usbd_cdc_if.c;Src\stm32f4xx_it.c;Src\stm32f4xx_hal_msp.c;Src\stm32f4xx_hal_timebase_tim.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pcd.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pcd_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_ll_usb.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rcc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rcc_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_flash.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_flash_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_flash_ramfunc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_gpio.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dma_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dma.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pwr.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pwr_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_cortex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_exti.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_adc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_adc_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_ll_adc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_can.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_crc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dac.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dac_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_i2c.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_i2c_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rng.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rtc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rtc_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_spi.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_tim.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_tim_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_uart.c;Middlewares\Third_Party\FreeRTOS\Source\croutine.c;Middlewares\Third_Party\FreeRTOS\Source\event_groups.c;Middlewares\Third_Party\FreeRTOS\Source\list.c;Middlewares\Third_Party\FreeRTOS\Source\queue.c;Middlewares\Third_Party\FreeRTOS\Source\stream_buffer.c;Middlewares\Third_Party\FreeRTOS\Source\tasks.c;Middlewares\Third_Party\FreeRTOS\Source\timers.c;Middlewares\Third_Party\FreeRTOS\Source\CMSIS_RTOS\cmsis_os.c;Middlewares\Third_Party\FreeRTOS\Source\portable\MemMang\heap_4.c;Middlewares\Third_Party\FreeRTOS\Source\portable\GCC\ARM_CM4F\port.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_core.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_ctlreq.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_ioreq.c;Middlewares\ST\STM32_USB_Device_Library\Class\CDC\Src\usbd_cdc.c;Drivers\CMSIS\Device\ST\STM32F4xx\Source\Templates\system_stm32f4xx.c;Src\system_stm32f4xx.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pcd.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pcd_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_ll_usb.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rcc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rcc_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_flash.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_flash_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_flash_ramfunc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_gpio.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dma_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dma.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pwr.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_pwr_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_cortex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_exti.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_adc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_adc_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_ll_adc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_can.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_crc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dac.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_dac_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_i2c.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_i2c_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rng.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rtc.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_rtc_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_spi.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_tim.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_tim_ex.c;Drivers\STM32F4xx_HAL_Driver\Src\stm32f4xx_hal_uart.c;Middlewares\Third_Party\FreeRTOS\Source\croutine.c;Middlewares\Third_Party\FreeRTOS\Source\event_groups.c;Middlewares\Third_Party\FreeRTOS\Source\list.c;Middlewares\Third_Party\FreeRTOS\Source\queue.c;Middlewares\Third_Party\FreeRTOS\Source\stream_buffer.c;Middlewares\Third_Party\FreeRTOS\Source\tasks.c;Middlewares\Third_Party\FreeRTOS\Source\timers.c;Middlewares\Third_Party\FreeRTOS\Source\CMSIS_RTOS\cmsis_os.c;Middlewares\Third_Party\FreeRTOS\Source\portable\MemMang\heap_4.c;Middlewares\Third_Party\FreeRTOS\Source\portable\GCC\ARM_CM4F\port.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_core.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_ctlreq.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_ioreq.c;Middlewares\ST\STM32_USB_Device_Library\Class\CDC\Src\usbd_cdc.c;Drivers\CMSIS\Device\ST\STM32F4xx\Source\Templates\system_stm32f4xx.c;Src\system_stm32f4xx.c;;;Middlewares\Third_Party\FreeRTOS\Source\croutine.c;Middlewares\Third_Party\FreeRTOS\Source\event_groups.c;Middlewares\Third_Party\FreeRTOS\Source\list.c;Middlewares\Third_Party\FreeRTOS\Source\queue.c;Middlewares\Third_Party\FreeRTOS\Source\stream_buffer.c;Middlewares\Third_Party\FreeRTOS\Source\tasks.c;Middlewares\Third_Party\FreeRTOS\Source\timers.c;Middlewares\Third_Party\FreeRTOS\Source\CMSIS_RTOS\cmsis_os.c;Middlewares\Third_Party\FreeRTOS\Source\portable\MemMang\heap_4.c;Middlewares\Third_Party\FreeRTOS\Source\portable\GCC\ARM_CM4F\port.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_core.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_ctlreq.c;Middlewares\ST\STM32_USB_Device_Library\Core\Src\usbd_ioreq.c;Middlewares\ST\STM32_USB_Device_Library\Class\CDC\Src\usbd_cdc.c;
+HeaderPath=Drivers\STM32F4xx_HAL_Driver\Inc;Drivers\STM32F4xx_HAL_Driver\Inc\Legacy;Middlewares\Third_Party\FreeRTOS\Source\include;Middlewares\Third_Party\FreeRTOS\Source\CMSIS_RTOS;Middlewares\Third_Party\FreeRTOS\Source\portable\GCC\ARM_CM4F;Middlewares\ST\STM32_USB_Device_Library\Core\Inc;Middlewares\ST\STM32_USB_Device_Library\Class\CDC\Inc;Drivers\CMSIS\Device\ST\STM32F4xx\Include;Drivers\CMSIS\Include;Middlewares\ST\ARM\DSP\Inc;Inc;
+CDefines=USE_HAL_DRIVER;STM32F407xx;USE_HAL_DRIVER;USE_HAL_DRIVER;
+
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..7f7fc41
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,115 @@
+cmake_minimum_required(VERSION 3.16)
+# 指定编译平台/架构与语言标准, 推荐指定Ninja为构建工具,可以加快编译速度(相比make)
+set(CMAKE_SYSTEM_NAME Generic)
+set(CMAKE_SYSTEM_PROCESSOR arm)
+set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
+# 指定工具链
+set(CMAKE_C_COMPILER_FORCED TRUE) # skip compiler test
+set(CMAKE_CXX_COMPILER_FORCED TRUE)
+set(CMAKE_C_COMPILER arm-none-eabi-gcc)
+set(CMAKE_ASM_COMPILER arm-none-eabi-gcc)
+set(CMAKE_OBJCOPY arm-none-eabi-objcopy)
+set(CMAKE_OBJDUMP arm-none-eabi-objdump)
+set(SIZE arm-none-eabi-size)
+set(CMAKE_AR arm-none-eabi-ar)
+set(CMAKE_C_STANDARD 11)
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+
+# 指定工程名称和语言类型
+project(basic_framework C ASM)
+
+# 选择构建类型
+set(CMAKE_BUILD_TYPE Debug) # Debug Release RelWithDebInfo MinSizeRel
+
+# board specific settings, arch/fpu/instruction
+set(MCU_FLAGS -mcpu=cortex-m4 -mthumb -mthumb-interwork -mfloat-abi=hard -mfpu=fpv4-sp-d16)
+set(LINKER_SCRIPT "${CMAKE_SOURCE_DIR}/STM32F407IGHx_FLASH.ld") # 指定链接脚本
+set(DSP_NAME "libCMSISDSP.a") # 指定DSP库名称
+link_directories(${CMAKE_SOURCE_DIR}/Middlewares/ST/ARM/DSP/Lib)
+
+# Generic compiler settings for optimization and basic link lib
+add_compile_options(-pipe ${MCU_FLAGS} -Wall -Werror -fmessage-length=0 # basic options
+ -ffunction-sections -fdata-sections -fno-common # optimize options
+ )
+add_link_options(-pipe ${MCU_FLAGS} -T${LINKER_SCRIPT} -Wl,--no-warn-rwx-segments # close RWX warning
+ -lm -lc -lnosys # lib options
+ -Wl,--gc-sections -flto -specs=nano.specs -specs=nosys.specs # optimize options
+ -Wl,-Map=${PROJECT_BINARY_DIR}/${PROJECT_NAME}.map -Wl,--cref -Wl,--print-memory-usage # map options
+ ) # if your executable is too large , try option '-s' to strip symbols
+
+# add_compile_definitions() works for compile stage
+# while add_definitions() works for both compile and link stage
+add_definitions(
+ -DUSE_HAL_DRIVER
+ -DSTM32F407xx
+ -DARM_MATH_CM4
+ ) # need -DLib folder.
+ * - arm_cortexM7lfdp_math.lib (Cortex-M7, Little endian, Double Precision Floating Point Unit)
+ * - arm_cortexM7bfdp_math.lib (Cortex-M7, Big endian, Double Precision Floating Point Unit)
+ * - arm_cortexM7lfsp_math.lib (Cortex-M7, Little endian, Single Precision Floating Point Unit)
+ * - arm_cortexM7bfsp_math.lib (Cortex-M7, Big endian and Single Precision Floating Point Unit on)
+ * - arm_cortexM7l_math.lib (Cortex-M7, Little endian)
+ * - arm_cortexM7b_math.lib (Cortex-M7, Big endian)
+ * - arm_cortexM4lf_math.lib (Cortex-M4, Little endian, Floating Point Unit)
+ * - arm_cortexM4bf_math.lib (Cortex-M4, Big endian, Floating Point Unit)
+ * - arm_cortexM4l_math.lib (Cortex-M4, Little endian)
+ * - arm_cortexM4b_math.lib (Cortex-M4, Big endian)
+ * - arm_cortexM3l_math.lib (Cortex-M3, Little endian)
+ * - arm_cortexM3b_math.lib (Cortex-M3, Big endian)
+ * - arm_cortexM0l_math.lib (Cortex-M0 / Cortex-M0+, Little endian)
+ * - arm_cortexM0b_math.lib (Cortex-M0 / Cortex-M0+, Big endian)
+ * - arm_ARMv8MBLl_math.lib (Armv8-M Baseline, Little endian)
+ * - arm_ARMv8MMLl_math.lib (Armv8-M Mainline, Little endian)
+ * - arm_ARMv8MMLlfsp_math.lib (Armv8-M Mainline, Little endian, Single Precision Floating Point Unit)
+ * - arm_ARMv8MMLld_math.lib (Armv8-M Mainline, Little endian, DSP instructions)
+ * - arm_ARMv8MMLldfsp_math.lib (Armv8-M Mainline, Little endian, DSP instructions, Single Precision Floating Point Unit)
+ *
+ * The library functions are declared in the public file arm_math.h which is placed in the Include folder.
+ * Simply include this file and link the appropriate library in the application and begin calling the library functions. The Library supports single
+ * public header file arm_math.h for Cortex-M cores with little endian and big endian. Same header file will be used for floating point unit(FPU) variants.
+ * Define the appropriate preprocessor macro ARM_MATH_CM7 or ARM_MATH_CM4 or ARM_MATH_CM3 or
+ * ARM_MATH_CM0 or ARM_MATH_CM0PLUS depending on the target processor in the application.
+ * For Armv8-M cores define preprocessor macro ARM_MATH_ARMV8MBL or ARM_MATH_ARMV8MML.
+ * Set preprocessor macro __DSP_PRESENT if Armv8-M Mainline core supports DSP instructions.
+ *
+ *
+ * Examples
+ * --------
+ *
+ * The library ships with a number of examples which demonstrate how to use the library functions.
+ *
+ * Toolchain Support
+ * ------------
+ *
+ * The library has been developed and tested with MDK version 5.14.0.0
+ * The library is being tested in GCC and IAR toolchains and updates on this activity will be made available shortly.
+ *
+ * Building the Library
+ * ------------
+ *
+ * The library installer contains a project file to rebuild libraries on MDK toolchain in the CMSIS\\DSP_Lib\\Source\\ARM folder.
+ * - arm_cortexM_math.uvprojx
+ *
+ *
+ * The libraries can be built by opening the arm_cortexM_math.uvprojx project in MDK-ARM, selecting a specific target, and defining the optional preprocessor macros detailed above.
+ *
+ * Preprocessor Macros
+ * ------------
+ *
+ * Each library project have different preprocessor macros.
+ *
+ * - UNALIGNED_SUPPORT_DISABLE:
+ *
+ * Define macro UNALIGNED_SUPPORT_DISABLE, If the silicon does not support unaligned memory access
+ *
+ * - ARM_MATH_BIG_ENDIAN:
+ *
+ * Define macro ARM_MATH_BIG_ENDIAN to build the library for big endian targets. By default library builds for little endian targets.
+ *
+ * - ARM_MATH_MATRIX_CHECK:
+ *
+ * Define macro ARM_MATH_MATRIX_CHECK for checking on the input and output sizes of matrices
+ *
+ * - ARM_MATH_ROUNDING:
+ *
+ * Define macro ARM_MATH_ROUNDING for rounding on support functions
+ *
+ * - ARM_MATH_CMx:
+ *
+ * Define macro ARM_MATH_CM4 for building the library on Cortex-M4 target, ARM_MATH_CM3 for building library on Cortex-M3 target
+ * and ARM_MATH_CM0 for building library on Cortex-M0 target, ARM_MATH_CM0PLUS for building library on Cortex-M0+ target, and
+ * ARM_MATH_CM7 for building the library on cortex-M7.
+ *
+ * - ARM_MATH_ARMV8MxL:
+ *
+ * Define macro ARM_MATH_ARMV8MBL for building the library on Armv8-M Baseline target, ARM_MATH_ARMV8MML for building library
+ * on Armv8-M Mainline target.
+ *
+ * - __FPU_PRESENT:
+ *
+ * Initialize macro __FPU_PRESENT = 1 when building on FPU supported Targets. Enable this macro for floating point libraries.
+ *
+ * - __DSP_PRESENT:
+ *
+ * Initialize macro __DSP_PRESENT = 1 when Armv8-M Mainline core supports DSP instructions.
+ *
+ *
+ * typedef struct
+ * {
+ * uint16_t numRows; // number of rows of the matrix.
+ * uint16_t numCols; // number of columns of the matrix.
+ * float32_t *pData; // points to the data of the matrix.
+ * } arm_matrix_instance_f32;
+ *
+ * There are similar definitions for Q15 and Q31 data types.
+ *
+ * The structure specifies the size of the matrix and then points to
+ * an array of data. The array is of size numRows X numCols
+ * and the values are arranged in row order. That is, the
+ * matrix element (i, j) is stored at:
+ * + * pData[i*numCols + j] + *+ * + * \par Init Functions + * There is an associated initialization function for each type of matrix + * data structure. + * The initialization function sets the values of the internal structure fields. + * Refer to the function
arm_mat_init_f32(), arm_mat_init_q31()
+ * and arm_mat_init_q15() for floating-point, Q31 and Q15 types, respectively.
+ *
+ * \par
+ * Use of the initialization function is optional. However, if initialization function is used
+ * then the instance structure cannot be placed into a const data section.
+ * To place the instance structure in a const data
+ * section, manually initialize the data structure. For example:
+ * + *+ * wherearm_matrix_instance_f32 S = {nRows, nColumns, pData};+ *arm_matrix_instance_q31 S = {nRows, nColumns, pData};+ *arm_matrix_instance_q15 S = {nRows, nColumns, pData};+ *
nRows specifies the number of rows, nColumns
+ * specifies the number of columns, and pData points to the
+ * data array.
+ *
+ * \par Size Checking
+ * By default all of the matrix functions perform size checking on the input and
+ * output matrices. For example, the matrix addition function verifies that the
+ * two input matrices and the output matrix all have the same number of rows and
+ * columns. If the size check fails the functions return:
+ * + * ARM_MATH_SIZE_MISMATCH + *+ * Otherwise the functions return + *
+ * ARM_MATH_SUCCESS + *+ * There is some overhead associated with this matrix size checking. + * The matrix size checking is enabled via the \#define + *
+ * ARM_MATH_MATRIX_CHECK + *+ * within the library project settings. By default this macro is defined + * and size checking is enabled. By changing the project settings and + * undefining this macro size checking is eliminated and the functions + * run a bit faster. With size checking disabled the functions always + * return
ARM_MATH_SUCCESS.
+ */
+
+/**
+ * @defgroup groupTransforms Transform Functions
+ */
+
+/**
+ * @defgroup groupController Controller Functions
+ */
+
+/**
+ * @defgroup groupStats Statistics Functions
+ */
+/**
+ * @defgroup groupSupport Support Functions
+ */
+
+/**
+ * @defgroup groupInterpolation Interpolation Functions
+ * These functions perform 1- and 2-dimensional interpolation of data.
+ * Linear interpolation is used for 1-dimensional data and
+ * bilinear interpolation is used for 2-dimensional data.
+ */
+
+/**
+ * @defgroup groupExamples Examples
+ */
+#ifndef _ARM_MATH_H
+#define _ARM_MATH_H
+
+/* Compiler specific diagnostic adjustment */
+#if defined ( __CC_ARM )
+
+#elif defined ( __ARMCC_VERSION ) && ( __ARMCC_VERSION >= 6010050 )
+
+#elif defined ( __GNUC__ )
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wsign-conversion"
+#pragma GCC diagnostic ignored "-Wconversion"
+#pragma GCC diagnostic ignored "-Wunused-parameter"
+
+#elif defined ( __ICCARM__ )
+
+#elif defined ( __TI_ARM__ )
+
+#elif defined ( __CSMC__ )
+
+#elif defined ( __TASKING__ )
+
+#else
+ #error Unknown compiler
+#endif
+
+
+#define __CMSIS_GENERIC /* disable NVIC and Systick functions */
+
+#if defined(ARM_MATH_CM7)
+ #include "core_cm7.h"
+ #define ARM_MATH_DSP
+#elif defined (ARM_MATH_CM4)
+ #include "core_cm4.h"
+ #define ARM_MATH_DSP
+#elif defined (ARM_MATH_CM3)
+ #include "core_cm3.h"
+#elif defined (ARM_MATH_CM0)
+ #include "core_cm0.h"
+ #define ARM_MATH_CM0_FAMILY
+#elif defined (ARM_MATH_CM0PLUS)
+ #include "core_cm0plus.h"
+ #define ARM_MATH_CM0_FAMILY
+#elif defined (ARM_MATH_ARMV8MBL)
+ #include "core_armv8mbl.h"
+ #define ARM_MATH_CM0_FAMILY
+#elif defined (ARM_MATH_ARMV8MML)
+ #include "core_armv8mml.h"
+ #if (defined (__DSP_PRESENT) && (__DSP_PRESENT == 1))
+ #define ARM_MATH_DSP
+ #endif
+#else
+ #error "Define according the used Cortex core ARM_MATH_CM7, ARM_MATH_CM4, ARM_MATH_CM3, ARM_MATH_CM0PLUS, ARM_MATH_CM0, ARM_MATH_ARMV8MBL, ARM_MATH_ARMV8MML"
+#endif
+
+#undef __CMSIS_GENERIC /* enable NVIC and Systick functions */
+#include "string.h"
+#include "math.h"
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+ /**
+ * @brief Macros required for reciprocal calculation in Normalized LMS
+ */
+
+#define DELTA_Q31 (0x100)
+#define DELTA_Q15 0x5
+#define INDEX_MASK 0x0000003F
+#ifndef PI
+ #define PI 3.14159265358979f
+#endif
+
+ /**
+ * @brief Macros required for SINE and COSINE Fast math approximations
+ */
+
+#define FAST_MATH_TABLE_SIZE 512
+#define FAST_MATH_Q31_SHIFT (32 - 10)
+#define FAST_MATH_Q15_SHIFT (16 - 10)
+#define CONTROLLER_Q31_SHIFT (32 - 9)
+#define TABLE_SPACING_Q31 0x400000
+#define TABLE_SPACING_Q15 0x80
+
+ /**
+ * @brief Macros required for SINE and COSINE Controller functions
+ */
+ /* 1.31(q31) Fixed value of 2/360 */
+ /* -1 to +1 is divided into 360 values so total spacing is (2/360) */
+#define INPUT_SPACING 0xB60B61
+
+ /**
+ * @brief Macro for Unaligned Support
+ */
+#ifndef UNALIGNED_SUPPORT_DISABLE
+ #define ALIGN4
+#else
+ #if defined (__GNUC__)
+ #define ALIGN4 __attribute__((aligned(4)))
+ #else
+ #define ALIGN4 __align(4)
+ #endif
+#endif /* #ifndef UNALIGNED_SUPPORT_DISABLE */
+
+ /**
+ * @brief Error status returned by some functions in the library.
+ */
+
+ typedef enum
+ {
+ ARM_MATH_SUCCESS = 0, /**< No error */
+ ARM_MATH_ARGUMENT_ERROR = -1, /**< One or more arguments are incorrect */
+ ARM_MATH_LENGTH_ERROR = -2, /**< Length of data buffer is incorrect */
+ ARM_MATH_SIZE_MISMATCH = -3, /**< Size of matrices is not compatible with the operation. */
+ ARM_MATH_NANINF = -4, /**< Not-a-number (NaN) or infinity is generated */
+ ARM_MATH_SINGULAR = -5, /**< Generated by matrix inversion if the input matrix is singular and cannot be inverted. */
+ ARM_MATH_TEST_FAILURE = -6 /**< Test Failed */
+ } arm_status;
+
+ /**
+ * @brief 8-bit fractional data type in 1.7 format.
+ */
+ typedef int8_t q7_t;
+
+ /**
+ * @brief 16-bit fractional data type in 1.15 format.
+ */
+ typedef int16_t q15_t;
+
+ /**
+ * @brief 32-bit fractional data type in 1.31 format.
+ */
+ typedef int32_t q31_t;
+
+ /**
+ * @brief 64-bit fractional data type in 1.63 format.
+ */
+ typedef int64_t q63_t;
+
+ /**
+ * @brief 32-bit floating-point type definition.
+ */
+ typedef float float32_t;
+
+ /**
+ * @brief 64-bit floating-point type definition.
+ */
+ typedef double float64_t;
+
+ /**
+ * @brief definition to read/write two 16 bit values.
+ */
+#if defined ( __CC_ARM )
+ #define __SIMD32_TYPE int32_t __packed
+ #define CMSIS_UNUSED __attribute__((unused))
+ #define CMSIS_INLINE __attribute__((always_inline))
+
+#elif defined ( __ARMCC_VERSION ) && ( __ARMCC_VERSION >= 6010050 )
+ #define __SIMD32_TYPE int32_t
+ #define CMSIS_UNUSED __attribute__((unused))
+ #define CMSIS_INLINE __attribute__((always_inline))
+
+#elif defined ( __GNUC__ )
+ #define __SIMD32_TYPE int32_t
+ #define CMSIS_UNUSED __attribute__((unused))
+ #define CMSIS_INLINE __attribute__((always_inline))
+
+#elif defined ( __ICCARM__ )
+ #define __SIMD32_TYPE int32_t __packed
+ #define CMSIS_UNUSED
+ #define CMSIS_INLINE
+
+#elif defined ( __TI_ARM__ )
+ #define __SIMD32_TYPE int32_t
+ #define CMSIS_UNUSED __attribute__((unused))
+ #define CMSIS_INLINE
+
+#elif defined ( __CSMC__ )
+ #define __SIMD32_TYPE int32_t
+ #define CMSIS_UNUSED
+ #define CMSIS_INLINE
+
+#elif defined ( __TASKING__ )
+ #define __SIMD32_TYPE __unaligned int32_t
+ #define CMSIS_UNUSED
+ #define CMSIS_INLINE
+
+#else
+ #error Unknown compiler
+#endif
+
+#define __SIMD32(addr) (*(__SIMD32_TYPE **) & (addr))
+#define __SIMD32_CONST(addr) ((__SIMD32_TYPE *)(addr))
+#define _SIMD32_OFFSET(addr) (*(__SIMD32_TYPE *) (addr))
+#define __SIMD64(addr) (*(int64_t **) & (addr))
+
+#if !defined (ARM_MATH_DSP)
+ /**
+ * @brief definition to pack two 16 bit values.
+ */
+#define __PKHBT(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0x0000FFFF) | \
+ (((int32_t)(ARG2) << ARG3) & (int32_t)0xFFFF0000) )
+#define __PKHTB(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0xFFFF0000) | \
+ (((int32_t)(ARG2) >> ARG3) & (int32_t)0x0000FFFF) )
+
+#endif /* !defined (ARM_MATH_DSP) */
+
+ /**
+ * @brief definition to pack four 8 bit values.
+ */
+#ifndef ARM_MATH_BIG_ENDIAN
+
+#define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v0) << 0) & (int32_t)0x000000FF) | \
+ (((int32_t)(v1) << 8) & (int32_t)0x0000FF00) | \
+ (((int32_t)(v2) << 16) & (int32_t)0x00FF0000) | \
+ (((int32_t)(v3) << 24) & (int32_t)0xFF000000) )
+#else
+
+#define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v3) << 0) & (int32_t)0x000000FF) | \
+ (((int32_t)(v2) << 8) & (int32_t)0x0000FF00) | \
+ (((int32_t)(v1) << 16) & (int32_t)0x00FF0000) | \
+ (((int32_t)(v0) << 24) & (int32_t)0xFF000000) )
+
+#endif
+
+
+ /**
+ * @brief Clips Q63 to Q31 values.
+ */
+ CMSIS_INLINE __STATIC_INLINE q31_t clip_q63_to_q31(
+ q63_t x)
+ {
+ return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ?
+ ((0x7FFFFFFF ^ ((q31_t) (x >> 63)))) : (q31_t) x;
+ }
+
+ /**
+ * @brief Clips Q63 to Q15 values.
+ */
+ CMSIS_INLINE __STATIC_INLINE q15_t clip_q63_to_q15(
+ q63_t x)
+ {
+ return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ?
+ ((0x7FFF ^ ((q15_t) (x >> 63)))) : (q15_t) (x >> 15);
+ }
+
+ /**
+ * @brief Clips Q31 to Q7 values.
+ */
+ CMSIS_INLINE __STATIC_INLINE q7_t clip_q31_to_q7(
+ q31_t x)
+ {
+ return ((q31_t) (x >> 24) != ((q31_t) x >> 23)) ?
+ ((0x7F ^ ((q7_t) (x >> 31)))) : (q7_t) x;
+ }
+
+ /**
+ * @brief Clips Q31 to Q15 values.
+ */
+ CMSIS_INLINE __STATIC_INLINE q15_t clip_q31_to_q15(
+ q31_t x)
+ {
+ return ((q31_t) (x >> 16) != ((q31_t) x >> 15)) ?
+ ((0x7FFF ^ ((q15_t) (x >> 31)))) : (q15_t) x;
+ }
+
+ /**
+ * @brief Multiplies 32 X 64 and returns 32 bit result in 2.30 format.
+ */
+
+ CMSIS_INLINE __STATIC_INLINE q63_t mult32x64(
+ q63_t x,
+ q31_t y)
+ {
+ return ((((q63_t) (x & 0x00000000FFFFFFFF) * y) >> 32) +
+ (((q63_t) (x >> 32) * y)));
+ }
+
+ /**
+ * @brief Function to Calculates 1/in (reciprocal) value of Q31 Data type.
+ */
+
+ CMSIS_INLINE __STATIC_INLINE uint32_t arm_recip_q31(
+ q31_t in,
+ q31_t * dst,
+ q31_t * pRecipTable)
+ {
+ q31_t out;
+ uint32_t tempVal;
+ uint32_t index, i;
+ uint32_t signBits;
+
+ if (in > 0)
+ {
+ signBits = ((uint32_t) (__CLZ( in) - 1));
+ }
+ else
+ {
+ signBits = ((uint32_t) (__CLZ(-in) - 1));
+ }
+
+ /* Convert input sample to 1.31 format */
+ in = (in << signBits);
+
+ /* calculation of index for initial approximated Val */
+ index = (uint32_t)(in >> 24);
+ index = (index & INDEX_MASK);
+
+ /* 1.31 with exp 1 */
+ out = pRecipTable[index];
+
+ /* calculation of reciprocal value */
+ /* running approximation for two iterations */
+ for (i = 0U; i < 2U; i++)
+ {
+ tempVal = (uint32_t) (((q63_t) in * out) >> 31);
+ tempVal = 0x7FFFFFFFu - tempVal;
+ /* 1.31 with exp 1 */
+ /* out = (q31_t) (((q63_t) out * tempVal) >> 30); */
+ out = clip_q63_to_q31(((q63_t) out * tempVal) >> 30);
+ }
+
+ /* write output */
+ *dst = out;
+
+ /* return num of signbits of out = 1/in value */
+ return (signBits + 1U);
+ }
+
+
+ /**
+ * @brief Function to Calculates 1/in (reciprocal) value of Q15 Data type.
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t arm_recip_q15(
+ q15_t in,
+ q15_t * dst,
+ q15_t * pRecipTable)
+ {
+ q15_t out = 0;
+ uint32_t tempVal = 0;
+ uint32_t index = 0, i = 0;
+ uint32_t signBits = 0;
+
+ if (in > 0)
+ {
+ signBits = ((uint32_t)(__CLZ( in) - 17));
+ }
+ else
+ {
+ signBits = ((uint32_t)(__CLZ(-in) - 17));
+ }
+
+ /* Convert input sample to 1.15 format */
+ in = (in << signBits);
+
+ /* calculation of index for initial approximated Val */
+ index = (uint32_t)(in >> 8);
+ index = (index & INDEX_MASK);
+
+ /* 1.15 with exp 1 */
+ out = pRecipTable[index];
+
+ /* calculation of reciprocal value */
+ /* running approximation for two iterations */
+ for (i = 0U; i < 2U; i++)
+ {
+ tempVal = (uint32_t) (((q31_t) in * out) >> 15);
+ tempVal = 0x7FFFu - tempVal;
+ /* 1.15 with exp 1 */
+ out = (q15_t) (((q31_t) out * tempVal) >> 14);
+ /* out = clip_q31_to_q15(((q31_t) out * tempVal) >> 14); */
+ }
+
+ /* write output */
+ *dst = out;
+
+ /* return num of signbits of out = 1/in value */
+ return (signBits + 1);
+ }
+
+
+/*
+ * @brief C custom defined intrinsic function for M3 and M0 processors
+ */
+#if !defined (ARM_MATH_DSP)
+
+ /*
+ * @brief C custom defined QADD8 for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __QADD8(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s, t, u;
+
+ r = __SSAT(((((q31_t)x << 24) >> 24) + (((q31_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF;
+ s = __SSAT(((((q31_t)x << 16) >> 24) + (((q31_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF;
+ t = __SSAT(((((q31_t)x << 8) >> 24) + (((q31_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF;
+ u = __SSAT(((((q31_t)x ) >> 24) + (((q31_t)y ) >> 24)), 8) & (int32_t)0x000000FF;
+
+ return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QSUB8 for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __QSUB8(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s, t, u;
+
+ r = __SSAT(((((q31_t)x << 24) >> 24) - (((q31_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF;
+ s = __SSAT(((((q31_t)x << 16) >> 24) - (((q31_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF;
+ t = __SSAT(((((q31_t)x << 8) >> 24) - (((q31_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF;
+ u = __SSAT(((((q31_t)x ) >> 24) - (((q31_t)y ) >> 24)), 8) & (int32_t)0x000000FF;
+
+ return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QADD16 for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __QADD16(
+ uint32_t x,
+ uint32_t y)
+ {
+/* q31_t r, s; without initialisation 'arm_offset_q15 test' fails but 'intrinsic' tests pass! for armCC */
+ q31_t r = 0, s = 0;
+
+ r = __SSAT(((((q31_t)x << 16) >> 16) + (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
+ s = __SSAT(((((q31_t)x ) >> 16) + (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SHADD16 for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SHADD16(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = (((((q31_t)x << 16) >> 16) + (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+ s = (((((q31_t)x ) >> 16) + (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QSUB16 for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __QSUB16(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = __SSAT(((((q31_t)x << 16) >> 16) - (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
+ s = __SSAT(((((q31_t)x ) >> 16) - (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SHSUB16 for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SHSUB16(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = (((((q31_t)x << 16) >> 16) - (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+ s = (((((q31_t)x ) >> 16) - (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QASX for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __QASX(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = __SSAT(((((q31_t)x << 16) >> 16) - (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
+ s = __SSAT(((((q31_t)x ) >> 16) + (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SHASX for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SHASX(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = (((((q31_t)x << 16) >> 16) - (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+ s = (((((q31_t)x ) >> 16) + (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QSAX for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __QSAX(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = __SSAT(((((q31_t)x << 16) >> 16) + (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
+ s = __SSAT(((((q31_t)x ) >> 16) - (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SHSAX for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SHSAX(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = (((((q31_t)x << 16) >> 16) + (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+ s = (((((q31_t)x ) >> 16) - (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SMUSDX for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SMUSDX(
+ uint32_t x,
+ uint32_t y)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) -
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) ));
+ }
+
+ /*
+ * @brief C custom defined SMUADX for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SMUADX(
+ uint32_t x,
+ uint32_t y)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) ));
+ }
+
+
+ /*
+ * @brief C custom defined QADD for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE int32_t __QADD(
+ int32_t x,
+ int32_t y)
+ {
+ return ((int32_t)(clip_q63_to_q31((q63_t)x + (q31_t)y)));
+ }
+
+
+ /*
+ * @brief C custom defined QSUB for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE int32_t __QSUB(
+ int32_t x,
+ int32_t y)
+ {
+ return ((int32_t)(clip_q63_to_q31((q63_t)x - (q31_t)y)));
+ }
+
+
+ /*
+ * @brief C custom defined SMLAD for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SMLAD(
+ uint32_t x,
+ uint32_t y,
+ uint32_t sum)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) +
+ ( ((q31_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMLADX for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SMLADX(
+ uint32_t x,
+ uint32_t y,
+ uint32_t sum)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ( ((q31_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMLSDX for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SMLSDX(
+ uint32_t x,
+ uint32_t y,
+ uint32_t sum)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) -
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ( ((q31_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMLALD for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint64_t __SMLALD(
+ uint32_t x,
+ uint32_t y,
+ uint64_t sum)
+ {
+/* return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); */
+ return ((uint64_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) +
+ ( ((q63_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMLALDX for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint64_t __SMLALDX(
+ uint32_t x,
+ uint32_t y,
+ uint64_t sum)
+ {
+/* return (sum + ((q15_t) (x >> 16) * (q15_t) y)) + ((q15_t) x * (q15_t) (y >> 16)); */
+ return ((uint64_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ( ((q63_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMUAD for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SMUAD(
+ uint32_t x,
+ uint32_t y)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMUSD for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SMUSD(
+ uint32_t x,
+ uint32_t y)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) -
+ ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) ));
+ }
+
+
+ /*
+ * @brief C custom defined SXTB16 for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE uint32_t __SXTB16(
+ uint32_t x)
+ {
+ return ((uint32_t)(((((q31_t)x << 24) >> 24) & (q31_t)0x0000FFFF) |
+ ((((q31_t)x << 8) >> 8) & (q31_t)0xFFFF0000) ));
+ }
+
+ /*
+ * @brief C custom defined SMMLA for M3 and M0 processors
+ */
+ CMSIS_INLINE __STATIC_INLINE int32_t __SMMLA(
+ int32_t x,
+ int32_t y,
+ int32_t sum)
+ {
+ return (sum + (int32_t) (((int64_t) x * y) >> 32));
+ }
+
+#endif /* !defined (ARM_MATH_DSP) */
+
+
+ /**
+ * @brief Instance structure for the Q7 FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of filter coefficients in the filter. */
+ q7_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ } arm_fir_instance_q7;
+
+ /**
+ * @brief Instance structure for the Q15 FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of filter coefficients in the filter. */
+ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ } arm_fir_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of filter coefficients in the filter. */
+ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ } arm_fir_instance_q31;
+
+ /**
+ * @brief Instance structure for the floating-point FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of filter coefficients in the filter. */
+ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ } arm_fir_instance_f32;
+
+
+ /**
+ * @brief Processing function for the Q7 FIR filter.
+ * @param[in] S points to an instance of the Q7 FIR filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_q7(
+ const arm_fir_instance_q7 * S,
+ q7_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q7 FIR filter.
+ * @param[in,out] S points to an instance of the Q7 FIR structure.
+ * @param[in] numTaps Number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of samples that are processed.
+ */
+ void arm_fir_init_q7(
+ arm_fir_instance_q7 * S,
+ uint16_t numTaps,
+ q7_t * pCoeffs,
+ q7_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q15 FIR filter.
+ * @param[in] S points to an instance of the Q15 FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_q15(
+ const arm_fir_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the fast Q15 FIR filter for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q15 FIR filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_fast_q15(
+ const arm_fir_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q15 FIR filter.
+ * @param[in,out] S points to an instance of the Q15 FIR filter structure.
+ * @param[in] numTaps Number of filter coefficients in the filter. Must be even and greater than or equal to 4.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of samples that are processed at a time.
+ * @return The function returns ARM_MATH_SUCCESS if initialization was successful or ARM_MATH_ARGUMENT_ERROR if
+ * numTaps is not a supported value.
+ */
+ arm_status arm_fir_init_q15(
+ arm_fir_instance_q15 * S,
+ uint16_t numTaps,
+ q15_t * pCoeffs,
+ q15_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 FIR filter.
+ * @param[in] S points to an instance of the Q31 FIR filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_q31(
+ const arm_fir_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the fast Q31 FIR filter for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q31 FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_fast_q31(
+ const arm_fir_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 FIR filter.
+ * @param[in,out] S points to an instance of the Q31 FIR structure.
+ * @param[in] numTaps Number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of samples that are processed at a time.
+ */
+ void arm_fir_init_q31(
+ arm_fir_instance_q31 * S,
+ uint16_t numTaps,
+ q31_t * pCoeffs,
+ q31_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the floating-point FIR filter.
+ * @param[in] S points to an instance of the floating-point FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_f32(
+ const arm_fir_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point FIR filter.
+ * @param[in,out] S points to an instance of the floating-point FIR filter structure.
+ * @param[in] numTaps Number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of samples that are processed at a time.
+ */
+ void arm_fir_init_f32(
+ arm_fir_instance_f32 * S,
+ uint16_t numTaps,
+ float32_t * pCoeffs,
+ float32_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q15 Biquad cascade filter.
+ */
+ typedef struct
+ {
+ int8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ q15_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
+ q15_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
+ int8_t postShift; /**< Additional shift, in bits, applied to each output sample. */
+ } arm_biquad_casd_df1_inst_q15;
+
+ /**
+ * @brief Instance structure for the Q31 Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ q31_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
+ q31_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
+ uint8_t postShift; /**< Additional shift, in bits, applied to each output sample. */
+ } arm_biquad_casd_df1_inst_q31;
+
+ /**
+ * @brief Instance structure for the floating-point Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float32_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
+ float32_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_casd_df1_inst_f32;
+
+
+ /**
+ * @brief Processing function for the Q15 Biquad cascade filter.
+ * @param[in] S points to an instance of the Q15 Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_q15(
+ const arm_biquad_casd_df1_inst_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q15 Biquad cascade filter.
+ * @param[in,out] S points to an instance of the Q15 Biquad cascade structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format
+ */
+ void arm_biquad_cascade_df1_init_q15(
+ arm_biquad_casd_df1_inst_q15 * S,
+ uint8_t numStages,
+ q15_t * pCoeffs,
+ q15_t * pState,
+ int8_t postShift);
+
+
+ /**
+ * @brief Fast but less precise processing function for the Q15 Biquad cascade filter for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q15 Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_fast_q15(
+ const arm_biquad_casd_df1_inst_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 Biquad cascade filter
+ * @param[in] S points to an instance of the Q31 Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_q31(
+ const arm_biquad_casd_df1_inst_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fast but less precise processing function for the Q31 Biquad cascade filter for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q31 Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_fast_q31(
+ const arm_biquad_casd_df1_inst_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 Biquad cascade filter.
+ * @param[in,out] S points to an instance of the Q31 Biquad cascade structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format
+ */
+ void arm_biquad_cascade_df1_init_q31(
+ arm_biquad_casd_df1_inst_q31 * S,
+ uint8_t numStages,
+ q31_t * pCoeffs,
+ q31_t * pState,
+ int8_t postShift);
+
+
+ /**
+ * @brief Processing function for the floating-point Biquad cascade filter.
+ * @param[in] S points to an instance of the floating-point Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_f32(
+ const arm_biquad_casd_df1_inst_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point Biquad cascade filter.
+ * @param[in,out] S points to an instance of the floating-point Biquad cascade structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ */
+ void arm_biquad_cascade_df1_init_f32(
+ arm_biquad_casd_df1_inst_f32 * S,
+ uint8_t numStages,
+ float32_t * pCoeffs,
+ float32_t * pState);
+
+
+ /**
+ * @brief Instance structure for the floating-point matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ float32_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_f32;
+
+
+ /**
+ * @brief Instance structure for the floating-point matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ float64_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_f64;
+
+ /**
+ * @brief Instance structure for the Q15 matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ q15_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ q31_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_q31;
+
+
+ /**
+ * @brief Floating-point matrix addition.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_add_f32(
+ const arm_matrix_instance_f32 * pSrcA,
+ const arm_matrix_instance_f32 * pSrcB,
+ arm_matrix_instance_f32 * pDst);
+
+
+ /**
+ * @brief Q15 matrix addition.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_add_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst);
+
+
+ /**
+ * @brief Q31 matrix addition.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_add_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+
+ /**
+ * @brief Floating-point, complex, matrix multiplication.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_cmplx_mult_f32(
+ const arm_matrix_instance_f32 * pSrcA,
+ const arm_matrix_instance_f32 * pSrcB,
+ arm_matrix_instance_f32 * pDst);
+
+
+ /**
+ * @brief Q15, complex, matrix multiplication.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_cmplx_mult_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst,
+ q15_t * pScratch);
+
+
+ /**
+ * @brief Q31, complex, matrix multiplication.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_cmplx_mult_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+
+ /**
+ * @brief Floating-point matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_trans_f32(
+ const arm_matrix_instance_f32 * pSrc,
+ arm_matrix_instance_f32 * pDst);
+
+
+ /**
+ * @brief Q15 matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_trans_q15(
+ const arm_matrix_instance_q15 * pSrc,
+ arm_matrix_instance_q15 * pDst);
+
+
+ /**
+ * @brief Q31 matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_trans_q31(
+ const arm_matrix_instance_q31 * pSrc,
+ arm_matrix_instance_q31 * pDst);
+
+
+ /**
+ * @brief Floating-point matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_mult_f32(
+ const arm_matrix_instance_f32 * pSrcA,
+ const arm_matrix_instance_f32 * pSrcB,
+ arm_matrix_instance_f32 * pDst);
+
+
+ /**
+ * @brief Q15 matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @param[in] pState points to the array for storing intermediate results
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_mult_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst,
+ q15_t * pState);
+
+
+ /**
+ * @brief Q15 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @param[in] pState points to the array for storing intermediate results
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_mult_fast_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst,
+ q15_t * pState);
+
+
+ /**
+ * @brief Q31 matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_mult_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+
+ /**
+ * @brief Q31 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_mult_fast_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+
+ /**
+ * @brief Floating-point matrix subtraction
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_sub_f32(
+ const arm_matrix_instance_f32 * pSrcA,
+ const arm_matrix_instance_f32 * pSrcB,
+ arm_matrix_instance_f32 * pDst);
+
+
+ /**
+ * @brief Q15 matrix subtraction
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_sub_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst);
+
+
+ /**
+ * @brief Q31 matrix subtraction
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_sub_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+
+ /**
+ * @brief Floating-point matrix scaling.
+ * @param[in] pSrc points to the input matrix
+ * @param[in] scale scale factor
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_scale_f32(
+ const arm_matrix_instance_f32 * pSrc,
+ float32_t scale,
+ arm_matrix_instance_f32 * pDst);
+
+
+ /**
+ * @brief Q15 matrix scaling.
+ * @param[in] pSrc points to input matrix
+ * @param[in] scaleFract fractional portion of the scale factor
+ * @param[in] shift number of bits to shift the result by
+ * @param[out] pDst points to output matrix
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_scale_q15(
+ const arm_matrix_instance_q15 * pSrc,
+ q15_t scaleFract,
+ int32_t shift,
+ arm_matrix_instance_q15 * pDst);
+
+
+ /**
+ * @brief Q31 matrix scaling.
+ * @param[in] pSrc points to input matrix
+ * @param[in] scaleFract fractional portion of the scale factor
+ * @param[in] shift number of bits to shift the result by
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+ arm_status arm_mat_scale_q31(
+ const arm_matrix_instance_q31 * pSrc,
+ q31_t scaleFract,
+ int32_t shift,
+ arm_matrix_instance_q31 * pDst);
+
+
+ /**
+ * @brief Q31 matrix initialization.
+ * @param[in,out] S points to an instance of the floating-point matrix structure.
+ * @param[in] nRows number of rows in the matrix.
+ * @param[in] nColumns number of columns in the matrix.
+ * @param[in] pData points to the matrix data array.
+ */
+ void arm_mat_init_q31(
+ arm_matrix_instance_q31 * S,
+ uint16_t nRows,
+ uint16_t nColumns,
+ q31_t * pData);
+
+
+ /**
+ * @brief Q15 matrix initialization.
+ * @param[in,out] S points to an instance of the floating-point matrix structure.
+ * @param[in] nRows number of rows in the matrix.
+ * @param[in] nColumns number of columns in the matrix.
+ * @param[in] pData points to the matrix data array.
+ */
+ void arm_mat_init_q15(
+ arm_matrix_instance_q15 * S,
+ uint16_t nRows,
+ uint16_t nColumns,
+ q15_t * pData);
+
+
+ /**
+ * @brief Floating-point matrix initialization.
+ * @param[in,out] S points to an instance of the floating-point matrix structure.
+ * @param[in] nRows number of rows in the matrix.
+ * @param[in] nColumns number of columns in the matrix.
+ * @param[in] pData points to the matrix data array.
+ */
+ void arm_mat_init_f32(
+ arm_matrix_instance_f32 * S,
+ uint16_t nRows,
+ uint16_t nColumns,
+ float32_t * pData);
+
+
+
+ /**
+ * @brief Instance structure for the Q15 PID Control.
+ */
+ typedef struct
+ {
+ q15_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */
+#if !defined (ARM_MATH_DSP)
+ q15_t A1;
+ q15_t A2;
+#else
+ q31_t A1; /**< The derived gain A1 = -Kp - 2Kd | Kd.*/
+#endif
+ q15_t state[3]; /**< The state array of length 3. */
+ q15_t Kp; /**< The proportional gain. */
+ q15_t Ki; /**< The integral gain. */
+ q15_t Kd; /**< The derivative gain. */
+ } arm_pid_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 PID Control.
+ */
+ typedef struct
+ {
+ q31_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */
+ q31_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */
+ q31_t A2; /**< The derived gain, A2 = Kd . */
+ q31_t state[3]; /**< The state array of length 3. */
+ q31_t Kp; /**< The proportional gain. */
+ q31_t Ki; /**< The integral gain. */
+ q31_t Kd; /**< The derivative gain. */
+ } arm_pid_instance_q31;
+
+ /**
+ * @brief Instance structure for the floating-point PID Control.
+ */
+ typedef struct
+ {
+ float32_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */
+ float32_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */
+ float32_t A2; /**< The derived gain, A2 = Kd . */
+ float32_t state[3]; /**< The state array of length 3. */
+ float32_t Kp; /**< The proportional gain. */
+ float32_t Ki; /**< The integral gain. */
+ float32_t Kd; /**< The derivative gain. */
+ } arm_pid_instance_f32;
+
+
+
+ /**
+ * @brief Initialization function for the floating-point PID Control.
+ * @param[in,out] S points to an instance of the PID structure.
+ * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state.
+ */
+ void arm_pid_init_f32(
+ arm_pid_instance_f32 * S,
+ int32_t resetStateFlag);
+
+
+ /**
+ * @brief Reset function for the floating-point PID Control.
+ * @param[in,out] S is an instance of the floating-point PID Control structure
+ */
+ void arm_pid_reset_f32(
+ arm_pid_instance_f32 * S);
+
+
+ /**
+ * @brief Initialization function for the Q31 PID Control.
+ * @param[in,out] S points to an instance of the Q15 PID structure.
+ * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state.
+ */
+ void arm_pid_init_q31(
+ arm_pid_instance_q31 * S,
+ int32_t resetStateFlag);
+
+
+ /**
+ * @brief Reset function for the Q31 PID Control.
+ * @param[in,out] S points to an instance of the Q31 PID Control structure
+ */
+
+ void arm_pid_reset_q31(
+ arm_pid_instance_q31 * S);
+
+
+ /**
+ * @brief Initialization function for the Q15 PID Control.
+ * @param[in,out] S points to an instance of the Q15 PID structure.
+ * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state.
+ */
+ void arm_pid_init_q15(
+ arm_pid_instance_q15 * S,
+ int32_t resetStateFlag);
+
+
+ /**
+ * @brief Reset function for the Q15 PID Control.
+ * @param[in,out] S points to an instance of the q15 PID Control structure
+ */
+ void arm_pid_reset_q15(
+ arm_pid_instance_q15 * S);
+
+
+ /**
+ * @brief Instance structure for the floating-point Linear Interpolate function.
+ */
+ typedef struct
+ {
+ uint32_t nValues; /**< nValues */
+ float32_t x1; /**< x1 */
+ float32_t xSpacing; /**< xSpacing */
+ float32_t *pYData; /**< pointer to the table of Y values */
+ } arm_linear_interp_instance_f32;
+
+ /**
+ * @brief Instance structure for the floating-point bilinear interpolation function.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows in the data table. */
+ uint16_t numCols; /**< number of columns in the data table. */
+ float32_t *pData; /**< points to the data table. */
+ } arm_bilinear_interp_instance_f32;
+
+ /**
+ * @brief Instance structure for the Q31 bilinear interpolation function.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows in the data table. */
+ uint16_t numCols; /**< number of columns in the data table. */
+ q31_t *pData; /**< points to the data table. */
+ } arm_bilinear_interp_instance_q31;
+
+ /**
+ * @brief Instance structure for the Q15 bilinear interpolation function.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows in the data table. */
+ uint16_t numCols; /**< number of columns in the data table. */
+ q15_t *pData; /**< points to the data table. */
+ } arm_bilinear_interp_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q15 bilinear interpolation function.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows in the data table. */
+ uint16_t numCols; /**< number of columns in the data table. */
+ q7_t *pData; /**< points to the data table. */
+ } arm_bilinear_interp_instance_q7;
+
+
+ /**
+ * @brief Q7 vector multiplication.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_mult_q7(
+ q7_t * pSrcA,
+ q7_t * pSrcB,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q15 vector multiplication.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_mult_q15(
+ q15_t * pSrcA,
+ q15_t * pSrcB,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q31 vector multiplication.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_mult_q31(
+ q31_t * pSrcA,
+ q31_t * pSrcB,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Floating-point vector multiplication.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_mult_f32(
+ float32_t * pSrcA,
+ float32_t * pSrcB,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q15 CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ q15_t *pTwiddle; /**< points to the Sin twiddle factor table. */
+ uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ } arm_cfft_radix2_instance_q15;
+
+/* Deprecated */
+ arm_status arm_cfft_radix2_init_q15(
+ arm_cfft_radix2_instance_q15 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix2_q15(
+ const arm_cfft_radix2_instance_q15 * S,
+ q15_t * pSrc);
+
+
+ /**
+ * @brief Instance structure for the Q15 CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ q15_t *pTwiddle; /**< points to the twiddle factor table. */
+ uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ } arm_cfft_radix4_instance_q15;
+
+/* Deprecated */
+ arm_status arm_cfft_radix4_init_q15(
+ arm_cfft_radix4_instance_q15 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix4_q15(
+ const arm_cfft_radix4_instance_q15 * S,
+ q15_t * pSrc);
+
+ /**
+ * @brief Instance structure for the Radix-2 Q31 CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ q31_t *pTwiddle; /**< points to the Twiddle factor table. */
+ uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ } arm_cfft_radix2_instance_q31;
+
+/* Deprecated */
+ arm_status arm_cfft_radix2_init_q31(
+ arm_cfft_radix2_instance_q31 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix2_q31(
+ const arm_cfft_radix2_instance_q31 * S,
+ q31_t * pSrc);
+
+ /**
+ * @brief Instance structure for the Q31 CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ q31_t *pTwiddle; /**< points to the twiddle factor table. */
+ uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ } arm_cfft_radix4_instance_q31;
+
+/* Deprecated */
+ void arm_cfft_radix4_q31(
+ const arm_cfft_radix4_instance_q31 * S,
+ q31_t * pSrc);
+
+/* Deprecated */
+ arm_status arm_cfft_radix4_init_q31(
+ arm_cfft_radix4_instance_q31 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+ /**
+ * @brief Instance structure for the floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ float32_t *pTwiddle; /**< points to the Twiddle factor table. */
+ uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ float32_t onebyfftLen; /**< value of 1/fftLen. */
+ } arm_cfft_radix2_instance_f32;
+
+/* Deprecated */
+ arm_status arm_cfft_radix2_init_f32(
+ arm_cfft_radix2_instance_f32 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix2_f32(
+ const arm_cfft_radix2_instance_f32 * S,
+ float32_t * pSrc);
+
+ /**
+ * @brief Instance structure for the floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ float32_t *pTwiddle; /**< points to the Twiddle factor table. */
+ uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ float32_t onebyfftLen; /**< value of 1/fftLen. */
+ } arm_cfft_radix4_instance_f32;
+
+/* Deprecated */
+ arm_status arm_cfft_radix4_init_f32(
+ arm_cfft_radix4_instance_f32 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix4_f32(
+ const arm_cfft_radix4_instance_f32 * S,
+ float32_t * pSrc);
+
+ /**
+ * @brief Instance structure for the fixed-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ const q15_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t bitRevLength; /**< bit reversal table length. */
+ } arm_cfft_instance_q15;
+
+void arm_cfft_q15(
+ const arm_cfft_instance_q15 * S,
+ q15_t * p1,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+ /**
+ * @brief Instance structure for the fixed-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ const q31_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t bitRevLength; /**< bit reversal table length. */
+ } arm_cfft_instance_q31;
+
+void arm_cfft_q31(
+ const arm_cfft_instance_q31 * S,
+ q31_t * p1,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+ /**
+ * @brief Instance structure for the floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ const float32_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t bitRevLength; /**< bit reversal table length. */
+ } arm_cfft_instance_f32;
+
+ void arm_cfft_f32(
+ const arm_cfft_instance_f32 * S,
+ float32_t * p1,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+ /**
+ * @brief Instance structure for the Q15 RFFT/RIFFT function.
+ */
+ typedef struct
+ {
+ uint32_t fftLenReal; /**< length of the real FFT. */
+ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */
+ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */
+ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ q15_t *pTwiddleAReal; /**< points to the real twiddle factor table. */
+ q15_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */
+ const arm_cfft_instance_q15 *pCfft; /**< points to the complex FFT instance. */
+ } arm_rfft_instance_q15;
+
+ arm_status arm_rfft_init_q15(
+ arm_rfft_instance_q15 * S,
+ uint32_t fftLenReal,
+ uint32_t ifftFlagR,
+ uint32_t bitReverseFlag);
+
+ void arm_rfft_q15(
+ const arm_rfft_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst);
+
+ /**
+ * @brief Instance structure for the Q31 RFFT/RIFFT function.
+ */
+ typedef struct
+ {
+ uint32_t fftLenReal; /**< length of the real FFT. */
+ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */
+ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */
+ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ q31_t *pTwiddleAReal; /**< points to the real twiddle factor table. */
+ q31_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */
+ const arm_cfft_instance_q31 *pCfft; /**< points to the complex FFT instance. */
+ } arm_rfft_instance_q31;
+
+ arm_status arm_rfft_init_q31(
+ arm_rfft_instance_q31 * S,
+ uint32_t fftLenReal,
+ uint32_t ifftFlagR,
+ uint32_t bitReverseFlag);
+
+ void arm_rfft_q31(
+ const arm_rfft_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst);
+
+ /**
+ * @brief Instance structure for the floating-point RFFT/RIFFT function.
+ */
+ typedef struct
+ {
+ uint32_t fftLenReal; /**< length of the real FFT. */
+ uint16_t fftLenBy2; /**< length of the complex FFT. */
+ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */
+ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */
+ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ float32_t *pTwiddleAReal; /**< points to the real twiddle factor table. */
+ float32_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */
+ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */
+ } arm_rfft_instance_f32;
+
+ arm_status arm_rfft_init_f32(
+ arm_rfft_instance_f32 * S,
+ arm_cfft_radix4_instance_f32 * S_CFFT,
+ uint32_t fftLenReal,
+ uint32_t ifftFlagR,
+ uint32_t bitReverseFlag);
+
+ void arm_rfft_f32(
+ const arm_rfft_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst);
+
+ /**
+ * @brief Instance structure for the floating-point RFFT/RIFFT function.
+ */
+typedef struct
+ {
+ arm_cfft_instance_f32 Sint; /**< Internal CFFT structure. */
+ uint16_t fftLenRFFT; /**< length of the real sequence */
+ float32_t * pTwiddleRFFT; /**< Twiddle factors real stage */
+ } arm_rfft_fast_instance_f32 ;
+
+arm_status arm_rfft_fast_init_f32 (
+ arm_rfft_fast_instance_f32 * S,
+ uint16_t fftLen);
+
+void arm_rfft_fast_f32(
+ arm_rfft_fast_instance_f32 * S,
+ float32_t * p, float32_t * pOut,
+ uint8_t ifftFlag);
+
+ /**
+ * @brief Instance structure for the floating-point DCT4/IDCT4 function.
+ */
+ typedef struct
+ {
+ uint16_t N; /**< length of the DCT4. */
+ uint16_t Nby2; /**< half of the length of the DCT4. */
+ float32_t normalize; /**< normalizing factor. */
+ float32_t *pTwiddle; /**< points to the twiddle factor table. */
+ float32_t *pCosFactor; /**< points to the cosFactor table. */
+ arm_rfft_instance_f32 *pRfft; /**< points to the real FFT instance. */
+ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */
+ } arm_dct4_instance_f32;
+
+
+ /**
+ * @brief Initialization function for the floating-point DCT4/IDCT4.
+ * @param[in,out] S points to an instance of floating-point DCT4/IDCT4 structure.
+ * @param[in] S_RFFT points to an instance of floating-point RFFT/RIFFT structure.
+ * @param[in] S_CFFT points to an instance of floating-point CFFT/CIFFT structure.
+ * @param[in] N length of the DCT4.
+ * @param[in] Nby2 half of the length of the DCT4.
+ * @param[in] normalize normalizing factor.
+ * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if fftLenReal is not a supported transform length.
+ */
+ arm_status arm_dct4_init_f32(
+ arm_dct4_instance_f32 * S,
+ arm_rfft_instance_f32 * S_RFFT,
+ arm_cfft_radix4_instance_f32 * S_CFFT,
+ uint16_t N,
+ uint16_t Nby2,
+ float32_t normalize);
+
+
+ /**
+ * @brief Processing function for the floating-point DCT4/IDCT4.
+ * @param[in] S points to an instance of the floating-point DCT4/IDCT4 structure.
+ * @param[in] pState points to state buffer.
+ * @param[in,out] pInlineBuffer points to the in-place input and output buffer.
+ */
+ void arm_dct4_f32(
+ const arm_dct4_instance_f32 * S,
+ float32_t * pState,
+ float32_t * pInlineBuffer);
+
+
+ /**
+ * @brief Instance structure for the Q31 DCT4/IDCT4 function.
+ */
+ typedef struct
+ {
+ uint16_t N; /**< length of the DCT4. */
+ uint16_t Nby2; /**< half of the length of the DCT4. */
+ q31_t normalize; /**< normalizing factor. */
+ q31_t *pTwiddle; /**< points to the twiddle factor table. */
+ q31_t *pCosFactor; /**< points to the cosFactor table. */
+ arm_rfft_instance_q31 *pRfft; /**< points to the real FFT instance. */
+ arm_cfft_radix4_instance_q31 *pCfft; /**< points to the complex FFT instance. */
+ } arm_dct4_instance_q31;
+
+
+ /**
+ * @brief Initialization function for the Q31 DCT4/IDCT4.
+ * @param[in,out] S points to an instance of Q31 DCT4/IDCT4 structure.
+ * @param[in] S_RFFT points to an instance of Q31 RFFT/RIFFT structure
+ * @param[in] S_CFFT points to an instance of Q31 CFFT/CIFFT structure
+ * @param[in] N length of the DCT4.
+ * @param[in] Nby2 half of the length of the DCT4.
+ * @param[in] normalize normalizing factor.
+ * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length.
+ */
+ arm_status arm_dct4_init_q31(
+ arm_dct4_instance_q31 * S,
+ arm_rfft_instance_q31 * S_RFFT,
+ arm_cfft_radix4_instance_q31 * S_CFFT,
+ uint16_t N,
+ uint16_t Nby2,
+ q31_t normalize);
+
+
+ /**
+ * @brief Processing function for the Q31 DCT4/IDCT4.
+ * @param[in] S points to an instance of the Q31 DCT4 structure.
+ * @param[in] pState points to state buffer.
+ * @param[in,out] pInlineBuffer points to the in-place input and output buffer.
+ */
+ void arm_dct4_q31(
+ const arm_dct4_instance_q31 * S,
+ q31_t * pState,
+ q31_t * pInlineBuffer);
+
+
+ /**
+ * @brief Instance structure for the Q15 DCT4/IDCT4 function.
+ */
+ typedef struct
+ {
+ uint16_t N; /**< length of the DCT4. */
+ uint16_t Nby2; /**< half of the length of the DCT4. */
+ q15_t normalize; /**< normalizing factor. */
+ q15_t *pTwiddle; /**< points to the twiddle factor table. */
+ q15_t *pCosFactor; /**< points to the cosFactor table. */
+ arm_rfft_instance_q15 *pRfft; /**< points to the real FFT instance. */
+ arm_cfft_radix4_instance_q15 *pCfft; /**< points to the complex FFT instance. */
+ } arm_dct4_instance_q15;
+
+
+ /**
+ * @brief Initialization function for the Q15 DCT4/IDCT4.
+ * @param[in,out] S points to an instance of Q15 DCT4/IDCT4 structure.
+ * @param[in] S_RFFT points to an instance of Q15 RFFT/RIFFT structure.
+ * @param[in] S_CFFT points to an instance of Q15 CFFT/CIFFT structure.
+ * @param[in] N length of the DCT4.
+ * @param[in] Nby2 half of the length of the DCT4.
+ * @param[in] normalize normalizing factor.
+ * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length.
+ */
+ arm_status arm_dct4_init_q15(
+ arm_dct4_instance_q15 * S,
+ arm_rfft_instance_q15 * S_RFFT,
+ arm_cfft_radix4_instance_q15 * S_CFFT,
+ uint16_t N,
+ uint16_t Nby2,
+ q15_t normalize);
+
+
+ /**
+ * @brief Processing function for the Q15 DCT4/IDCT4.
+ * @param[in] S points to an instance of the Q15 DCT4 structure.
+ * @param[in] pState points to state buffer.
+ * @param[in,out] pInlineBuffer points to the in-place input and output buffer.
+ */
+ void arm_dct4_q15(
+ const arm_dct4_instance_q15 * S,
+ q15_t * pState,
+ q15_t * pInlineBuffer);
+
+
+ /**
+ * @brief Floating-point vector addition.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_add_f32(
+ float32_t * pSrcA,
+ float32_t * pSrcB,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q7 vector addition.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_add_q7(
+ q7_t * pSrcA,
+ q7_t * pSrcB,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q15 vector addition.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_add_q15(
+ q15_t * pSrcA,
+ q15_t * pSrcB,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q31 vector addition.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_add_q31(
+ q31_t * pSrcA,
+ q31_t * pSrcB,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Floating-point vector subtraction.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_sub_f32(
+ float32_t * pSrcA,
+ float32_t * pSrcB,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q7 vector subtraction.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_sub_q7(
+ q7_t * pSrcA,
+ q7_t * pSrcB,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q15 vector subtraction.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_sub_q15(
+ q15_t * pSrcA,
+ q15_t * pSrcB,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q31 vector subtraction.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_sub_q31(
+ q31_t * pSrcA,
+ q31_t * pSrcB,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Multiplies a floating-point vector by a scalar.
+ * @param[in] pSrc points to the input vector
+ * @param[in] scale scale factor to be applied
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_scale_f32(
+ float32_t * pSrc,
+ float32_t scale,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Multiplies a Q7 vector by a scalar.
+ * @param[in] pSrc points to the input vector
+ * @param[in] scaleFract fractional portion of the scale value
+ * @param[in] shift number of bits to shift the result by
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_scale_q7(
+ q7_t * pSrc,
+ q7_t scaleFract,
+ int8_t shift,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Multiplies a Q15 vector by a scalar.
+ * @param[in] pSrc points to the input vector
+ * @param[in] scaleFract fractional portion of the scale value
+ * @param[in] shift number of bits to shift the result by
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_scale_q15(
+ q15_t * pSrc,
+ q15_t scaleFract,
+ int8_t shift,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Multiplies a Q31 vector by a scalar.
+ * @param[in] pSrc points to the input vector
+ * @param[in] scaleFract fractional portion of the scale value
+ * @param[in] shift number of bits to shift the result by
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_scale_q31(
+ q31_t * pSrc,
+ q31_t scaleFract,
+ int8_t shift,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q7 vector absolute value.
+ * @param[in] pSrc points to the input buffer
+ * @param[out] pDst points to the output buffer
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_abs_q7(
+ q7_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Floating-point vector absolute value.
+ * @param[in] pSrc points to the input buffer
+ * @param[out] pDst points to the output buffer
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_abs_f32(
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q15 vector absolute value.
+ * @param[in] pSrc points to the input buffer
+ * @param[out] pDst points to the output buffer
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_abs_q15(
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Q31 vector absolute value.
+ * @param[in] pSrc points to the input buffer
+ * @param[out] pDst points to the output buffer
+ * @param[in] blockSize number of samples in each vector
+ */
+ void arm_abs_q31(
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Dot product of floating-point vectors.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[in] blockSize number of samples in each vector
+ * @param[out] result output result returned here
+ */
+ void arm_dot_prod_f32(
+ float32_t * pSrcA,
+ float32_t * pSrcB,
+ uint32_t blockSize,
+ float32_t * result);
+
+
+ /**
+ * @brief Dot product of Q7 vectors.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[in] blockSize number of samples in each vector
+ * @param[out] result output result returned here
+ */
+ void arm_dot_prod_q7(
+ q7_t * pSrcA,
+ q7_t * pSrcB,
+ uint32_t blockSize,
+ q31_t * result);
+
+
+ /**
+ * @brief Dot product of Q15 vectors.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[in] blockSize number of samples in each vector
+ * @param[out] result output result returned here
+ */
+ void arm_dot_prod_q15(
+ q15_t * pSrcA,
+ q15_t * pSrcB,
+ uint32_t blockSize,
+ q63_t * result);
+
+
+ /**
+ * @brief Dot product of Q31 vectors.
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[in] blockSize number of samples in each vector
+ * @param[out] result output result returned here
+ */
+ void arm_dot_prod_q31(
+ q31_t * pSrcA,
+ q31_t * pSrcB,
+ uint32_t blockSize,
+ q63_t * result);
+
+
+ /**
+ * @brief Shifts the elements of a Q7 vector a specified number of bits.
+ * @param[in] pSrc points to the input vector
+ * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right.
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_shift_q7(
+ q7_t * pSrc,
+ int8_t shiftBits,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Shifts the elements of a Q15 vector a specified number of bits.
+ * @param[in] pSrc points to the input vector
+ * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right.
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_shift_q15(
+ q15_t * pSrc,
+ int8_t shiftBits,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Shifts the elements of a Q31 vector a specified number of bits.
+ * @param[in] pSrc points to the input vector
+ * @param[in] shiftBits number of bits to shift. A positive value shifts left; a negative value shifts right.
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_shift_q31(
+ q31_t * pSrc,
+ int8_t shiftBits,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Adds a constant offset to a floating-point vector.
+ * @param[in] pSrc points to the input vector
+ * @param[in] offset is the offset to be added
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_offset_f32(
+ float32_t * pSrc,
+ float32_t offset,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Adds a constant offset to a Q7 vector.
+ * @param[in] pSrc points to the input vector
+ * @param[in] offset is the offset to be added
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_offset_q7(
+ q7_t * pSrc,
+ q7_t offset,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Adds a constant offset to a Q15 vector.
+ * @param[in] pSrc points to the input vector
+ * @param[in] offset is the offset to be added
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_offset_q15(
+ q15_t * pSrc,
+ q15_t offset,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Adds a constant offset to a Q31 vector.
+ * @param[in] pSrc points to the input vector
+ * @param[in] offset is the offset to be added
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_offset_q31(
+ q31_t * pSrc,
+ q31_t offset,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Negates the elements of a floating-point vector.
+ * @param[in] pSrc points to the input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_negate_f32(
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Negates the elements of a Q7 vector.
+ * @param[in] pSrc points to the input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_negate_q7(
+ q7_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Negates the elements of a Q15 vector.
+ * @param[in] pSrc points to the input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_negate_q15(
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Negates the elements of a Q31 vector.
+ * @param[in] pSrc points to the input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] blockSize number of samples in the vector
+ */
+ void arm_negate_q31(
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Copies the elements of a floating-point vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_copy_f32(
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Copies the elements of a Q7 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_copy_q7(
+ q7_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Copies the elements of a Q15 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_copy_q15(
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Copies the elements of a Q31 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_copy_q31(
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fills a constant value into a floating-point vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_fill_f32(
+ float32_t value,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fills a constant value into a Q7 vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_fill_q7(
+ q7_t value,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fills a constant value into a Q15 vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_fill_q15(
+ q15_t value,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fills a constant value into a Q31 vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_fill_q31(
+ q31_t value,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+/**
+ * @brief Convolution of floating-point sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the location where the output result is written. Length srcALen+srcBLen-1.
+ */
+ void arm_conv_f32(
+ float32_t * pSrcA,
+ uint32_t srcALen,
+ float32_t * pSrcB,
+ uint32_t srcBLen,
+ float32_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q15 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ * @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
+ */
+ void arm_conv_opt_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+/**
+ * @brief Convolution of Q15 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the location where the output result is written. Length srcALen+srcBLen-1.
+ */
+ void arm_conv_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ */
+ void arm_conv_fast_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ * @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
+ */
+ void arm_conv_fast_opt_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Convolution of Q31 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ */
+ void arm_conv_q31(
+ q31_t * pSrcA,
+ uint32_t srcALen,
+ q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ */
+ void arm_conv_fast_q31(
+ q31_t * pSrcA,
+ uint32_t srcALen,
+ q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ * @param[in] pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
+ */
+ void arm_conv_opt_q7(
+ q7_t * pSrcA,
+ uint32_t srcALen,
+ q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Convolution of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ */
+ void arm_conv_q7(
+ q7_t * pSrcA,
+ uint32_t srcALen,
+ q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst);
+
+
+ /**
+ * @brief Partial convolution of floating-point sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_f32(
+ float32_t * pSrcA,
+ uint32_t srcALen,
+ float32_t * pSrcB,
+ uint32_t srcBLen,
+ float32_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q15 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_opt_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Partial convolution of Q15 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_fast_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_fast_opt_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Partial convolution of Q31 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_q31(
+ q31_t * pSrcA,
+ uint32_t srcALen,
+ q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_fast_q31(
+ q31_t * pSrcA,
+ uint32_t srcALen,
+ q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q7 sequences
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @param[in] pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_opt_q7(
+ q7_t * pSrcA,
+ uint32_t srcALen,
+ q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+/**
+ * @brief Partial convolution of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_q7(
+ q7_t * pSrcA,
+ uint32_t srcALen,
+ q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Instance structure for the Q15 FIR decimator.
+ */
+ typedef struct
+ {
+ uint8_t M; /**< decimation factor. */
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ } arm_fir_decimate_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 FIR decimator.
+ */
+ typedef struct
+ {
+ uint8_t M; /**< decimation factor. */
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ } arm_fir_decimate_instance_q31;
+
+ /**
+ * @brief Instance structure for the floating-point FIR decimator.
+ */
+ typedef struct
+ {
+ uint8_t M; /**< decimation factor. */
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ } arm_fir_decimate_instance_f32;
+
+
+ /**
+ * @brief Processing function for the floating-point FIR decimator.
+ * @param[in] S points to an instance of the floating-point FIR decimator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_decimate_f32(
+ const arm_fir_decimate_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point FIR decimator.
+ * @param[in,out] S points to an instance of the floating-point FIR decimator structure.
+ * @param[in] numTaps number of coefficients in the filter.
+ * @param[in] M decimation factor.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * blockSize is not a multiple of M.
+ */
+ arm_status arm_fir_decimate_init_f32(
+ arm_fir_decimate_instance_f32 * S,
+ uint16_t numTaps,
+ uint8_t M,
+ float32_t * pCoeffs,
+ float32_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q15 FIR decimator.
+ * @param[in] S points to an instance of the Q15 FIR decimator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_decimate_q15(
+ const arm_fir_decimate_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q15 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q15 FIR decimator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_decimate_fast_q15(
+ const arm_fir_decimate_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q15 FIR decimator.
+ * @param[in,out] S points to an instance of the Q15 FIR decimator structure.
+ * @param[in] numTaps number of coefficients in the filter.
+ * @param[in] M decimation factor.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * blockSize is not a multiple of M.
+ */
+ arm_status arm_fir_decimate_init_q15(
+ arm_fir_decimate_instance_q15 * S,
+ uint16_t numTaps,
+ uint8_t M,
+ q15_t * pCoeffs,
+ q15_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 FIR decimator.
+ * @param[in] S points to an instance of the Q31 FIR decimator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_decimate_q31(
+ const arm_fir_decimate_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Processing function for the Q31 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q31 FIR decimator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_decimate_fast_q31(
+ arm_fir_decimate_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 FIR decimator.
+ * @param[in,out] S points to an instance of the Q31 FIR decimator structure.
+ * @param[in] numTaps number of coefficients in the filter.
+ * @param[in] M decimation factor.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * blockSize is not a multiple of M.
+ */
+ arm_status arm_fir_decimate_init_q31(
+ arm_fir_decimate_instance_q31 * S,
+ uint16_t numTaps,
+ uint8_t M,
+ q31_t * pCoeffs,
+ q31_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q15 FIR interpolator.
+ */
+ typedef struct
+ {
+ uint8_t L; /**< upsample factor. */
+ uint16_t phaseLength; /**< length of each polyphase filter component. */
+ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */
+ q15_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */
+ } arm_fir_interpolate_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 FIR interpolator.
+ */
+ typedef struct
+ {
+ uint8_t L; /**< upsample factor. */
+ uint16_t phaseLength; /**< length of each polyphase filter component. */
+ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */
+ q31_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */
+ } arm_fir_interpolate_instance_q31;
+
+ /**
+ * @brief Instance structure for the floating-point FIR interpolator.
+ */
+ typedef struct
+ {
+ uint8_t L; /**< upsample factor. */
+ uint16_t phaseLength; /**< length of each polyphase filter component. */
+ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */
+ float32_t *pState; /**< points to the state variable array. The array is of length phaseLength+numTaps-1. */
+ } arm_fir_interpolate_instance_f32;
+
+
+ /**
+ * @brief Processing function for the Q15 FIR interpolator.
+ * @param[in] S points to an instance of the Q15 FIR interpolator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_interpolate_q15(
+ const arm_fir_interpolate_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q15 FIR interpolator.
+ * @param[in,out] S points to an instance of the Q15 FIR interpolator structure.
+ * @param[in] L upsample factor.
+ * @param[in] numTaps number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficient buffer.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * the filter length numTaps is not a multiple of the interpolation factor L.
+ */
+ arm_status arm_fir_interpolate_init_q15(
+ arm_fir_interpolate_instance_q15 * S,
+ uint8_t L,
+ uint16_t numTaps,
+ q15_t * pCoeffs,
+ q15_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 FIR interpolator.
+ * @param[in] S points to an instance of the Q15 FIR interpolator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_interpolate_q31(
+ const arm_fir_interpolate_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 FIR interpolator.
+ * @param[in,out] S points to an instance of the Q31 FIR interpolator structure.
+ * @param[in] L upsample factor.
+ * @param[in] numTaps number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficient buffer.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * the filter length numTaps is not a multiple of the interpolation factor L.
+ */
+ arm_status arm_fir_interpolate_init_q31(
+ arm_fir_interpolate_instance_q31 * S,
+ uint8_t L,
+ uint16_t numTaps,
+ q31_t * pCoeffs,
+ q31_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the floating-point FIR interpolator.
+ * @param[in] S points to an instance of the floating-point FIR interpolator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_interpolate_f32(
+ const arm_fir_interpolate_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point FIR interpolator.
+ * @param[in,out] S points to an instance of the floating-point FIR interpolator structure.
+ * @param[in] L upsample factor.
+ * @param[in] numTaps number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficient buffer.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * the filter length numTaps is not a multiple of the interpolation factor L.
+ */
+ arm_status arm_fir_interpolate_init_f32(
+ arm_fir_interpolate_instance_f32 * S,
+ uint8_t L,
+ uint16_t numTaps,
+ float32_t * pCoeffs,
+ float32_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the high precision Q31 Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ q63_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */
+ q31_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ uint8_t postShift; /**< additional shift, in bits, applied to each output sample. */
+ } arm_biquad_cas_df1_32x64_ins_q31;
+
+
+ /**
+ * @param[in] S points to an instance of the high precision Q31 Biquad cascade filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cas_df1_32x64_q31(
+ const arm_biquad_cas_df1_32x64_ins_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @param[in,out] S points to an instance of the high precision Q31 Biquad cascade filter structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] postShift shift to be applied to the output. Varies according to the coefficients format
+ */
+ void arm_biquad_cas_df1_32x64_init_q31(
+ arm_biquad_cas_df1_32x64_ins_q31 * S,
+ uint8_t numStages,
+ q31_t * pCoeffs,
+ q63_t * pState,
+ uint8_t postShift);
+
+
+ /**
+ * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float32_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */
+ float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_cascade_df2T_instance_f32;
+
+ /**
+ * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float32_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */
+ float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_cascade_stereo_df2T_instance_f32;
+
+ /**
+ * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float64_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */
+ float64_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_cascade_df2T_instance_f64;
+
+
+ /**
+ * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in] S points to an instance of the filter data structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df2T_f32(
+ const arm_biquad_cascade_df2T_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. 2 channels
+ * @param[in] S points to an instance of the filter data structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_stereo_df2T_f32(
+ const arm_biquad_cascade_stereo_df2T_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in] S points to an instance of the filter data structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df2T_f64(
+ const arm_biquad_cascade_df2T_instance_f64 * S,
+ float64_t * pSrc,
+ float64_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in,out] S points to an instance of the filter data structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ */
+ void arm_biquad_cascade_df2T_init_f32(
+ arm_biquad_cascade_df2T_instance_f32 * S,
+ uint8_t numStages,
+ float32_t * pCoeffs,
+ float32_t * pState);
+
+
+ /**
+ * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in,out] S points to an instance of the filter data structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ */
+ void arm_biquad_cascade_stereo_df2T_init_f32(
+ arm_biquad_cascade_stereo_df2T_instance_f32 * S,
+ uint8_t numStages,
+ float32_t * pCoeffs,
+ float32_t * pState);
+
+
+ /**
+ * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in,out] S points to an instance of the filter data structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ */
+ void arm_biquad_cascade_df2T_init_f64(
+ arm_biquad_cascade_df2T_instance_f64 * S,
+ uint8_t numStages,
+ float64_t * pCoeffs,
+ float64_t * pState);
+
+
+ /**
+ * @brief Instance structure for the Q15 FIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of filter stages. */
+ q15_t *pState; /**< points to the state variable array. The array is of length numStages. */
+ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */
+ } arm_fir_lattice_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 FIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of filter stages. */
+ q31_t *pState; /**< points to the state variable array. The array is of length numStages. */
+ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */
+ } arm_fir_lattice_instance_q31;
+
+ /**
+ * @brief Instance structure for the floating-point FIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of filter stages. */
+ float32_t *pState; /**< points to the state variable array. The array is of length numStages. */
+ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */
+ } arm_fir_lattice_instance_f32;
+
+
+ /**
+ * @brief Initialization function for the Q15 FIR lattice filter.
+ * @param[in] S points to an instance of the Q15 FIR lattice structure.
+ * @param[in] numStages number of filter stages.
+ * @param[in] pCoeffs points to the coefficient buffer. The array is of length numStages.
+ * @param[in] pState points to the state buffer. The array is of length numStages.
+ */
+ void arm_fir_lattice_init_q15(
+ arm_fir_lattice_instance_q15 * S,
+ uint16_t numStages,
+ q15_t * pCoeffs,
+ q15_t * pState);
+
+
+ /**
+ * @brief Processing function for the Q15 FIR lattice filter.
+ * @param[in] S points to an instance of the Q15 FIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_lattice_q15(
+ const arm_fir_lattice_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 FIR lattice filter.
+ * @param[in] S points to an instance of the Q31 FIR lattice structure.
+ * @param[in] numStages number of filter stages.
+ * @param[in] pCoeffs points to the coefficient buffer. The array is of length numStages.
+ * @param[in] pState points to the state buffer. The array is of length numStages.
+ */
+ void arm_fir_lattice_init_q31(
+ arm_fir_lattice_instance_q31 * S,
+ uint16_t numStages,
+ q31_t * pCoeffs,
+ q31_t * pState);
+
+
+ /**
+ * @brief Processing function for the Q31 FIR lattice filter.
+ * @param[in] S points to an instance of the Q31 FIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_lattice_q31(
+ const arm_fir_lattice_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+/**
+ * @brief Initialization function for the floating-point FIR lattice filter.
+ * @param[in] S points to an instance of the floating-point FIR lattice structure.
+ * @param[in] numStages number of filter stages.
+ * @param[in] pCoeffs points to the coefficient buffer. The array is of length numStages.
+ * @param[in] pState points to the state buffer. The array is of length numStages.
+ */
+ void arm_fir_lattice_init_f32(
+ arm_fir_lattice_instance_f32 * S,
+ uint16_t numStages,
+ float32_t * pCoeffs,
+ float32_t * pState);
+
+
+ /**
+ * @brief Processing function for the floating-point FIR lattice filter.
+ * @param[in] S points to an instance of the floating-point FIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_lattice_f32(
+ const arm_fir_lattice_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q15 IIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of stages in the filter. */
+ q15_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */
+ q15_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */
+ q15_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */
+ } arm_iir_lattice_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 IIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of stages in the filter. */
+ q31_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */
+ q31_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */
+ q31_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */
+ } arm_iir_lattice_instance_q31;
+
+ /**
+ * @brief Instance structure for the floating-point IIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of stages in the filter. */
+ float32_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */
+ float32_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */
+ float32_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */
+ } arm_iir_lattice_instance_f32;
+
+
+ /**
+ * @brief Processing function for the floating-point IIR lattice filter.
+ * @param[in] S points to an instance of the floating-point IIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_f32(
+ const arm_iir_lattice_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point IIR lattice filter.
+ * @param[in] S points to an instance of the floating-point IIR lattice structure.
+ * @param[in] numStages number of stages in the filter.
+ * @param[in] pkCoeffs points to the reflection coefficient buffer. The array is of length numStages.
+ * @param[in] pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1.
+ * @param[in] pState points to the state buffer. The array is of length numStages+blockSize-1.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_init_f32(
+ arm_iir_lattice_instance_f32 * S,
+ uint16_t numStages,
+ float32_t * pkCoeffs,
+ float32_t * pvCoeffs,
+ float32_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 IIR lattice filter.
+ * @param[in] S points to an instance of the Q31 IIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_q31(
+ const arm_iir_lattice_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 IIR lattice filter.
+ * @param[in] S points to an instance of the Q31 IIR lattice structure.
+ * @param[in] numStages number of stages in the filter.
+ * @param[in] pkCoeffs points to the reflection coefficient buffer. The array is of length numStages.
+ * @param[in] pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1.
+ * @param[in] pState points to the state buffer. The array is of length numStages+blockSize.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_init_q31(
+ arm_iir_lattice_instance_q31 * S,
+ uint16_t numStages,
+ q31_t * pkCoeffs,
+ q31_t * pvCoeffs,
+ q31_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q15 IIR lattice filter.
+ * @param[in] S points to an instance of the Q15 IIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_q15(
+ const arm_iir_lattice_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+/**
+ * @brief Initialization function for the Q15 IIR lattice filter.
+ * @param[in] S points to an instance of the fixed-point Q15 IIR lattice structure.
+ * @param[in] numStages number of stages in the filter.
+ * @param[in] pkCoeffs points to reflection coefficient buffer. The array is of length numStages.
+ * @param[in] pvCoeffs points to ladder coefficient buffer. The array is of length numStages+1.
+ * @param[in] pState points to state buffer. The array is of length numStages+blockSize.
+ * @param[in] blockSize number of samples to process per call.
+ */
+ void arm_iir_lattice_init_q15(
+ arm_iir_lattice_instance_q15 * S,
+ uint16_t numStages,
+ q15_t * pkCoeffs,
+ q15_t * pvCoeffs,
+ q15_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the floating-point LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ float32_t mu; /**< step size that controls filter coefficient updates. */
+ } arm_lms_instance_f32;
+
+
+ /**
+ * @brief Processing function for floating-point LMS filter.
+ * @param[in] S points to an instance of the floating-point LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_f32(
+ const arm_lms_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pRef,
+ float32_t * pOut,
+ float32_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for floating-point LMS filter.
+ * @param[in] S points to an instance of the floating-point LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to the coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_init_f32(
+ arm_lms_instance_f32 * S,
+ uint16_t numTaps,
+ float32_t * pCoeffs,
+ float32_t * pState,
+ float32_t mu,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q15 LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ q15_t mu; /**< step size that controls filter coefficient updates. */
+ uint32_t postShift; /**< bit shift applied to coefficients. */
+ } arm_lms_instance_q15;
+
+
+ /**
+ * @brief Initialization function for the Q15 LMS filter.
+ * @param[in] S points to an instance of the Q15 LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to the coefficient buffer.
+ * @param[in] pState points to the state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ * @param[in] postShift bit shift applied to coefficients.
+ */
+ void arm_lms_init_q15(
+ arm_lms_instance_q15 * S,
+ uint16_t numTaps,
+ q15_t * pCoeffs,
+ q15_t * pState,
+ q15_t mu,
+ uint32_t blockSize,
+ uint32_t postShift);
+
+
+ /**
+ * @brief Processing function for Q15 LMS filter.
+ * @param[in] S points to an instance of the Q15 LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_q15(
+ const arm_lms_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pRef,
+ q15_t * pOut,
+ q15_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q31 LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ q31_t mu; /**< step size that controls filter coefficient updates. */
+ uint32_t postShift; /**< bit shift applied to coefficients. */
+ } arm_lms_instance_q31;
+
+
+ /**
+ * @brief Processing function for Q31 LMS filter.
+ * @param[in] S points to an instance of the Q15 LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_q31(
+ const arm_lms_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pRef,
+ q31_t * pOut,
+ q31_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for Q31 LMS filter.
+ * @param[in] S points to an instance of the Q31 LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ * @param[in] postShift bit shift applied to coefficients.
+ */
+ void arm_lms_init_q31(
+ arm_lms_instance_q31 * S,
+ uint16_t numTaps,
+ q31_t * pCoeffs,
+ q31_t * pState,
+ q31_t mu,
+ uint32_t blockSize,
+ uint32_t postShift);
+
+
+ /**
+ * @brief Instance structure for the floating-point normalized LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ float32_t mu; /**< step size that control filter coefficient updates. */
+ float32_t energy; /**< saves previous frame energy. */
+ float32_t x0; /**< saves previous input sample. */
+ } arm_lms_norm_instance_f32;
+
+
+ /**
+ * @brief Processing function for floating-point normalized LMS filter.
+ * @param[in] S points to an instance of the floating-point normalized LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_norm_f32(
+ arm_lms_norm_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pRef,
+ float32_t * pOut,
+ float32_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for floating-point normalized LMS filter.
+ * @param[in] S points to an instance of the floating-point LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_norm_init_f32(
+ arm_lms_norm_instance_f32 * S,
+ uint16_t numTaps,
+ float32_t * pCoeffs,
+ float32_t * pState,
+ float32_t mu,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q31 normalized LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ q31_t mu; /**< step size that controls filter coefficient updates. */
+ uint8_t postShift; /**< bit shift applied to coefficients. */
+ q31_t *recipTable; /**< points to the reciprocal initial value table. */
+ q31_t energy; /**< saves previous frame energy. */
+ q31_t x0; /**< saves previous input sample. */
+ } arm_lms_norm_instance_q31;
+
+
+ /**
+ * @brief Processing function for Q31 normalized LMS filter.
+ * @param[in] S points to an instance of the Q31 normalized LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_norm_q31(
+ arm_lms_norm_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pRef,
+ q31_t * pOut,
+ q31_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for Q31 normalized LMS filter.
+ * @param[in] S points to an instance of the Q31 normalized LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ * @param[in] postShift bit shift applied to coefficients.
+ */
+ void arm_lms_norm_init_q31(
+ arm_lms_norm_instance_q31 * S,
+ uint16_t numTaps,
+ q31_t * pCoeffs,
+ q31_t * pState,
+ q31_t mu,
+ uint32_t blockSize,
+ uint8_t postShift);
+
+
+ /**
+ * @brief Instance structure for the Q15 normalized LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< Number of coefficients in the filter. */
+ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ q15_t mu; /**< step size that controls filter coefficient updates. */
+ uint8_t postShift; /**< bit shift applied to coefficients. */
+ q15_t *recipTable; /**< Points to the reciprocal initial value table. */
+ q15_t energy; /**< saves previous frame energy. */
+ q15_t x0; /**< saves previous input sample. */
+ } arm_lms_norm_instance_q15;
+
+
+ /**
+ * @brief Processing function for Q15 normalized LMS filter.
+ * @param[in] S points to an instance of the Q15 normalized LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_norm_q15(
+ arm_lms_norm_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pRef,
+ q15_t * pOut,
+ q15_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for Q15 normalized LMS filter.
+ * @param[in] S points to an instance of the Q15 normalized LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ * @param[in] postShift bit shift applied to coefficients.
+ */
+ void arm_lms_norm_init_q15(
+ arm_lms_norm_instance_q15 * S,
+ uint16_t numTaps,
+ q15_t * pCoeffs,
+ q15_t * pState,
+ q15_t mu,
+ uint32_t blockSize,
+ uint8_t postShift);
+
+
+ /**
+ * @brief Correlation of floating-point sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_f32(
+ float32_t * pSrcA,
+ uint32_t srcALen,
+ float32_t * pSrcB,
+ uint32_t srcBLen,
+ float32_t * pDst);
+
+
+ /**
+ * @brief Correlation of Q15 sequences
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ * @param[in] pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ */
+ void arm_correlate_opt_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ q15_t * pScratch);
+
+
+ /**
+ * @brief Correlation of Q15 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+
+ void arm_correlate_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst);
+
+
+ /**
+ * @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+
+ void arm_correlate_fast_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst);
+
+
+ /**
+ * @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ * @param[in] pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ */
+ void arm_correlate_fast_opt_q15(
+ q15_t * pSrcA,
+ uint32_t srcALen,
+ q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ q15_t * pScratch);
+
+
+ /**
+ * @brief Correlation of Q31 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_q31(
+ q31_t * pSrcA,
+ uint32_t srcALen,
+ q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst);
+
+
+ /**
+ * @brief Correlation of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_fast_q31(
+ q31_t * pSrcA,
+ uint32_t srcALen,
+ q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst);
+
+
+ /**
+ * @brief Correlation of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ * @param[in] pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
+ */
+ void arm_correlate_opt_q7(
+ q7_t * pSrcA,
+ uint32_t srcALen,
+ q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Correlation of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_q7(
+ q7_t * pSrcA,
+ uint32_t srcALen,
+ q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst);
+
+
+ /**
+ * @brief Instance structure for the floating-point sparse FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
+ float32_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
+ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
+ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
+ } arm_fir_sparse_instance_f32;
+
+ /**
+ * @brief Instance structure for the Q31 sparse FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
+ q31_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
+ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
+ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
+ } arm_fir_sparse_instance_q31;
+
+ /**
+ * @brief Instance structure for the Q15 sparse FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
+ q15_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
+ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
+ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
+ } arm_fir_sparse_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q7 sparse FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
+ q7_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
+ q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
+ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
+ } arm_fir_sparse_instance_q7;
+
+
+ /**
+ * @brief Processing function for the floating-point sparse FIR filter.
+ * @param[in] S points to an instance of the floating-point sparse FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] pScratchIn points to a temporary buffer of size blockSize.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_sparse_f32(
+ arm_fir_sparse_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ float32_t * pScratchIn,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point sparse FIR filter.
+ * @param[in,out] S points to an instance of the floating-point sparse FIR structure.
+ * @param[in] numTaps number of nonzero coefficients in the filter.
+ * @param[in] pCoeffs points to the array of filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] pTapDelay points to the array of offset times.
+ * @param[in] maxDelay maximum offset time supported.
+ * @param[in] blockSize number of samples that will be processed per block.
+ */
+ void arm_fir_sparse_init_f32(
+ arm_fir_sparse_instance_f32 * S,
+ uint16_t numTaps,
+ float32_t * pCoeffs,
+ float32_t * pState,
+ int32_t * pTapDelay,
+ uint16_t maxDelay,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 sparse FIR filter.
+ * @param[in] S points to an instance of the Q31 sparse FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] pScratchIn points to a temporary buffer of size blockSize.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_sparse_q31(
+ arm_fir_sparse_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst,
+ q31_t * pScratchIn,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 sparse FIR filter.
+ * @param[in,out] S points to an instance of the Q31 sparse FIR structure.
+ * @param[in] numTaps number of nonzero coefficients in the filter.
+ * @param[in] pCoeffs points to the array of filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] pTapDelay points to the array of offset times.
+ * @param[in] maxDelay maximum offset time supported.
+ * @param[in] blockSize number of samples that will be processed per block.
+ */
+ void arm_fir_sparse_init_q31(
+ arm_fir_sparse_instance_q31 * S,
+ uint16_t numTaps,
+ q31_t * pCoeffs,
+ q31_t * pState,
+ int32_t * pTapDelay,
+ uint16_t maxDelay,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q15 sparse FIR filter.
+ * @param[in] S points to an instance of the Q15 sparse FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] pScratchIn points to a temporary buffer of size blockSize.
+ * @param[in] pScratchOut points to a temporary buffer of size blockSize.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_sparse_q15(
+ arm_fir_sparse_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst,
+ q15_t * pScratchIn,
+ q31_t * pScratchOut,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q15 sparse FIR filter.
+ * @param[in,out] S points to an instance of the Q15 sparse FIR structure.
+ * @param[in] numTaps number of nonzero coefficients in the filter.
+ * @param[in] pCoeffs points to the array of filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] pTapDelay points to the array of offset times.
+ * @param[in] maxDelay maximum offset time supported.
+ * @param[in] blockSize number of samples that will be processed per block.
+ */
+ void arm_fir_sparse_init_q15(
+ arm_fir_sparse_instance_q15 * S,
+ uint16_t numTaps,
+ q15_t * pCoeffs,
+ q15_t * pState,
+ int32_t * pTapDelay,
+ uint16_t maxDelay,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q7 sparse FIR filter.
+ * @param[in] S points to an instance of the Q7 sparse FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] pScratchIn points to a temporary buffer of size blockSize.
+ * @param[in] pScratchOut points to a temporary buffer of size blockSize.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_sparse_q7(
+ arm_fir_sparse_instance_q7 * S,
+ q7_t * pSrc,
+ q7_t * pDst,
+ q7_t * pScratchIn,
+ q31_t * pScratchOut,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q7 sparse FIR filter.
+ * @param[in,out] S points to an instance of the Q7 sparse FIR structure.
+ * @param[in] numTaps number of nonzero coefficients in the filter.
+ * @param[in] pCoeffs points to the array of filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] pTapDelay points to the array of offset times.
+ * @param[in] maxDelay maximum offset time supported.
+ * @param[in] blockSize number of samples that will be processed per block.
+ */
+ void arm_fir_sparse_init_q7(
+ arm_fir_sparse_instance_q7 * S,
+ uint16_t numTaps,
+ q7_t * pCoeffs,
+ q7_t * pState,
+ int32_t * pTapDelay,
+ uint16_t maxDelay,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Floating-point sin_cos function.
+ * @param[in] theta input value in degrees
+ * @param[out] pSinVal points to the processed sine output.
+ * @param[out] pCosVal points to the processed cos output.
+ */
+ void arm_sin_cos_f32(
+ float32_t theta,
+ float32_t * pSinVal,
+ float32_t * pCosVal);
+
+
+ /**
+ * @brief Q31 sin_cos function.
+ * @param[in] theta scaled input value in degrees
+ * @param[out] pSinVal points to the processed sine output.
+ * @param[out] pCosVal points to the processed cosine output.
+ */
+ void arm_sin_cos_q31(
+ q31_t theta,
+ q31_t * pSinVal,
+ q31_t * pCosVal);
+
+
+ /**
+ * @brief Floating-point complex conjugate.
+ * @param[in] pSrc points to the input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] numSamples number of complex samples in each vector
+ */
+ void arm_cmplx_conj_f32(
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t numSamples);
+
+ /**
+ * @brief Q31 complex conjugate.
+ * @param[in] pSrc points to the input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] numSamples number of complex samples in each vector
+ */
+ void arm_cmplx_conj_q31(
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Q15 complex conjugate.
+ * @param[in] pSrc points to the input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] numSamples number of complex samples in each vector
+ */
+ void arm_cmplx_conj_q15(
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Floating-point complex magnitude squared
+ * @param[in] pSrc points to the complex input vector
+ * @param[out] pDst points to the real output vector
+ * @param[in] numSamples number of complex samples in the input vector
+ */
+ void arm_cmplx_mag_squared_f32(
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Q31 complex magnitude squared
+ * @param[in] pSrc points to the complex input vector
+ * @param[out] pDst points to the real output vector
+ * @param[in] numSamples number of complex samples in the input vector
+ */
+ void arm_cmplx_mag_squared_q31(
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Q15 complex magnitude squared
+ * @param[in] pSrc points to the complex input vector
+ * @param[out] pDst points to the real output vector
+ * @param[in] numSamples number of complex samples in the input vector
+ */
+ void arm_cmplx_mag_squared_q15(
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @ingroup groupController
+ */
+
+ /**
+ * @defgroup PID PID Motor Control
+ *
+ * A Proportional Integral Derivative (PID) controller is a generic feedback control
+ * loop mechanism widely used in industrial control systems.
+ * A PID controller is the most commonly used type of feedback controller.
+ *
+ * This set of functions implements (PID) controllers
+ * for Q15, Q31, and floating-point data types. The functions operate on a single sample
+ * of data and each call to the function returns a single processed value.
+ * S points to an instance of the PID control data structure. in
+ * is the input sample value. The functions return the output value.
+ *
+ * \par Algorithm:
+ * + * y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2] + * A0 = Kp + Ki + Kd + * A1 = (-Kp ) - (2 * Kd ) + * A2 = Kd+ * + * \par + * where \c Kp is proportional constant, \c Ki is Integral constant and \c Kd is Derivative constant + * + * \par + * \image html PID.gif "Proportional Integral Derivative Controller" + * + * \par + * The PID controller calculates an "error" value as the difference between + * the measured output and the reference input. + * The controller attempts to minimize the error by adjusting the process control inputs. + * The proportional value determines the reaction to the current error, + * the integral value determines the reaction based on the sum of recent errors, + * and the derivative value determines the reaction based on the rate at which the error has been changing. + * + * \par Instance Structure + * The Gains A0, A1, A2 and state variables for a PID controller are stored together in an instance data structure. + * A separate instance structure must be defined for each PID Controller. + * There are separate instance structure declarations for each of the 3 supported data types. + * + * \par Reset Functions + * There is also an associated reset function for each data type which clears the state array. + * + * \par Initialization Functions + * There is also an associated initialization function for each data type. + * The initialization function performs the following operations: + * - Initializes the Gains A0, A1, A2 from Kp,Ki, Kd gains. + * - Zeros out the values in the state buffer. + * + * \par + * Instance structure cannot be placed into a const data section and it is recommended to use the initialization function. + * + * \par Fixed-Point Behavior + * Care must be taken when using the fixed-point versions of the PID Controller functions. + * In particular, the overflow and saturation behavior of the accumulator used in each function must be considered. + * Refer to the function specific documentation below for usage guidelines. + */ + + /** + * @addtogroup PID + * @{ + */ + + /** + * @brief Process function for the floating-point PID Control. + * @param[in,out] S is an instance of the floating-point PID Control structure + * @param[in] in input sample to process + * @return out processed output sample. + */ + CMSIS_INLINE __STATIC_INLINE float32_t arm_pid_f32( + arm_pid_instance_f32 * S, + float32_t in) + { + float32_t out; + + /* y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2] */ + out = (S->A0 * in) + + (S->A1 * S->state[0]) + (S->A2 * S->state[1]) + (S->state[2]); + + /* Update state */ + S->state[1] = S->state[0]; + S->state[0] = in; + S->state[2] = out; + + /* return to application */ + return (out); + + } + + /** + * @brief Process function for the Q31 PID Control. + * @param[in,out] S points to an instance of the Q31 PID Control structure + * @param[in] in input sample to process + * @return out processed output sample. + * + * Scaling and Overflow Behavior: + * \par + * The function is implemented using an internal 64-bit accumulator. + * The accumulator has a 2.62 format and maintains full precision of the intermediate multiplication results but provides only a single guard bit. + * Thus, if the accumulator result overflows it wraps around rather than clip. + * In order to avoid overflows completely the input signal must be scaled down by 2 bits as there are four additions. + * After all multiply-accumulates are performed, the 2.62 accumulator is truncated to 1.32 format and then saturated to 1.31 format. + */ + CMSIS_INLINE __STATIC_INLINE q31_t arm_pid_q31( + arm_pid_instance_q31 * S, + q31_t in) + { + q63_t acc; + q31_t out; + + /* acc = A0 * x[n] */ + acc = (q63_t) S->A0 * in; + + /* acc += A1 * x[n-1] */ + acc += (q63_t) S->A1 * S->state[0]; + + /* acc += A2 * x[n-2] */ + acc += (q63_t) S->A2 * S->state[1]; + + /* convert output to 1.31 format to add y[n-1] */ + out = (q31_t) (acc >> 31U); + + /* out += y[n-1] */ + out += S->state[2]; + + /* Update state */ + S->state[1] = S->state[0]; + S->state[0] = in; + S->state[2] = out; + + /* return to application */ + return (out); + } + + + /** + * @brief Process function for the Q15 PID Control. + * @param[in,out] S points to an instance of the Q15 PID Control structure + * @param[in] in input sample to process + * @return out processed output sample. + * + * Scaling and Overflow Behavior: + * \par + * The function is implemented using a 64-bit internal accumulator. + * Both Gains and state variables are represented in 1.15 format and multiplications yield a 2.30 result. + * The 2.30 intermediate results are accumulated in a 64-bit accumulator in 34.30 format. + * There is no risk of internal overflow with this approach and the full precision of intermediate multiplications is preserved. + * After all additions have been performed, the accumulator is truncated to 34.15 format by discarding low 15 bits. + * Lastly, the accumulator is saturated to yield a result in 1.15 format. + */ + CMSIS_INLINE __STATIC_INLINE q15_t arm_pid_q15( + arm_pid_instance_q15 * S, + q15_t in) + { + q63_t acc; + q15_t out; + +#if defined (ARM_MATH_DSP) + __SIMD32_TYPE *vstate; + + /* Implementation of PID controller */ + + /* acc = A0 * x[n] */ + acc = (q31_t) __SMUAD((uint32_t)S->A0, (uint32_t)in); + + /* acc += A1 * x[n-1] + A2 * x[n-2] */ + vstate = __SIMD32_CONST(S->state); + acc = (q63_t)__SMLALD((uint32_t)S->A1, (uint32_t)*vstate, (uint64_t)acc); +#else + /* acc = A0 * x[n] */ + acc = ((q31_t) S->A0) * in; + + /* acc += A1 * x[n-1] + A2 * x[n-2] */ + acc += (q31_t) S->A1 * S->state[0]; + acc += (q31_t) S->A2 * S->state[1]; +#endif + + /* acc += y[n-1] */ + acc += (q31_t) S->state[2] << 15; + + /* saturate the output */ + out = (q15_t) (__SSAT((acc >> 15), 16)); + + /* Update state */ + S->state[1] = S->state[0]; + S->state[0] = in; + S->state[2] = out; + + /* return to application */ + return (out); + } + + /** + * @} end of PID group + */ + + + /** + * @brief Floating-point matrix inverse. + * @param[in] src points to the instance of the input floating-point matrix structure. + * @param[out] dst points to the instance of the output floating-point matrix structure. + * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match. + * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR. + */ + arm_status arm_mat_inverse_f32( + const arm_matrix_instance_f32 * src, + arm_matrix_instance_f32 * dst); + + + /** + * @brief Floating-point matrix inverse. + * @param[in] src points to the instance of the input floating-point matrix structure. + * @param[out] dst points to the instance of the output floating-point matrix structure. + * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match. + * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR. + */ + arm_status arm_mat_inverse_f64( + const arm_matrix_instance_f64 * src, + arm_matrix_instance_f64 * dst); + + + + /** + * @ingroup groupController + */ + + /** + * @defgroup clarke Vector Clarke Transform + * Forward Clarke transform converts the instantaneous stator phases into a two-coordinate time invariant vector. + * Generally the Clarke transform uses three-phase currents
Ia, Ib and Ic to calculate currents
+ * in the two-phase orthogonal stator axis Ialpha and Ibeta.
+ * When Ialpha is superposed with Ia as shown in the figure below
+ * \image html clarke.gif Stator current space vector and its components in (a,b).
+ * and Ia + Ib + Ic = 0, in this condition Ialpha and Ibeta
+ * can be calculated using only Ia and Ib.
+ *
+ * The function operates on a single sample of data and each call to the function returns the processed output.
+ * The library provides separate functions for Q31 and floating-point data types.
+ * \par Algorithm
+ * \image html clarkeFormula.gif
+ * where Ia and Ib are the instantaneous stator phases and
+ * pIalpha and pIbeta are the two coordinates of time invariant vector.
+ * \par Fixed-Point Behavior
+ * Care must be taken when using the Q31 version of the Clarke transform.
+ * In particular, the overflow and saturation behavior of the accumulator used must be considered.
+ * Refer to the function specific documentation below for usage guidelines.
+ */
+
+ /**
+ * @addtogroup clarke
+ * @{
+ */
+
+ /**
+ *
+ * @brief Floating-point Clarke transform
+ * @param[in] Ia input three-phase coordinate a
+ * @param[in] Ib input three-phase coordinate b
+ * @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
+ * @param[out] pIbeta points to output two-phase orthogonal vector axis beta
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_clarke_f32(
+ float32_t Ia,
+ float32_t Ib,
+ float32_t * pIalpha,
+ float32_t * pIbeta)
+ {
+ /* Calculate pIalpha using the equation, pIalpha = Ia */
+ *pIalpha = Ia;
+
+ /* Calculate pIbeta using the equation, pIbeta = (1/sqrt(3)) * Ia + (2/sqrt(3)) * Ib */
+ *pIbeta = ((float32_t) 0.57735026919 * Ia + (float32_t) 1.15470053838 * Ib);
+ }
+
+
+ /**
+ * @brief Clarke transform for Q31 version
+ * @param[in] Ia input three-phase coordinate a
+ * @param[in] Ib input three-phase coordinate b
+ * @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
+ * @param[out] pIbeta points to output two-phase orthogonal vector axis beta
+ *
+ * Scaling and Overflow Behavior:
+ * \par
+ * The function is implemented using an internal 32-bit accumulator.
+ * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
+ * There is saturation on the addition, hence there is no risk of overflow.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_clarke_q31(
+ q31_t Ia,
+ q31_t Ib,
+ q31_t * pIalpha,
+ q31_t * pIbeta)
+ {
+ q31_t product1, product2; /* Temporary variables used to store intermediate results */
+
+ /* Calculating pIalpha from Ia by equation pIalpha = Ia */
+ *pIalpha = Ia;
+
+ /* Intermediate product is calculated by (1/(sqrt(3)) * Ia) */
+ product1 = (q31_t) (((q63_t) Ia * 0x24F34E8B) >> 30);
+
+ /* Intermediate product is calculated by (2/sqrt(3) * Ib) */
+ product2 = (q31_t) (((q63_t) Ib * 0x49E69D16) >> 30);
+
+ /* pIbeta is calculated by adding the intermediate products */
+ *pIbeta = __QADD(product1, product2);
+ }
+
+ /**
+ * @} end of clarke group
+ */
+
+ /**
+ * @brief Converts the elements of the Q7 vector to Q31 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_q7_to_q31(
+ q7_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+
+ /**
+ * @ingroup groupController
+ */
+
+ /**
+ * @defgroup inv_clarke Vector Inverse Clarke Transform
+ * Inverse Clarke transform converts the two-coordinate time invariant vector into instantaneous stator phases.
+ *
+ * The function operates on a single sample of data and each call to the function returns the processed output.
+ * The library provides separate functions for Q31 and floating-point data types.
+ * \par Algorithm
+ * \image html clarkeInvFormula.gif
+ * where pIa and pIb are the instantaneous stator phases and
+ * Ialpha and Ibeta are the two coordinates of time invariant vector.
+ * \par Fixed-Point Behavior
+ * Care must be taken when using the Q31 version of the Clarke transform.
+ * In particular, the overflow and saturation behavior of the accumulator used must be considered.
+ * Refer to the function specific documentation below for usage guidelines.
+ */
+
+ /**
+ * @addtogroup inv_clarke
+ * @{
+ */
+
+ /**
+ * @brief Floating-point Inverse Clarke transform
+ * @param[in] Ialpha input two-phase orthogonal vector axis alpha
+ * @param[in] Ibeta input two-phase orthogonal vector axis beta
+ * @param[out] pIa points to output three-phase coordinate a
+ * @param[out] pIb points to output three-phase coordinate b
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_inv_clarke_f32(
+ float32_t Ialpha,
+ float32_t Ibeta,
+ float32_t * pIa,
+ float32_t * pIb)
+ {
+ /* Calculating pIa from Ialpha by equation pIa = Ialpha */
+ *pIa = Ialpha;
+
+ /* Calculating pIb from Ialpha and Ibeta by equation pIb = -(1/2) * Ialpha + (sqrt(3)/2) * Ibeta */
+ *pIb = -0.5f * Ialpha + 0.8660254039f * Ibeta;
+ }
+
+
+ /**
+ * @brief Inverse Clarke transform for Q31 version
+ * @param[in] Ialpha input two-phase orthogonal vector axis alpha
+ * @param[in] Ibeta input two-phase orthogonal vector axis beta
+ * @param[out] pIa points to output three-phase coordinate a
+ * @param[out] pIb points to output three-phase coordinate b
+ *
+ * Scaling and Overflow Behavior:
+ * \par
+ * The function is implemented using an internal 32-bit accumulator.
+ * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
+ * There is saturation on the subtraction, hence there is no risk of overflow.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_inv_clarke_q31(
+ q31_t Ialpha,
+ q31_t Ibeta,
+ q31_t * pIa,
+ q31_t * pIb)
+ {
+ q31_t product1, product2; /* Temporary variables used to store intermediate results */
+
+ /* Calculating pIa from Ialpha by equation pIa = Ialpha */
+ *pIa = Ialpha;
+
+ /* Intermediate product is calculated by (1/(2*sqrt(3)) * Ia) */
+ product1 = (q31_t) (((q63_t) (Ialpha) * (0x40000000)) >> 31);
+
+ /* Intermediate product is calculated by (1/sqrt(3) * pIb) */
+ product2 = (q31_t) (((q63_t) (Ibeta) * (0x6ED9EBA1)) >> 31);
+
+ /* pIb is calculated by subtracting the products */
+ *pIb = __QSUB(product2, product1);
+ }
+
+ /**
+ * @} end of inv_clarke group
+ */
+
+ /**
+ * @brief Converts the elements of the Q7 vector to Q15 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_q7_to_q15(
+ q7_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+
+ /**
+ * @ingroup groupController
+ */
+
+ /**
+ * @defgroup park Vector Park Transform
+ *
+ * Forward Park transform converts the input two-coordinate vector to flux and torque components.
+ * The Park transform can be used to realize the transformation of the Ialpha and the Ibeta currents
+ * from the stationary to the moving reference frame and control the spatial relationship between
+ * the stator vector current and rotor flux vector.
+ * If we consider the d axis aligned with the rotor flux, the diagram below shows the
+ * current vector and the relationship from the two reference frames:
+ * \image html park.gif "Stator current space vector and its component in (a,b) and in the d,q rotating reference frame"
+ *
+ * The function operates on a single sample of data and each call to the function returns the processed output.
+ * The library provides separate functions for Q31 and floating-point data types.
+ * \par Algorithm
+ * \image html parkFormula.gif
+ * where Ialpha and Ibeta are the stator vector components,
+ * pId and pIq are rotor vector components and cosVal and sinVal are the
+ * cosine and sine values of theta (rotor flux position).
+ * \par Fixed-Point Behavior
+ * Care must be taken when using the Q31 version of the Park transform.
+ * In particular, the overflow and saturation behavior of the accumulator used must be considered.
+ * Refer to the function specific documentation below for usage guidelines.
+ */
+
+ /**
+ * @addtogroup park
+ * @{
+ */
+
+ /**
+ * @brief Floating-point Park transform
+ * @param[in] Ialpha input two-phase vector coordinate alpha
+ * @param[in] Ibeta input two-phase vector coordinate beta
+ * @param[out] pId points to output rotor reference frame d
+ * @param[out] pIq points to output rotor reference frame q
+ * @param[in] sinVal sine value of rotation angle theta
+ * @param[in] cosVal cosine value of rotation angle theta
+ *
+ * The function implements the forward Park transform.
+ *
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_park_f32(
+ float32_t Ialpha,
+ float32_t Ibeta,
+ float32_t * pId,
+ float32_t * pIq,
+ float32_t sinVal,
+ float32_t cosVal)
+ {
+ /* Calculate pId using the equation, pId = Ialpha * cosVal + Ibeta * sinVal */
+ *pId = Ialpha * cosVal + Ibeta * sinVal;
+
+ /* Calculate pIq using the equation, pIq = - Ialpha * sinVal + Ibeta * cosVal */
+ *pIq = -Ialpha * sinVal + Ibeta * cosVal;
+ }
+
+
+ /**
+ * @brief Park transform for Q31 version
+ * @param[in] Ialpha input two-phase vector coordinate alpha
+ * @param[in] Ibeta input two-phase vector coordinate beta
+ * @param[out] pId points to output rotor reference frame d
+ * @param[out] pIq points to output rotor reference frame q
+ * @param[in] sinVal sine value of rotation angle theta
+ * @param[in] cosVal cosine value of rotation angle theta
+ *
+ * Scaling and Overflow Behavior:
+ * \par
+ * The function is implemented using an internal 32-bit accumulator.
+ * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
+ * There is saturation on the addition and subtraction, hence there is no risk of overflow.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_park_q31(
+ q31_t Ialpha,
+ q31_t Ibeta,
+ q31_t * pId,
+ q31_t * pIq,
+ q31_t sinVal,
+ q31_t cosVal)
+ {
+ q31_t product1, product2; /* Temporary variables used to store intermediate results */
+ q31_t product3, product4; /* Temporary variables used to store intermediate results */
+
+ /* Intermediate product is calculated by (Ialpha * cosVal) */
+ product1 = (q31_t) (((q63_t) (Ialpha) * (cosVal)) >> 31);
+
+ /* Intermediate product is calculated by (Ibeta * sinVal) */
+ product2 = (q31_t) (((q63_t) (Ibeta) * (sinVal)) >> 31);
+
+
+ /* Intermediate product is calculated by (Ialpha * sinVal) */
+ product3 = (q31_t) (((q63_t) (Ialpha) * (sinVal)) >> 31);
+
+ /* Intermediate product is calculated by (Ibeta * cosVal) */
+ product4 = (q31_t) (((q63_t) (Ibeta) * (cosVal)) >> 31);
+
+ /* Calculate pId by adding the two intermediate products 1 and 2 */
+ *pId = __QADD(product1, product2);
+
+ /* Calculate pIq by subtracting the two intermediate products 3 from 4 */
+ *pIq = __QSUB(product4, product3);
+ }
+
+ /**
+ * @} end of park group
+ */
+
+ /**
+ * @brief Converts the elements of the Q7 vector to floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q7_to_float(
+ q7_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @ingroup groupController
+ */
+
+ /**
+ * @defgroup inv_park Vector Inverse Park transform
+ * Inverse Park transform converts the input flux and torque components to two-coordinate vector.
+ *
+ * The function operates on a single sample of data and each call to the function returns the processed output.
+ * The library provides separate functions for Q31 and floating-point data types.
+ * \par Algorithm
+ * \image html parkInvFormula.gif
+ * where pIalpha and pIbeta are the stator vector components,
+ * Id and Iq are rotor vector components and cosVal and sinVal are the
+ * cosine and sine values of theta (rotor flux position).
+ * \par Fixed-Point Behavior
+ * Care must be taken when using the Q31 version of the Park transform.
+ * In particular, the overflow and saturation behavior of the accumulator used must be considered.
+ * Refer to the function specific documentation below for usage guidelines.
+ */
+
+ /**
+ * @addtogroup inv_park
+ * @{
+ */
+
+ /**
+ * @brief Floating-point Inverse Park transform
+ * @param[in] Id input coordinate of rotor reference frame d
+ * @param[in] Iq input coordinate of rotor reference frame q
+ * @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
+ * @param[out] pIbeta points to output two-phase orthogonal vector axis beta
+ * @param[in] sinVal sine value of rotation angle theta
+ * @param[in] cosVal cosine value of rotation angle theta
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_inv_park_f32(
+ float32_t Id,
+ float32_t Iq,
+ float32_t * pIalpha,
+ float32_t * pIbeta,
+ float32_t sinVal,
+ float32_t cosVal)
+ {
+ /* Calculate pIalpha using the equation, pIalpha = Id * cosVal - Iq * sinVal */
+ *pIalpha = Id * cosVal - Iq * sinVal;
+
+ /* Calculate pIbeta using the equation, pIbeta = Id * sinVal + Iq * cosVal */
+ *pIbeta = Id * sinVal + Iq * cosVal;
+ }
+
+
+ /**
+ * @brief Inverse Park transform for Q31 version
+ * @param[in] Id input coordinate of rotor reference frame d
+ * @param[in] Iq input coordinate of rotor reference frame q
+ * @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
+ * @param[out] pIbeta points to output two-phase orthogonal vector axis beta
+ * @param[in] sinVal sine value of rotation angle theta
+ * @param[in] cosVal cosine value of rotation angle theta
+ *
+ * Scaling and Overflow Behavior:
+ * \par
+ * The function is implemented using an internal 32-bit accumulator.
+ * The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
+ * There is saturation on the addition, hence there is no risk of overflow.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_inv_park_q31(
+ q31_t Id,
+ q31_t Iq,
+ q31_t * pIalpha,
+ q31_t * pIbeta,
+ q31_t sinVal,
+ q31_t cosVal)
+ {
+ q31_t product1, product2; /* Temporary variables used to store intermediate results */
+ q31_t product3, product4; /* Temporary variables used to store intermediate results */
+
+ /* Intermediate product is calculated by (Id * cosVal) */
+ product1 = (q31_t) (((q63_t) (Id) * (cosVal)) >> 31);
+
+ /* Intermediate product is calculated by (Iq * sinVal) */
+ product2 = (q31_t) (((q63_t) (Iq) * (sinVal)) >> 31);
+
+
+ /* Intermediate product is calculated by (Id * sinVal) */
+ product3 = (q31_t) (((q63_t) (Id) * (sinVal)) >> 31);
+
+ /* Intermediate product is calculated by (Iq * cosVal) */
+ product4 = (q31_t) (((q63_t) (Iq) * (cosVal)) >> 31);
+
+ /* Calculate pIalpha by using the two intermediate products 1 and 2 */
+ *pIalpha = __QSUB(product1, product2);
+
+ /* Calculate pIbeta by using the two intermediate products 3 and 4 */
+ *pIbeta = __QADD(product4, product3);
+ }
+
+ /**
+ * @} end of Inverse park group
+ */
+
+
+ /**
+ * @brief Converts the elements of the Q31 vector to floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q31_to_float(
+ q31_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @ingroup groupInterpolation
+ */
+
+ /**
+ * @defgroup LinearInterpolate Linear Interpolation
+ *
+ * Linear interpolation is a method of curve fitting using linear polynomials.
+ * Linear interpolation works by effectively drawing a straight line between two neighboring samples and returning the appropriate point along that line
+ *
+ * \par
+ * \image html LinearInterp.gif "Linear interpolation"
+ *
+ * \par
+ * A Linear Interpolate function calculates an output value(y), for the input(x)
+ * using linear interpolation of the input values x0, x1( nearest input values) and the output values y0 and y1(nearest output values)
+ *
+ * \par Algorithm:
+ * + * y = y0 + (x - x0) * ((y1 - y0)/(x1-x0)) + * where x0, x1 are nearest values of input x + * y0, y1 are nearest values to output y + *+ * + * \par + * This set of functions implements Linear interpolation process + * for Q7, Q15, Q31, and floating-point data types. The functions operate on a single + * sample of data and each call to the function returns a single processed value. + *
S points to an instance of the Linear Interpolate function data structure.
+ * x is the input sample value. The functions returns the output value.
+ *
+ * \par
+ * if x is outside of the table boundary, Linear interpolation returns first value of the table
+ * if x is below input range and returns last value of table if x is above range.
+ */
+
+ /**
+ * @addtogroup LinearInterpolate
+ * @{
+ */
+
+ /**
+ * @brief Process function for the floating-point Linear Interpolation Function.
+ * @param[in,out] S is an instance of the floating-point Linear Interpolation structure
+ * @param[in] x input sample to process
+ * @return y processed output sample.
+ *
+ */
+ CMSIS_INLINE __STATIC_INLINE float32_t arm_linear_interp_f32(
+ arm_linear_interp_instance_f32 * S,
+ float32_t x)
+ {
+ float32_t y;
+ float32_t x0, x1; /* Nearest input values */
+ float32_t y0, y1; /* Nearest output values */
+ float32_t xSpacing = S->xSpacing; /* spacing between input values */
+ int32_t i; /* Index variable */
+ float32_t *pYData = S->pYData; /* pointer to output table */
+
+ /* Calculation of index */
+ i = (int32_t) ((x - S->x1) / xSpacing);
+
+ if (i < 0)
+ {
+ /* Iniatilize output for below specified range as least output value of table */
+ y = pYData[0];
+ }
+ else if ((uint32_t)i >= S->nValues)
+ {
+ /* Iniatilize output for above specified range as last output value of table */
+ y = pYData[S->nValues - 1];
+ }
+ else
+ {
+ /* Calculation of nearest input values */
+ x0 = S->x1 + i * xSpacing;
+ x1 = S->x1 + (i + 1) * xSpacing;
+
+ /* Read of nearest output values */
+ y0 = pYData[i];
+ y1 = pYData[i + 1];
+
+ /* Calculation of output */
+ y = y0 + (x - x0) * ((y1 - y0) / (x1 - x0));
+
+ }
+
+ /* returns output value */
+ return (y);
+ }
+
+
+ /**
+ *
+ * @brief Process function for the Q31 Linear Interpolation Function.
+ * @param[in] pYData pointer to Q31 Linear Interpolation table
+ * @param[in] x input sample to process
+ * @param[in] nValues number of table values
+ * @return y processed output sample.
+ *
+ * \par
+ * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part.
+ * This function can support maximum of table size 2^12.
+ *
+ */
+ CMSIS_INLINE __STATIC_INLINE q31_t arm_linear_interp_q31(
+ q31_t * pYData,
+ q31_t x,
+ uint32_t nValues)
+ {
+ q31_t y; /* output */
+ q31_t y0, y1; /* Nearest output values */
+ q31_t fract; /* fractional part */
+ int32_t index; /* Index to read nearest output values */
+
+ /* Input is in 12.20 format */
+ /* 12 bits for the table index */
+ /* Index value calculation */
+ index = ((x & (q31_t)0xFFF00000) >> 20);
+
+ if (index >= (int32_t)(nValues - 1))
+ {
+ return (pYData[nValues - 1]);
+ }
+ else if (index < 0)
+ {
+ return (pYData[0]);
+ }
+ else
+ {
+ /* 20 bits for the fractional part */
+ /* shift left by 11 to keep fract in 1.31 format */
+ fract = (x & 0x000FFFFF) << 11;
+
+ /* Read two nearest output values from the index in 1.31(q31) format */
+ y0 = pYData[index];
+ y1 = pYData[index + 1];
+
+ /* Calculation of y0 * (1-fract) and y is in 2.30 format */
+ y = ((q31_t) ((q63_t) y0 * (0x7FFFFFFF - fract) >> 32));
+
+ /* Calculation of y0 * (1-fract) + y1 *fract and y is in 2.30 format */
+ y += ((q31_t) (((q63_t) y1 * fract) >> 32));
+
+ /* Convert y to 1.31 format */
+ return (y << 1U);
+ }
+ }
+
+
+ /**
+ *
+ * @brief Process function for the Q15 Linear Interpolation Function.
+ * @param[in] pYData pointer to Q15 Linear Interpolation table
+ * @param[in] x input sample to process
+ * @param[in] nValues number of table values
+ * @return y processed output sample.
+ *
+ * \par
+ * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part.
+ * This function can support maximum of table size 2^12.
+ *
+ */
+ CMSIS_INLINE __STATIC_INLINE q15_t arm_linear_interp_q15(
+ q15_t * pYData,
+ q31_t x,
+ uint32_t nValues)
+ {
+ q63_t y; /* output */
+ q15_t y0, y1; /* Nearest output values */
+ q31_t fract; /* fractional part */
+ int32_t index; /* Index to read nearest output values */
+
+ /* Input is in 12.20 format */
+ /* 12 bits for the table index */
+ /* Index value calculation */
+ index = ((x & (int32_t)0xFFF00000) >> 20);
+
+ if (index >= (int32_t)(nValues - 1))
+ {
+ return (pYData[nValues - 1]);
+ }
+ else if (index < 0)
+ {
+ return (pYData[0]);
+ }
+ else
+ {
+ /* 20 bits for the fractional part */
+ /* fract is in 12.20 format */
+ fract = (x & 0x000FFFFF);
+
+ /* Read two nearest output values from the index */
+ y0 = pYData[index];
+ y1 = pYData[index + 1];
+
+ /* Calculation of y0 * (1-fract) and y is in 13.35 format */
+ y = ((q63_t) y0 * (0xFFFFF - fract));
+
+ /* Calculation of (y0 * (1-fract) + y1 * fract) and y is in 13.35 format */
+ y += ((q63_t) y1 * (fract));
+
+ /* convert y to 1.15 format */
+ return (q15_t) (y >> 20);
+ }
+ }
+
+
+ /**
+ *
+ * @brief Process function for the Q7 Linear Interpolation Function.
+ * @param[in] pYData pointer to Q7 Linear Interpolation table
+ * @param[in] x input sample to process
+ * @param[in] nValues number of table values
+ * @return y processed output sample.
+ *
+ * \par
+ * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part.
+ * This function can support maximum of table size 2^12.
+ */
+ CMSIS_INLINE __STATIC_INLINE q7_t arm_linear_interp_q7(
+ q7_t * pYData,
+ q31_t x,
+ uint32_t nValues)
+ {
+ q31_t y; /* output */
+ q7_t y0, y1; /* Nearest output values */
+ q31_t fract; /* fractional part */
+ uint32_t index; /* Index to read nearest output values */
+
+ /* Input is in 12.20 format */
+ /* 12 bits for the table index */
+ /* Index value calculation */
+ if (x < 0)
+ {
+ return (pYData[0]);
+ }
+ index = (x >> 20) & 0xfff;
+
+ if (index >= (nValues - 1))
+ {
+ return (pYData[nValues - 1]);
+ }
+ else
+ {
+ /* 20 bits for the fractional part */
+ /* fract is in 12.20 format */
+ fract = (x & 0x000FFFFF);
+
+ /* Read two nearest output values from the index and are in 1.7(q7) format */
+ y0 = pYData[index];
+ y1 = pYData[index + 1];
+
+ /* Calculation of y0 * (1-fract ) and y is in 13.27(q27) format */
+ y = ((y0 * (0xFFFFF - fract)));
+
+ /* Calculation of y1 * fract + y0 * (1-fract) and y is in 13.27(q27) format */
+ y += (y1 * fract);
+
+ /* convert y to 1.7(q7) format */
+ return (q7_t) (y >> 20);
+ }
+ }
+
+ /**
+ * @} end of LinearInterpolate group
+ */
+
+ /**
+ * @brief Fast approximation to the trigonometric sine function for floating-point data.
+ * @param[in] x input value in radians.
+ * @return sin(x).
+ */
+ float32_t arm_sin_f32(
+ float32_t x);
+
+
+ /**
+ * @brief Fast approximation to the trigonometric sine function for Q31 data.
+ * @param[in] x Scaled input value in radians.
+ * @return sin(x).
+ */
+ q31_t arm_sin_q31(
+ q31_t x);
+
+
+ /**
+ * @brief Fast approximation to the trigonometric sine function for Q15 data.
+ * @param[in] x Scaled input value in radians.
+ * @return sin(x).
+ */
+ q15_t arm_sin_q15(
+ q15_t x);
+
+
+ /**
+ * @brief Fast approximation to the trigonometric cosine function for floating-point data.
+ * @param[in] x input value in radians.
+ * @return cos(x).
+ */
+ float32_t arm_cos_f32(
+ float32_t x);
+
+
+ /**
+ * @brief Fast approximation to the trigonometric cosine function for Q31 data.
+ * @param[in] x Scaled input value in radians.
+ * @return cos(x).
+ */
+ q31_t arm_cos_q31(
+ q31_t x);
+
+
+ /**
+ * @brief Fast approximation to the trigonometric cosine function for Q15 data.
+ * @param[in] x Scaled input value in radians.
+ * @return cos(x).
+ */
+ q15_t arm_cos_q15(
+ q15_t x);
+
+
+ /**
+ * @ingroup groupFastMath
+ */
+
+
+ /**
+ * @defgroup SQRT Square Root
+ *
+ * Computes the square root of a number.
+ * There are separate functions for Q15, Q31, and floating-point data types.
+ * The square root function is computed using the Newton-Raphson algorithm.
+ * This is an iterative algorithm of the form:
+ * + * x1 = x0 - f(x0)/f'(x0) + *+ * where
x1 is the current estimate,
+ * x0 is the previous estimate, and
+ * f'(x0) is the derivative of f() evaluated at x0.
+ * For the square root function, the algorithm reduces to:
+ * + * x0 = in/2 [initial guess] + * x1 = 1/2 * ( x0 + in / x0) [each iteration] + *+ */ + + + /** + * @addtogroup SQRT + * @{ + */ + + /** + * @brief Floating-point square root function. + * @param[in] in input value. + * @param[out] pOut square root of input value. + * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if + *
in is negative value and returns zero output for negative values.
+ */
+ CMSIS_INLINE __STATIC_INLINE arm_status arm_sqrt_f32(
+ float32_t in,
+ float32_t * pOut)
+ {
+ if (in >= 0.0f)
+ {
+
+#if (__FPU_USED == 1) && defined ( __CC_ARM )
+ *pOut = __sqrtf(in);
+#elif (__FPU_USED == 1) && (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))
+ *pOut = __builtin_sqrtf(in);
+#elif (__FPU_USED == 1) && defined(__GNUC__)
+ *pOut = __builtin_sqrtf(in);
+#elif (__FPU_USED == 1) && defined ( __ICCARM__ ) && (__VER__ >= 6040000)
+ __ASM("VSQRT.F32 %0,%1" : "=t"(*pOut) : "t"(in));
+#else
+ *pOut = sqrtf(in);
+#endif
+
+ return (ARM_MATH_SUCCESS);
+ }
+ else
+ {
+ *pOut = 0.0f;
+ return (ARM_MATH_ARGUMENT_ERROR);
+ }
+ }
+
+
+ /**
+ * @brief Q31 square root function.
+ * @param[in] in input value. The range of the input value is [0 +1) or 0x00000000 to 0x7FFFFFFF.
+ * @param[out] pOut square root of input value.
+ * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if
+ * in is negative value and returns zero output for negative values.
+ */
+ arm_status arm_sqrt_q31(
+ q31_t in,
+ q31_t * pOut);
+
+
+ /**
+ * @brief Q15 square root function.
+ * @param[in] in input value. The range of the input value is [0 +1) or 0x0000 to 0x7FFF.
+ * @param[out] pOut square root of input value.
+ * @return The function returns ARM_MATH_SUCCESS if input value is positive value or ARM_MATH_ARGUMENT_ERROR if
+ * in is negative value and returns zero output for negative values.
+ */
+ arm_status arm_sqrt_q15(
+ q15_t in,
+ q15_t * pOut);
+
+ /**
+ * @} end of SQRT group
+ */
+
+
+ /**
+ * @brief floating-point Circular write function.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_circularWrite_f32(
+ int32_t * circBuffer,
+ int32_t L,
+ uint16_t * writeOffset,
+ int32_t bufferInc,
+ const int32_t * src,
+ int32_t srcInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0U;
+ int32_t wOffset;
+
+ /* Copy the value of Index pointer that points
+ * to the current location where the input samples to be copied */
+ wOffset = *writeOffset;
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the input sample to the circular buffer */
+ circBuffer[wOffset] = *src;
+
+ /* Update the input pointer */
+ src += srcInc;
+
+ /* Circularly update wOffset. Watch out for positive and negative value */
+ wOffset += bufferInc;
+ if (wOffset >= L)
+ wOffset -= L;
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *writeOffset = (uint16_t)wOffset;
+ }
+
+
+
+ /**
+ * @brief floating-point Circular Read function.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_circularRead_f32(
+ int32_t * circBuffer,
+ int32_t L,
+ int32_t * readOffset,
+ int32_t bufferInc,
+ int32_t * dst,
+ int32_t * dst_base,
+ int32_t dst_length,
+ int32_t dstInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0U;
+ int32_t rOffset, dst_end;
+
+ /* Copy the value of Index pointer that points
+ * to the current location from where the input samples to be read */
+ rOffset = *readOffset;
+ dst_end = (int32_t) (dst_base + dst_length);
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the sample from the circular buffer to the destination buffer */
+ *dst = circBuffer[rOffset];
+
+ /* Update the input pointer */
+ dst += dstInc;
+
+ if (dst == (int32_t *) dst_end)
+ {
+ dst = dst_base;
+ }
+
+ /* Circularly update rOffset. Watch out for positive and negative value */
+ rOffset += bufferInc;
+
+ if (rOffset >= L)
+ {
+ rOffset -= L;
+ }
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *readOffset = rOffset;
+ }
+
+
+ /**
+ * @brief Q15 Circular write function.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_circularWrite_q15(
+ q15_t * circBuffer,
+ int32_t L,
+ uint16_t * writeOffset,
+ int32_t bufferInc,
+ const q15_t * src,
+ int32_t srcInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0U;
+ int32_t wOffset;
+
+ /* Copy the value of Index pointer that points
+ * to the current location where the input samples to be copied */
+ wOffset = *writeOffset;
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the input sample to the circular buffer */
+ circBuffer[wOffset] = *src;
+
+ /* Update the input pointer */
+ src += srcInc;
+
+ /* Circularly update wOffset. Watch out for positive and negative value */
+ wOffset += bufferInc;
+ if (wOffset >= L)
+ wOffset -= L;
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *writeOffset = (uint16_t)wOffset;
+ }
+
+
+ /**
+ * @brief Q15 Circular Read function.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_circularRead_q15(
+ q15_t * circBuffer,
+ int32_t L,
+ int32_t * readOffset,
+ int32_t bufferInc,
+ q15_t * dst,
+ q15_t * dst_base,
+ int32_t dst_length,
+ int32_t dstInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0;
+ int32_t rOffset, dst_end;
+
+ /* Copy the value of Index pointer that points
+ * to the current location from where the input samples to be read */
+ rOffset = *readOffset;
+
+ dst_end = (int32_t) (dst_base + dst_length);
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the sample from the circular buffer to the destination buffer */
+ *dst = circBuffer[rOffset];
+
+ /* Update the input pointer */
+ dst += dstInc;
+
+ if (dst == (q15_t *) dst_end)
+ {
+ dst = dst_base;
+ }
+
+ /* Circularly update wOffset. Watch out for positive and negative value */
+ rOffset += bufferInc;
+
+ if (rOffset >= L)
+ {
+ rOffset -= L;
+ }
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *readOffset = rOffset;
+ }
+
+
+ /**
+ * @brief Q7 Circular write function.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_circularWrite_q7(
+ q7_t * circBuffer,
+ int32_t L,
+ uint16_t * writeOffset,
+ int32_t bufferInc,
+ const q7_t * src,
+ int32_t srcInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0U;
+ int32_t wOffset;
+
+ /* Copy the value of Index pointer that points
+ * to the current location where the input samples to be copied */
+ wOffset = *writeOffset;
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the input sample to the circular buffer */
+ circBuffer[wOffset] = *src;
+
+ /* Update the input pointer */
+ src += srcInc;
+
+ /* Circularly update wOffset. Watch out for positive and negative value */
+ wOffset += bufferInc;
+ if (wOffset >= L)
+ wOffset -= L;
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *writeOffset = (uint16_t)wOffset;
+ }
+
+
+ /**
+ * @brief Q7 Circular Read function.
+ */
+ CMSIS_INLINE __STATIC_INLINE void arm_circularRead_q7(
+ q7_t * circBuffer,
+ int32_t L,
+ int32_t * readOffset,
+ int32_t bufferInc,
+ q7_t * dst,
+ q7_t * dst_base,
+ int32_t dst_length,
+ int32_t dstInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0;
+ int32_t rOffset, dst_end;
+
+ /* Copy the value of Index pointer that points
+ * to the current location from where the input samples to be read */
+ rOffset = *readOffset;
+
+ dst_end = (int32_t) (dst_base + dst_length);
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the sample from the circular buffer to the destination buffer */
+ *dst = circBuffer[rOffset];
+
+ /* Update the input pointer */
+ dst += dstInc;
+
+ if (dst == (q7_t *) dst_end)
+ {
+ dst = dst_base;
+ }
+
+ /* Circularly update rOffset. Watch out for positive and negative value */
+ rOffset += bufferInc;
+
+ if (rOffset >= L)
+ {
+ rOffset -= L;
+ }
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *readOffset = rOffset;
+ }
+
+
+ /**
+ * @brief Sum of the squares of the elements of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_q31(
+ q31_t * pSrc,
+ uint32_t blockSize,
+ q63_t * pResult);
+
+
+ /**
+ * @brief Sum of the squares of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_f32(
+ float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Sum of the squares of the elements of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_q15(
+ q15_t * pSrc,
+ uint32_t blockSize,
+ q63_t * pResult);
+
+
+ /**
+ * @brief Sum of the squares of the elements of a Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_q7(
+ q7_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Mean value of a Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_q7(
+ q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * pResult);
+
+
+ /**
+ * @brief Mean value of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_q15(
+ q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+
+ /**
+ * @brief Mean value of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_q31(
+ q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Mean value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_f32(
+ float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Variance of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_var_f32(
+ float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Variance of the elements of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_var_q31(
+ q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Variance of the elements of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_var_q15(
+ q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+
+ /**
+ * @brief Root Mean Square of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_rms_f32(
+ float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Root Mean Square of the elements of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_rms_q31(
+ q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Root Mean Square of the elements of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_rms_q15(
+ q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+
+ /**
+ * @brief Standard deviation of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_std_f32(
+ float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Standard deviation of the elements of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_std_q31(
+ q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Standard deviation of the elements of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_std_q15(
+ q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+
+ /**
+ * @brief Floating-point complex magnitude
+ * @param[in] pSrc points to the complex input vector
+ * @param[out] pDst points to the real output vector
+ * @param[in] numSamples number of complex samples in the input vector
+ */
+ void arm_cmplx_mag_f32(
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Q31 complex magnitude
+ * @param[in] pSrc points to the complex input vector
+ * @param[out] pDst points to the real output vector
+ * @param[in] numSamples number of complex samples in the input vector
+ */
+ void arm_cmplx_mag_q31(
+ q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Q15 complex magnitude
+ * @param[in] pSrc points to the complex input vector
+ * @param[out] pDst points to the real output vector
+ * @param[in] numSamples number of complex samples in the input vector
+ */
+ void arm_cmplx_mag_q15(
+ q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Q15 complex dot product
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[in] numSamples number of complex samples in each vector
+ * @param[out] realResult real part of the result returned here
+ * @param[out] imagResult imaginary part of the result returned here
+ */
+ void arm_cmplx_dot_prod_q15(
+ q15_t * pSrcA,
+ q15_t * pSrcB,
+ uint32_t numSamples,
+ q31_t * realResult,
+ q31_t * imagResult);
+
+
+ /**
+ * @brief Q31 complex dot product
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[in] numSamples number of complex samples in each vector
+ * @param[out] realResult real part of the result returned here
+ * @param[out] imagResult imaginary part of the result returned here
+ */
+ void arm_cmplx_dot_prod_q31(
+ q31_t * pSrcA,
+ q31_t * pSrcB,
+ uint32_t numSamples,
+ q63_t * realResult,
+ q63_t * imagResult);
+
+
+ /**
+ * @brief Floating-point complex dot product
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[in] numSamples number of complex samples in each vector
+ * @param[out] realResult real part of the result returned here
+ * @param[out] imagResult imaginary part of the result returned here
+ */
+ void arm_cmplx_dot_prod_f32(
+ float32_t * pSrcA,
+ float32_t * pSrcB,
+ uint32_t numSamples,
+ float32_t * realResult,
+ float32_t * imagResult);
+
+
+ /**
+ * @brief Q15 complex-by-real multiplication
+ * @param[in] pSrcCmplx points to the complex input vector
+ * @param[in] pSrcReal points to the real input vector
+ * @param[out] pCmplxDst points to the complex output vector
+ * @param[in] numSamples number of samples in each vector
+ */
+ void arm_cmplx_mult_real_q15(
+ q15_t * pSrcCmplx,
+ q15_t * pSrcReal,
+ q15_t * pCmplxDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Q31 complex-by-real multiplication
+ * @param[in] pSrcCmplx points to the complex input vector
+ * @param[in] pSrcReal points to the real input vector
+ * @param[out] pCmplxDst points to the complex output vector
+ * @param[in] numSamples number of samples in each vector
+ */
+ void arm_cmplx_mult_real_q31(
+ q31_t * pSrcCmplx,
+ q31_t * pSrcReal,
+ q31_t * pCmplxDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Floating-point complex-by-real multiplication
+ * @param[in] pSrcCmplx points to the complex input vector
+ * @param[in] pSrcReal points to the real input vector
+ * @param[out] pCmplxDst points to the complex output vector
+ * @param[in] numSamples number of samples in each vector
+ */
+ void arm_cmplx_mult_real_f32(
+ float32_t * pSrcCmplx,
+ float32_t * pSrcReal,
+ float32_t * pCmplxDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Minimum value of a Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] result is output pointer
+ * @param[in] index is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_q7(
+ q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * result,
+ uint32_t * index);
+
+
+ /**
+ * @brief Minimum value of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[in] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_q15(
+ q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult,
+ uint32_t * pIndex);
+
+
+ /**
+ * @brief Minimum value of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_q31(
+ q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult,
+ uint32_t * pIndex);
+
+
+ /**
+ * @brief Minimum value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_f32(
+ float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult,
+ uint32_t * pIndex);
+
+
+/**
+ * @brief Maximum value of a Q7 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_q7(
+ q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * pResult,
+ uint32_t * pIndex);
+
+
+/**
+ * @brief Maximum value of a Q15 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_q15(
+ q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult,
+ uint32_t * pIndex);
+
+
+/**
+ * @brief Maximum value of a Q31 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_q31(
+ q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult,
+ uint32_t * pIndex);
+
+
+/**
+ * @brief Maximum value of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_f32(
+ float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult,
+ uint32_t * pIndex);
+
+
+ /**
+ * @brief Q15 complex-by-complex multiplication
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] numSamples number of complex samples in each vector
+ */
+ void arm_cmplx_mult_cmplx_q15(
+ q15_t * pSrcA,
+ q15_t * pSrcB,
+ q15_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Q31 complex-by-complex multiplication
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] numSamples number of complex samples in each vector
+ */
+ void arm_cmplx_mult_cmplx_q31(
+ q31_t * pSrcA,
+ q31_t * pSrcB,
+ q31_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Floating-point complex-by-complex multiplication
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[out] pDst points to the output vector
+ * @param[in] numSamples number of complex samples in each vector
+ */
+ void arm_cmplx_mult_cmplx_f32(
+ float32_t * pSrcA,
+ float32_t * pSrcB,
+ float32_t * pDst,
+ uint32_t numSamples);
+
+
+ /**
+ * @brief Converts the elements of the floating-point vector to Q31 vector.
+ * @param[in] pSrc points to the floating-point input vector
+ * @param[out] pDst points to the Q31 output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_float_to_q31(
+ float32_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the floating-point vector to Q15 vector.
+ * @param[in] pSrc points to the floating-point input vector
+ * @param[out] pDst points to the Q15 output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_float_to_q15(
+ float32_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the floating-point vector to Q7 vector.
+ * @param[in] pSrc points to the floating-point input vector
+ * @param[out] pDst points to the Q7 output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_float_to_q7(
+ float32_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q31 vector to Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q31_to_q15(
+ q31_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q31 vector to Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q31_to_q7(
+ q31_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q15 vector to floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q15_to_float(
+ q15_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q15 vector to Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q15_to_q31(
+ q15_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q15 vector to Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q15_to_q7(
+ q15_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @ingroup groupInterpolation
+ */
+
+ /**
+ * @defgroup BilinearInterpolate Bilinear Interpolation
+ *
+ * Bilinear interpolation is an extension of linear interpolation applied to a two dimensional grid.
+ * The underlying function f(x, y) is sampled on a regular grid and the interpolation process
+ * determines values between the grid points.
+ * Bilinear interpolation is equivalent to two step linear interpolation, first in the x-dimension and then in the y-dimension.
+ * Bilinear interpolation is often used in image processing to rescale images.
+ * The CMSIS DSP library provides bilinear interpolation functions for Q7, Q15, Q31, and floating-point data types.
+ *
+ * Algorithm
+ * \par
+ * The instance structure used by the bilinear interpolation functions describes a two dimensional data table.
+ * For floating-point, the instance structure is defined as:
+ *
+ * typedef struct
+ * {
+ * uint16_t numRows;
+ * uint16_t numCols;
+ * float32_t *pData;
+ * } arm_bilinear_interp_instance_f32;
+ *
+ *
+ * \par
+ * where numRows specifies the number of rows in the table;
+ * numCols specifies the number of columns in the table;
+ * and pData points to an array of size numRows*numCols values.
+ * The data table pTable is organized in row order and the supplied data values fall on integer indexes.
+ * That is, table element (x,y) is located at pTable[x + y*numCols] where x and y are integers.
+ *
+ * \par
+ * Let (x, y) specify the desired interpolation point. Then define:
+ * + * XF = floor(x) + * YF = floor(y) + *+ * \par + * The interpolated output point is computed as: + *
+ * f(x, y) = f(XF, YF) * (1-(x-XF)) * (1-(y-YF)) + * + f(XF+1, YF) * (x-XF)*(1-(y-YF)) + * + f(XF, YF+1) * (1-(x-XF))*(y-YF) + * + f(XF+1, YF+1) * (x-XF)*(y-YF) + *+ * Note that the coordinates (x, y) contain integer and fractional components. + * The integer components specify which portion of the table to use while the + * fractional components control the interpolation processor. + * + * \par + * if (x,y) are outside of the table boundary, Bilinear interpolation returns zero output. + */ + + /** + * @addtogroup BilinearInterpolate + * @{ + */ + + + /** + * + * @brief Floating-point bilinear interpolation. + * @param[in,out] S points to an instance of the interpolation structure. + * @param[in] X interpolation coordinate. + * @param[in] Y interpolation coordinate. + * @return out interpolated value. + */ + CMSIS_INLINE __STATIC_INLINE float32_t arm_bilinear_interp_f32( + const arm_bilinear_interp_instance_f32 * S, + float32_t X, + float32_t Y) + { + float32_t out; + float32_t f00, f01, f10, f11; + float32_t *pData = S->pData; + int32_t xIndex, yIndex, index; + float32_t xdiff, ydiff; + float32_t b1, b2, b3, b4; + + xIndex = (int32_t) X; + yIndex = (int32_t) Y; + + /* Care taken for table outside boundary */ + /* Returns zero output when values are outside table boundary */ + if (xIndex < 0 || xIndex > (S->numRows - 1) || yIndex < 0 || yIndex > (S->numCols - 1)) + { + return (0); + } + + /* Calculation of index for two nearest points in X-direction */ + index = (xIndex - 1) + (yIndex - 1) * S->numCols; + + + /* Read two nearest points in X-direction */ + f00 = pData[index]; + f01 = pData[index + 1]; + + /* Calculation of index for two nearest points in Y-direction */ + index = (xIndex - 1) + (yIndex) * S->numCols; + + + /* Read two nearest points in Y-direction */ + f10 = pData[index]; + f11 = pData[index + 1]; + + /* Calculation of intermediate values */ + b1 = f00; + b2 = f01 - f00; + b3 = f10 - f00; + b4 = f00 - f01 - f10 + f11; + + /* Calculation of fractional part in X */ + xdiff = X - xIndex; + + /* Calculation of fractional part in Y */ + ydiff = Y - yIndex; + + /* Calculation of bi-linear interpolated output */ + out = b1 + b2 * xdiff + b3 * ydiff + b4 * xdiff * ydiff; + + /* return to application */ + return (out); + } + + + /** + * + * @brief Q31 bilinear interpolation. + * @param[in,out] S points to an instance of the interpolation structure. + * @param[in] X interpolation coordinate in 12.20 format. + * @param[in] Y interpolation coordinate in 12.20 format. + * @return out interpolated value. + */ + CMSIS_INLINE __STATIC_INLINE q31_t arm_bilinear_interp_q31( + arm_bilinear_interp_instance_q31 * S, + q31_t X, + q31_t Y) + { + q31_t out; /* Temporary output */ + q31_t acc = 0; /* output */ + q31_t xfract, yfract; /* X, Y fractional parts */ + q31_t x1, x2, y1, y2; /* Nearest output values */ + int32_t rI, cI; /* Row and column indices */ + q31_t *pYData = S->pData; /* pointer to output table values */ + uint32_t nCols = S->numCols; /* num of rows */ + + /* Input is in 12.20 format */ + /* 12 bits for the table index */ + /* Index value calculation */ + rI = ((X & (q31_t)0xFFF00000) >> 20); + + /* Input is in 12.20 format */ + /* 12 bits for the table index */ + /* Index value calculation */ + cI = ((Y & (q31_t)0xFFF00000) >> 20); + + /* Care taken for table outside boundary */ + /* Returns zero output when values are outside table boundary */ + if (rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) + { + return (0); + } + + /* 20 bits for the fractional part */ + /* shift left xfract by 11 to keep 1.31 format */ + xfract = (X & 0x000FFFFF) << 11U; + + /* Read two nearest output values from the index */ + x1 = pYData[(rI) + (int32_t)nCols * (cI) ]; + x2 = pYData[(rI) + (int32_t)nCols * (cI) + 1]; + + /* 20 bits for the fractional part */ + /* shift left yfract by 11 to keep 1.31 format */ + yfract = (Y & 0x000FFFFF) << 11U; + + /* Read two nearest output values from the index */ + y1 = pYData[(rI) + (int32_t)nCols * (cI + 1) ]; + y2 = pYData[(rI) + (int32_t)nCols * (cI + 1) + 1]; + + /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 3.29(q29) format */ + out = ((q31_t) (((q63_t) x1 * (0x7FFFFFFF - xfract)) >> 32)); + acc = ((q31_t) (((q63_t) out * (0x7FFFFFFF - yfract)) >> 32)); + + /* x2 * (xfract) * (1-yfract) in 3.29(q29) and adding to acc */ + out = ((q31_t) ((q63_t) x2 * (0x7FFFFFFF - yfract) >> 32)); + acc += ((q31_t) ((q63_t) out * (xfract) >> 32)); + + /* y1 * (1 - xfract) * (yfract) in 3.29(q29) and adding to acc */ + out = ((q31_t) ((q63_t) y1 * (0x7FFFFFFF - xfract) >> 32)); + acc += ((q31_t) ((q63_t) out * (yfract) >> 32)); + + /* y2 * (xfract) * (yfract) in 3.29(q29) and adding to acc */ + out = ((q31_t) ((q63_t) y2 * (xfract) >> 32)); + acc += ((q31_t) ((q63_t) out * (yfract) >> 32)); + + /* Convert acc to 1.31(q31) format */ + return ((q31_t)(acc << 2)); + } + + + /** + * @brief Q15 bilinear interpolation. + * @param[in,out] S points to an instance of the interpolation structure. + * @param[in] X interpolation coordinate in 12.20 format. + * @param[in] Y interpolation coordinate in 12.20 format. + * @return out interpolated value. + */ + CMSIS_INLINE __STATIC_INLINE q15_t arm_bilinear_interp_q15( + arm_bilinear_interp_instance_q15 * S, + q31_t X, + q31_t Y) + { + q63_t acc = 0; /* output */ + q31_t out; /* Temporary output */ + q15_t x1, x2, y1, y2; /* Nearest output values */ + q31_t xfract, yfract; /* X, Y fractional parts */ + int32_t rI, cI; /* Row and column indices */ + q15_t *pYData = S->pData; /* pointer to output table values */ + uint32_t nCols = S->numCols; /* num of rows */ + + /* Input is in 12.20 format */ + /* 12 bits for the table index */ + /* Index value calculation */ + rI = ((X & (q31_t)0xFFF00000) >> 20); + + /* Input is in 12.20 format */ + /* 12 bits for the table index */ + /* Index value calculation */ + cI = ((Y & (q31_t)0xFFF00000) >> 20); + + /* Care taken for table outside boundary */ + /* Returns zero output when values are outside table boundary */ + if (rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) + { + return (0); + } + + /* 20 bits for the fractional part */ + /* xfract should be in 12.20 format */ + xfract = (X & 0x000FFFFF); + + /* Read two nearest output values from the index */ + x1 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI) ]; + x2 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI) + 1]; + + /* 20 bits for the fractional part */ + /* yfract should be in 12.20 format */ + yfract = (Y & 0x000FFFFF); + + /* Read two nearest output values from the index */ + y1 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI + 1) ]; + y2 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI + 1) + 1]; + + /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 13.51 format */ + + /* x1 is in 1.15(q15), xfract in 12.20 format and out is in 13.35 format */ + /* convert 13.35 to 13.31 by right shifting and out is in 1.31 */ + out = (q31_t) (((q63_t) x1 * (0xFFFFF - xfract)) >> 4U); + acc = ((q63_t) out * (0xFFFFF - yfract)); + + /* x2 * (xfract) * (1-yfract) in 1.51 and adding to acc */ + out = (q31_t) (((q63_t) x2 * (0xFFFFF - yfract)) >> 4U); + acc += ((q63_t) out * (xfract)); + + /* y1 * (1 - xfract) * (yfract) in 1.51 and adding to acc */ + out = (q31_t) (((q63_t) y1 * (0xFFFFF - xfract)) >> 4U); + acc += ((q63_t) out * (yfract)); + + /* y2 * (xfract) * (yfract) in 1.51 and adding to acc */ + out = (q31_t) (((q63_t) y2 * (xfract)) >> 4U); + acc += ((q63_t) out * (yfract)); + + /* acc is in 13.51 format and down shift acc by 36 times */ + /* Convert out to 1.15 format */ + return ((q15_t)(acc >> 36)); + } + + + /** + * @brief Q7 bilinear interpolation. + * @param[in,out] S points to an instance of the interpolation structure. + * @param[in] X interpolation coordinate in 12.20 format. + * @param[in] Y interpolation coordinate in 12.20 format. + * @return out interpolated value. + */ + CMSIS_INLINE __STATIC_INLINE q7_t arm_bilinear_interp_q7( + arm_bilinear_interp_instance_q7 * S, + q31_t X, + q31_t Y) + { + q63_t acc = 0; /* output */ + q31_t out; /* Temporary output */ + q31_t xfract, yfract; /* X, Y fractional parts */ + q7_t x1, x2, y1, y2; /* Nearest output values */ + int32_t rI, cI; /* Row and column indices */ + q7_t *pYData = S->pData; /* pointer to output table values */ + uint32_t nCols = S->numCols; /* num of rows */ + + /* Input is in 12.20 format */ + /* 12 bits for the table index */ + /* Index value calculation */ + rI = ((X & (q31_t)0xFFF00000) >> 20); + + /* Input is in 12.20 format */ + /* 12 bits for the table index */ + /* Index value calculation */ + cI = ((Y & (q31_t)0xFFF00000) >> 20); + + /* Care taken for table outside boundary */ + /* Returns zero output when values are outside table boundary */ + if (rI < 0 || rI > (S->numRows - 1) || cI < 0 || cI > (S->numCols - 1)) + { + return (0); + } + + /* 20 bits for the fractional part */ + /* xfract should be in 12.20 format */ + xfract = (X & (q31_t)0x000FFFFF); + + /* Read two nearest output values from the index */ + x1 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI) ]; + x2 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI) + 1]; + + /* 20 bits for the fractional part */ + /* yfract should be in 12.20 format */ + yfract = (Y & (q31_t)0x000FFFFF); + + /* Read two nearest output values from the index */ + y1 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI + 1) ]; + y2 = pYData[((uint32_t)rI) + nCols * ((uint32_t)cI + 1) + 1]; + + /* Calculation of x1 * (1-xfract ) * (1-yfract) and acc is in 16.47 format */ + out = ((x1 * (0xFFFFF - xfract))); + acc = (((q63_t) out * (0xFFFFF - yfract))); + + /* x2 * (xfract) * (1-yfract) in 2.22 and adding to acc */ + out = ((x2 * (0xFFFFF - yfract))); + acc += (((q63_t) out * (xfract))); + + /* y1 * (1 - xfract) * (yfract) in 2.22 and adding to acc */ + out = ((y1 * (0xFFFFF - xfract))); + acc += (((q63_t) out * (yfract))); + + /* y2 * (xfract) * (yfract) in 2.22 and adding to acc */ + out = ((y2 * (yfract))); + acc += (((q63_t) out * (xfract))); + + /* acc in 16.47 format and down shift by 40 to convert to 1.7 format */ + return ((q7_t)(acc >> 40)); + } + + /** + * @} end of BilinearInterpolate group + */ + + +/* SMMLAR */ +#define multAcc_32x32_keep32_R(a, x, y) \ + a = (q31_t) (((((q63_t) a) << 32) + ((q63_t) x * y) + 0x80000000LL ) >> 32) + +/* SMMLSR */ +#define multSub_32x32_keep32_R(a, x, y) \ + a = (q31_t) (((((q63_t) a) << 32) - ((q63_t) x * y) + 0x80000000LL ) >> 32) + +/* SMMULR */ +#define mult_32x32_keep32_R(a, x, y) \ + a = (q31_t) (((q63_t) x * y + 0x80000000LL ) >> 32) + +/* SMMLA */ +#define multAcc_32x32_keep32(a, x, y) \ + a += (q31_t) (((q63_t) x * y) >> 32) + +/* SMMLS */ +#define multSub_32x32_keep32(a, x, y) \ + a -= (q31_t) (((q63_t) x * y) >> 32) + +/* SMMUL */ +#define mult_32x32_keep32(a, x, y) \ + a = (q31_t) (((q63_t) x * y ) >> 32) + + +#if defined ( __CC_ARM ) + /* Enter low optimization region - place directly above function definition */ + #if defined( ARM_MATH_CM4 ) || defined( ARM_MATH_CM7) + #define LOW_OPTIMIZATION_ENTER \ + _Pragma ("push") \ + _Pragma ("O1") + #else + #define LOW_OPTIMIZATION_ENTER + #endif + + /* Exit low optimization region - place directly after end of function definition */ + #if defined ( ARM_MATH_CM4 ) || defined ( ARM_MATH_CM7 ) + #define LOW_OPTIMIZATION_EXIT \ + _Pragma ("pop") + #else + #define LOW_OPTIMIZATION_EXIT + #endif + + /* Enter low optimization region - place directly above function definition */ + #define IAR_ONLY_LOW_OPTIMIZATION_ENTER + + /* Exit low optimization region - place directly after end of function definition */ + #define IAR_ONLY_LOW_OPTIMIZATION_EXIT + +#elif defined (__ARMCC_VERSION ) && ( __ARMCC_VERSION >= 6010050 ) + #define LOW_OPTIMIZATION_ENTER + #define LOW_OPTIMIZATION_EXIT + #define IAR_ONLY_LOW_OPTIMIZATION_ENTER + #define IAR_ONLY_LOW_OPTIMIZATION_EXIT + +#elif defined ( __GNUC__ ) + #define LOW_OPTIMIZATION_ENTER \ + __attribute__(( optimize("-O1") )) + #define LOW_OPTIMIZATION_EXIT + #define IAR_ONLY_LOW_OPTIMIZATION_ENTER + #define IAR_ONLY_LOW_OPTIMIZATION_EXIT + +#elif defined ( __ICCARM__ ) + /* Enter low optimization region - place directly above function definition */ + #if defined ( ARM_MATH_CM4 ) || defined ( ARM_MATH_CM7 ) + #define LOW_OPTIMIZATION_ENTER \ + _Pragma ("optimize=low") + #else + #define LOW_OPTIMIZATION_ENTER + #endif + + /* Exit low optimization region - place directly after end of function definition */ + #define LOW_OPTIMIZATION_EXIT + + /* Enter low optimization region - place directly above function definition */ + #if defined ( ARM_MATH_CM4 ) || defined ( ARM_MATH_CM7 ) + #define IAR_ONLY_LOW_OPTIMIZATION_ENTER \ + _Pragma ("optimize=low") + #else + #define IAR_ONLY_LOW_OPTIMIZATION_ENTER + #endif + + /* Exit low optimization region - place directly after end of function definition */ + #define IAR_ONLY_LOW_OPTIMIZATION_EXIT + +#elif defined ( __TI_ARM__ ) + #define LOW_OPTIMIZATION_ENTER + #define LOW_OPTIMIZATION_EXIT + #define IAR_ONLY_LOW_OPTIMIZATION_ENTER + #define IAR_ONLY_LOW_OPTIMIZATION_EXIT + +#elif defined ( __CSMC__ ) + #define LOW_OPTIMIZATION_ENTER + #define LOW_OPTIMIZATION_EXIT + #define IAR_ONLY_LOW_OPTIMIZATION_ENTER + #define IAR_ONLY_LOW_OPTIMIZATION_EXIT + +#elif defined ( __TASKING__ ) + #define LOW_OPTIMIZATION_ENTER + #define LOW_OPTIMIZATION_EXIT + #define IAR_ONLY_LOW_OPTIMIZATION_ENTER + #define IAR_ONLY_LOW_OPTIMIZATION_EXIT + +#endif + + +#ifdef __cplusplus +} +#endif + +/* Compiler specific diagnostic adjustment */ +#if defined ( __CC_ARM ) + +#elif defined ( __ARMCC_VERSION ) && ( __ARMCC_VERSION >= 6010050 ) + +#elif defined ( __GNUC__ ) +#pragma GCC diagnostic pop + +#elif defined ( __ICCARM__ ) + +#elif defined ( __TI_ARM__ ) + +#elif defined ( __CSMC__ ) + +#elif defined ( __TASKING__ ) + +#else + #error Unknown compiler +#endif + +#endif /* _ARM_MATH_H */ + +/** + * + * End of file. + */ diff --git a/Middlewares/ST/ARM/DSP/Include/arm_common_tables.h b/Middlewares/ST/ARM/DSP/Include/arm_common_tables.h new file mode 100644 index 0000000..3e72c80 --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/arm_common_tables.h @@ -0,0 +1,539 @@ +/* ---------------------------------------------------------------------- + * Project: CMSIS DSP Library + * Title: arm_common_tables.h + * Description: Extern declaration for common tables + * + * @version V1.10.0 + * @date 08 July 2021 + * + * Target Processor: Cortex-M and Cortex-A cores + * -------------------------------------------------------------------- */ +/* + * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ARM_COMMON_TABLES_H +#define _ARM_COMMON_TABLES_H + +#include "arm_math_types.h" +#include "dsp/fast_math_functions.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_FFT_ALLOW_TABLES) + /* Double Precision Float CFFT twiddles */ + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREV_1024) + extern const uint16_t armBitRevTable[1024]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F64_16) + extern const uint64_t twiddleCoefF64_16[32]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F64_32) + extern const uint64_t twiddleCoefF64_32[64]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F64_64) + extern const uint64_t twiddleCoefF64_64[128]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F64_128) + extern const uint64_t twiddleCoefF64_128[256]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F64_256) + extern const uint64_t twiddleCoefF64_256[512]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F64_512) + extern const uint64_t twiddleCoefF64_512[1024]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F64_1024) + extern const uint64_t twiddleCoefF64_1024[2048]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F64_2048) + extern const uint64_t twiddleCoefF64_2048[4096]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F64_4096) + extern const uint64_t twiddleCoefF64_4096[8192]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F32_16) + extern const float32_t twiddleCoef_16[32]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F32_32) + extern const float32_t twiddleCoef_32[64]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F32_64) + extern const float32_t twiddleCoef_64[128]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F32_128) + extern const float32_t twiddleCoef_128[256]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F32_256) + extern const float32_t twiddleCoef_256[512]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F32_512) + extern const float32_t twiddleCoef_512[1024]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F32_1024) + extern const float32_t twiddleCoef_1024[2048]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F32_2048) + extern const float32_t twiddleCoef_2048[4096]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F32_4096) + extern const float32_t twiddleCoef_4096[8192]; + #define twiddleCoef twiddleCoef_4096 + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + /* Q31 */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q31_16) + extern const q31_t twiddleCoef_16_q31[24]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q31_32) + extern const q31_t twiddleCoef_32_q31[48]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q31_64) + extern const q31_t twiddleCoef_64_q31[96]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q31_128) + extern const q31_t twiddleCoef_128_q31[192]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q31_256) + extern const q31_t twiddleCoef_256_q31[384]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q31_512) + extern const q31_t twiddleCoef_512_q31[768]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q31_1024) + extern const q31_t twiddleCoef_1024_q31[1536]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q31_2048) + extern const q31_t twiddleCoef_2048_q31[3072]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q31_4096) + extern const q31_t twiddleCoef_4096_q31[6144]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q15_16) + extern const q15_t twiddleCoef_16_q15[24]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q15_32) + extern const q15_t twiddleCoef_32_q15[48]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q15_64) + extern const q15_t twiddleCoef_64_q15[96]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q15_128) + extern const q15_t twiddleCoef_128_q15[192]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q15_256) + extern const q15_t twiddleCoef_256_q15[384]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q15_512) + extern const q15_t twiddleCoef_512_q15[768]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q15_1024) + extern const q15_t twiddleCoef_1024_q15[1536]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q15_2048) + extern const q15_t twiddleCoef_2048_q15[3072]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_Q15_4096) + extern const q15_t twiddleCoef_4096_q15[6144]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + /* Double Precision Float RFFT twiddles */ + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F64_32) + extern const uint64_t twiddleCoefF64_rfft_32[32]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F64_64) + extern const uint64_t twiddleCoefF64_rfft_64[64]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F64_128) + extern const uint64_t twiddleCoefF64_rfft_128[128]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F64_256) + extern const uint64_t twiddleCoefF64_rfft_256[256]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F64_512) + extern const uint64_t twiddleCoefF64_rfft_512[512]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F64_1024) + extern const uint64_t twiddleCoefF64_rfft_1024[1024]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F64_2048) + extern const uint64_t twiddleCoefF64_rfft_2048[2048]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F64_4096) + extern const uint64_t twiddleCoefF64_rfft_4096[4096]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F32_32) + extern const float32_t twiddleCoef_rfft_32[32]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F32_64) + extern const float32_t twiddleCoef_rfft_64[64]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F32_128) + extern const float32_t twiddleCoef_rfft_128[128]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F32_256) + extern const float32_t twiddleCoef_rfft_256[256]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F32_512) + extern const float32_t twiddleCoef_rfft_512[512]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F32_1024) + extern const float32_t twiddleCoef_rfft_1024[1024]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F32_2048) + extern const float32_t twiddleCoef_rfft_2048[2048]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F32_4096) + extern const float32_t twiddleCoef_rfft_4096[4096]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + + /* Double precision floating-point bit reversal tables */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT64_16) + #define ARMBITREVINDEXTABLEF64_16_TABLE_LENGTH ((uint16_t)12) + extern const uint16_t armBitRevIndexTableF64_16[ARMBITREVINDEXTABLEF64_16_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT64_32) + #define ARMBITREVINDEXTABLEF64_32_TABLE_LENGTH ((uint16_t)24) + extern const uint16_t armBitRevIndexTableF64_32[ARMBITREVINDEXTABLEF64_32_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT64_64) + #define ARMBITREVINDEXTABLEF64_64_TABLE_LENGTH ((uint16_t)56) + extern const uint16_t armBitRevIndexTableF64_64[ARMBITREVINDEXTABLEF64_64_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT64_128) + #define ARMBITREVINDEXTABLEF64_128_TABLE_LENGTH ((uint16_t)112) + extern const uint16_t armBitRevIndexTableF64_128[ARMBITREVINDEXTABLEF64_128_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT64_256) + #define ARMBITREVINDEXTABLEF64_256_TABLE_LENGTH ((uint16_t)240) + extern const uint16_t armBitRevIndexTableF64_256[ARMBITREVINDEXTABLEF64_256_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT64_512) + #define ARMBITREVINDEXTABLEF64_512_TABLE_LENGTH ((uint16_t)480) + extern const uint16_t armBitRevIndexTableF64_512[ARMBITREVINDEXTABLEF64_512_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT64_1024) + #define ARMBITREVINDEXTABLEF64_1024_TABLE_LENGTH ((uint16_t)992) + extern const uint16_t armBitRevIndexTableF64_1024[ARMBITREVINDEXTABLEF64_1024_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT64_2048) + #define ARMBITREVINDEXTABLEF64_2048_TABLE_LENGTH ((uint16_t)1984) + extern const uint16_t armBitRevIndexTableF64_2048[ARMBITREVINDEXTABLEF64_2048_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT64_4096) + #define ARMBITREVINDEXTABLEF64_4096_TABLE_LENGTH ((uint16_t)4032) + extern const uint16_t armBitRevIndexTableF64_4096[ARMBITREVINDEXTABLEF64_4096_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + /* floating-point bit reversal tables */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT_16) + #define ARMBITREVINDEXTABLE_16_TABLE_LENGTH ((uint16_t)20) + extern const uint16_t armBitRevIndexTable16[ARMBITREVINDEXTABLE_16_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT_32) + #define ARMBITREVINDEXTABLE_32_TABLE_LENGTH ((uint16_t)48) + extern const uint16_t armBitRevIndexTable32[ARMBITREVINDEXTABLE_32_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT_64) + #define ARMBITREVINDEXTABLE_64_TABLE_LENGTH ((uint16_t)56) + extern const uint16_t armBitRevIndexTable64[ARMBITREVINDEXTABLE_64_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT_128) + #define ARMBITREVINDEXTABLE_128_TABLE_LENGTH ((uint16_t)208) + extern const uint16_t armBitRevIndexTable128[ARMBITREVINDEXTABLE_128_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT_256) + #define ARMBITREVINDEXTABLE_256_TABLE_LENGTH ((uint16_t)440) + extern const uint16_t armBitRevIndexTable256[ARMBITREVINDEXTABLE_256_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT_512) + #define ARMBITREVINDEXTABLE_512_TABLE_LENGTH ((uint16_t)448) + extern const uint16_t armBitRevIndexTable512[ARMBITREVINDEXTABLE_512_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT_1024) + #define ARMBITREVINDEXTABLE_1024_TABLE_LENGTH ((uint16_t)1800) + extern const uint16_t armBitRevIndexTable1024[ARMBITREVINDEXTABLE_1024_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT_2048) + #define ARMBITREVINDEXTABLE_2048_TABLE_LENGTH ((uint16_t)3808) + extern const uint16_t armBitRevIndexTable2048[ARMBITREVINDEXTABLE_2048_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FLT_4096) + #define ARMBITREVINDEXTABLE_4096_TABLE_LENGTH ((uint16_t)4032) + extern const uint16_t armBitRevIndexTable4096[ARMBITREVINDEXTABLE_4096_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + + /* fixed-point bit reversal tables */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FXT_16) + #define ARMBITREVINDEXTABLE_FIXED_16_TABLE_LENGTH ((uint16_t)12) + extern const uint16_t armBitRevIndexTable_fixed_16[ARMBITREVINDEXTABLE_FIXED_16_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FXT_32) + #define ARMBITREVINDEXTABLE_FIXED_32_TABLE_LENGTH ((uint16_t)24) + extern const uint16_t armBitRevIndexTable_fixed_32[ARMBITREVINDEXTABLE_FIXED_32_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FXT_64) + #define ARMBITREVINDEXTABLE_FIXED_64_TABLE_LENGTH ((uint16_t)56) + extern const uint16_t armBitRevIndexTable_fixed_64[ARMBITREVINDEXTABLE_FIXED_64_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FXT_128) + #define ARMBITREVINDEXTABLE_FIXED_128_TABLE_LENGTH ((uint16_t)112) + extern const uint16_t armBitRevIndexTable_fixed_128[ARMBITREVINDEXTABLE_FIXED_128_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FXT_256) + #define ARMBITREVINDEXTABLE_FIXED_256_TABLE_LENGTH ((uint16_t)240) + extern const uint16_t armBitRevIndexTable_fixed_256[ARMBITREVINDEXTABLE_FIXED_256_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FXT_512) + #define ARMBITREVINDEXTABLE_FIXED_512_TABLE_LENGTH ((uint16_t)480) + extern const uint16_t armBitRevIndexTable_fixed_512[ARMBITREVINDEXTABLE_FIXED_512_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FXT_1024) + #define ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH ((uint16_t)992) + extern const uint16_t armBitRevIndexTable_fixed_1024[ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FXT_2048) + #define ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH ((uint16_t)1984) + extern const uint16_t armBitRevIndexTable_fixed_2048[ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_BITREVIDX_FXT_4096) + #define ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH ((uint16_t)4032) + extern const uint16_t armBitRevIndexTable_fixed_4096[ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_REALCOEF_F32) + extern const float32_t realCoefA[8192]; + extern const float32_t realCoefB[8192]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_REALCOEF_Q31) + extern const q31_t realCoefAQ31[8192]; + extern const q31_t realCoefBQ31[8192]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_REALCOEF_Q15) + extern const q15_t realCoefAQ15[8192]; + extern const q15_t realCoefBQ15[8192]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_F32_128) + extern const float32_t Weights_128[256]; + extern const float32_t cos_factors_128[128]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_F32_512) + extern const float32_t Weights_512[1024]; + extern const float32_t cos_factors_512[512]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_F32_2048) + extern const float32_t Weights_2048[4096]; + extern const float32_t cos_factors_2048[2048]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_F32_8192) + extern const float32_t Weights_8192[16384]; + extern const float32_t cos_factors_8192[8192]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_Q15_128) + extern const q15_t WeightsQ15_128[256]; + extern const q15_t cos_factorsQ15_128[128]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_Q15_512) + extern const q15_t WeightsQ15_512[1024]; + extern const q15_t cos_factorsQ15_512[512]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_Q15_2048) + extern const q15_t WeightsQ15_2048[4096]; + extern const q15_t cos_factorsQ15_2048[2048]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_Q15_8192) + extern const q15_t WeightsQ15_8192[16384]; + extern const q15_t cos_factorsQ15_8192[8192]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_Q31_128) + extern const q31_t WeightsQ31_128[256]; + extern const q31_t cos_factorsQ31_128[128]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_Q31_512) + extern const q31_t WeightsQ31_512[1024]; + extern const q31_t cos_factorsQ31_512[512]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_Q31_2048) + extern const q31_t WeightsQ31_2048[4096]; + extern const q31_t cos_factorsQ31_2048[2048]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_DCT4_Q31_8192) + extern const q31_t WeightsQ31_8192[16384]; + extern const q31_t cos_factorsQ31_8192[8192]; + #endif + +#endif /* if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_FFT_TABLES) */ + +#if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_FAST_ALLOW_TABLES) + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_RECIP_Q15) + extern const q15_t armRecipTableQ15[64]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) defined(ARM_ALL_FAST_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_RECIP_Q31) + extern const q31_t armRecipTableQ31[64]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) defined(ARM_ALL_FAST_TABLES) */ + + /* Tables for Fast Math Sine and Cosine */ + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_SIN_F32) + extern const float32_t sinTable_f32[FAST_MATH_TABLE_SIZE + 1]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) defined(ARM_ALL_FAST_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_SIN_Q31) + extern const q31_t sinTable_q31[FAST_MATH_TABLE_SIZE + 1]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) defined(ARM_ALL_FAST_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_SIN_Q15) + extern const q15_t sinTable_q15[FAST_MATH_TABLE_SIZE + 1]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) defined(ARM_ALL_FAST_TABLES) */ + + /* Fast vector sqrt */ + #if defined(ARM_MATH_MVEI) && !defined(ARM_MATH_AUTOVECTORIZE) + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_FAST_SQRT_Q31_MVE) + extern const q31_t sqrtTable_Q31[256]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) defined(ARM_ALL_FAST_TABLES) */ + #endif + + /* Accurate scalar sqrt */ + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_SQRT_Q31) + extern const q31_t sqrt_initial_lut_q31[32]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_SQRT_Q15) + extern const q15_t sqrt_initial_lut_q15[16]; + #endif + + #if defined(ARM_MATH_MVEI) && !defined(ARM_MATH_AUTOVECTORIZE) + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_FAST_SQRT_Q15_MVE) + extern const q15_t sqrtTable_Q15[256]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) defined(ARM_ALL_FAST_TABLES) */ + #endif + +#endif /* if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_FAST_TABLES) */ + +#if (defined(ARM_MATH_MVEF) || defined(ARM_MATH_HELIUM)) && !defined(ARM_MATH_AUTOVECTORIZE) + extern const float32_t exp_tab[8]; + extern const float32_t __logf_lut_f32[8]; +#endif /* (defined(ARM_MATH_MVEF) || defined(ARM_MATH_HELIUM)) && !defined(ARM_MATH_AUTOVECTORIZE) */ + +#if (defined(ARM_MATH_MVEI) || defined(ARM_MATH_HELIUM)) && !defined(ARM_MATH_AUTOVECTORIZE) +extern const unsigned char hwLUT[256]; +#endif /* (defined(ARM_MATH_MVEI) || defined(ARM_MATH_HELIUM)) */ + +#ifdef __cplusplus +} +#endif + +#endif /* ARM_COMMON_TABLES_H */ + diff --git a/Middlewares/ST/ARM/DSP/Include/arm_common_tables_f16.h b/Middlewares/ST/ARM/DSP/Include/arm_common_tables_f16.h new file mode 100644 index 0000000..f9a63fe --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/arm_common_tables_f16.h @@ -0,0 +1,132 @@ +/* ---------------------------------------------------------------------- + * Project: CMSIS DSP Library + * Title: arm_common_tables_f16.h + * Description: Extern declaration for common tables + * + * @version V1.10.0 + * @date 08 July 2021 + * + * Target Processor: Cortex-M and Cortex-A cores + * -------------------------------------------------------------------- */ +/* + * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ARM_COMMON_TABLES_F16_H +#define _ARM_COMMON_TABLES_F16_H + +#include "arm_math_types_f16.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_FFT_ALLOW_TABLES) + + /* F16 */ + #if !defined(__CC_ARM) && defined(ARM_FLOAT16_SUPPORTED) + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F16_16) + extern const float16_t twiddleCoefF16_16[32]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F16_32) + extern const float16_t twiddleCoefF16_32[64]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F16_64) + extern const float16_t twiddleCoefF16_64[128]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F16_128) + extern const float16_t twiddleCoefF16_128[256]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F16_256) + extern const float16_t twiddleCoefF16_256[512]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F16_512) + extern const float16_t twiddleCoefF16_512[1024]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F16_1024) + extern const float16_t twiddleCoefF16_1024[2048]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F16_2048) + extern const float16_t twiddleCoefF16_2048[4096]; + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_F16_4096) + extern const float16_t twiddleCoefF16_4096[8192]; + #define twiddleCoefF16 twiddleCoefF16_4096 + #endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) */ + + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F16_32) + extern const float16_t twiddleCoefF16_rfft_32[32]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F16_64) + extern const float16_t twiddleCoefF16_rfft_64[64]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F16_128) + extern const float16_t twiddleCoefF16_rfft_128[128]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F16_256) + extern const float16_t twiddleCoefF16_rfft_256[256]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F16_512) + extern const float16_t twiddleCoefF16_rfft_512[512]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F16_1024) + extern const float16_t twiddleCoefF16_rfft_1024[1024]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F16_2048) + extern const float16_t twiddleCoefF16_rfft_2048[2048]; + #endif + + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || defined(ARM_TABLE_TWIDDLECOEF_RFFT_F16_4096) + extern const float16_t twiddleCoefF16_rfft_4096[4096]; + #endif + + #endif /* ARMAC5 */ + +#endif /* !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_FFT_ALLOW_TABLES) */ + +#if !defined(__CC_ARM) && defined(ARM_FLOAT16_SUPPORTED) + +#if (defined(ARM_MATH_MVEF) || defined(ARM_MATH_HELIUM)) && !defined(ARM_MATH_AUTOVECTORIZE) + extern const float16_t exp_tab_f16[8]; + extern const float16_t __logf_lut_f16[8]; +#endif /* (defined(ARM_MATH_MVEF) || defined(ARM_MATH_HELIUM)) && !defined(ARM_MATH_AUTOVECTORIZE) */ +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* _ARM_COMMON_TABLES_F16_H */ + + diff --git a/Middlewares/ST/ARM/DSP/Include/arm_const_structs.h b/Middlewares/ST/ARM/DSP/Include/arm_const_structs.h new file mode 100644 index 0000000..59026db --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/arm_const_structs.h @@ -0,0 +1,86 @@ +/* ---------------------------------------------------------------------- + * Project: CMSIS DSP Library + * Title: arm_const_structs.h + * Description: Constant structs that are initialized for user convenience. + * For example, some can be given as arguments to the arm_cfft_f32() function. + * + * @version V1.10.0 + * @date 08 July 2021 + * + * Target Processor: Cortex-M and Cortex-A cores + * -------------------------------------------------------------------- */ +/* + * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ARM_CONST_STRUCTS_H +#define _ARM_CONST_STRUCTS_H + +#include "arm_math_types.h" +#include "arm_common_tables.h" +#include "dsp/transform_functions.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + extern const arm_cfft_instance_f64 arm_cfft_sR_f64_len16; + extern const arm_cfft_instance_f64 arm_cfft_sR_f64_len32; + extern const arm_cfft_instance_f64 arm_cfft_sR_f64_len64; + extern const arm_cfft_instance_f64 arm_cfft_sR_f64_len128; + extern const arm_cfft_instance_f64 arm_cfft_sR_f64_len256; + extern const arm_cfft_instance_f64 arm_cfft_sR_f64_len512; + extern const arm_cfft_instance_f64 arm_cfft_sR_f64_len1024; + extern const arm_cfft_instance_f64 arm_cfft_sR_f64_len2048; + extern const arm_cfft_instance_f64 arm_cfft_sR_f64_len4096; + + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len16; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len32; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len64; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len128; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len256; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len512; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len1024; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len2048; + extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len4096; + + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len16; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len32; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len64; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len128; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len256; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len512; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len1024; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len2048; + extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len4096; + + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len16; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len32; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len64; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len128; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len256; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len512; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len1024; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len2048; + extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len4096; + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/Middlewares/ST/ARM/DSP/Include/arm_const_structs_f16.h b/Middlewares/ST/ARM/DSP/Include/arm_const_structs_f16.h new file mode 100644 index 0000000..0984d74 --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/arm_const_structs_f16.h @@ -0,0 +1,77 @@ +/* ---------------------------------------------------------------------- + * Project: CMSIS DSP Library + * Title: arm_const_structs_f16.h + * Description: Constant structs that are initialized for user convenience. + * For example, some can be given as arguments to the arm_cfft_f16() function. + * + * @version V1.10.0 + * @date 08 July 2021 + * + * Target Processor: Cortex-M and Cortex-A cores + * -------------------------------------------------------------------- */ +/* + * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ARM_CONST_STRUCTS_F16_H +#define _ARM_CONST_STRUCTS_F16_H + +#include "arm_math_types_f16.h" +#include "arm_common_tables.h" +#include "arm_common_tables_f16.h" +#include "dsp/transform_functions_f16.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__CC_ARM) && defined(ARM_FLOAT16_SUPPORTED) + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || (defined(ARM_TABLE_TWIDDLECOEF_F16_16) && defined(ARM_TABLE_BITREVIDX_FLT_16)) + extern const arm_cfft_instance_f16 arm_cfft_sR_f16_len16; + #endif + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || (defined(ARM_TABLE_TWIDDLECOEF_F16_32) && defined(ARM_TABLE_BITREVIDX_FLT_32)) + extern const arm_cfft_instance_f16 arm_cfft_sR_f16_len32; + #endif + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || (defined(ARM_TABLE_TWIDDLECOEF_F16_64) && defined(ARM_TABLE_BITREVIDX_FLT_64)) + extern const arm_cfft_instance_f16 arm_cfft_sR_f16_len64; + #endif + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || (defined(ARM_TABLE_TWIDDLECOEF_F16_128) && defined(ARM_TABLE_BITREVIDX_FLT_128)) + extern const arm_cfft_instance_f16 arm_cfft_sR_f16_len128; + #endif + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || (defined(ARM_TABLE_TWIDDLECOEF_F16_256) && defined(ARM_TABLE_BITREVIDX_FLT_256)) + extern const arm_cfft_instance_f16 arm_cfft_sR_f16_len256; + #endif + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || (defined(ARM_TABLE_TWIDDLECOEF_F16_512) && defined(ARM_TABLE_BITREVIDX_FLT_512)) + extern const arm_cfft_instance_f16 arm_cfft_sR_f16_len512; + #endif + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || (defined(ARM_TABLE_TWIDDLECOEF_F16_1024) && defined(ARM_TABLE_BITREVIDX_FLT_1024)) + extern const arm_cfft_instance_f16 arm_cfft_sR_f16_len1024; + #endif + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || (defined(ARM_TABLE_TWIDDLECOEF_F16_2048) && defined(ARM_TABLE_BITREVIDX_FLT_2048)) + extern const arm_cfft_instance_f16 arm_cfft_sR_f16_len2048; + #endif + #if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FFT_TABLES) || (defined(ARM_TABLE_TWIDDLECOEF_F16_4096) && defined(ARM_TABLE_BITREVIDX_FLT_4096)) + extern const arm_cfft_instance_f16 arm_cfft_sR_f16_len4096; + #endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Middlewares/ST/ARM/DSP/Include/arm_helium_utils.h b/Middlewares/ST/ARM/DSP/Include/arm_helium_utils.h new file mode 100644 index 0000000..ae9037c --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/arm_helium_utils.h @@ -0,0 +1,753 @@ +/* ---------------------------------------------------------------------- + * Project: CMSIS DSP Library + * Title: arm_helium_utils.h + * Description: Utility functions for Helium development + * + * @version V1.10.0 + * @date 08 July 2021 + * + * Target Processor: Cortex-M and Cortex-A cores + * -------------------------------------------------------------------- */ +/* + * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ARM_UTILS_HELIUM_H_ +#define _ARM_UTILS_HELIUM_H_ + + +#ifdef __cplusplus +extern "C" +{ +#endif +/*************************************** + +Definitions available for MVEF and MVEI + +***************************************/ +#if (defined (ARM_MATH_HELIUM) || defined(ARM_MATH_MVEF) || defined(ARM_MATH_MVEI)) && !defined(ARM_MATH_AUTOVECTORIZE) + +#define INACTIVELANE 0 /* inactive lane content */ + + +#endif /* defined (ARM_MATH_HELIUM) || defined(ARM_MATH_MVEF) || defined(ARM_MATH_MVEI) */ + +/*************************************** + +Definitions available for MVEF only + +***************************************/ +#if (defined (ARM_MATH_HELIUM) || defined(ARM_MATH_MVEF)) && !defined(ARM_MATH_AUTOVECTORIZE) + +__STATIC_FORCEINLINE float32_t vecAddAcrossF32Mve(float32x4_t in) +{ + float32_t acc; + + acc = vgetq_lane(in, 0) + vgetq_lane(in, 1) + + vgetq_lane(in, 2) + vgetq_lane(in, 3); + + return acc; +} + + + + +/* newton initial guess */ +#define INVSQRT_MAGIC_F32 0x5f3759df +#define INV_NEWTON_INIT_F32 0x7EF127EA + + +#define INVSQRT_NEWTON_MVE_F32(invSqrt, xHalf, xStart)\ +{ \ + float32x4_t tmp; \ + \ + /* tmp = xhalf * x * x */ \ + tmp = vmulq(xStart, xStart); \ + tmp = vmulq(tmp, xHalf); \ + /* (1.5f - xhalf * x * x) */ \ + tmp = vsubq(vdupq_n_f32(1.5f), tmp); \ + /* x = x*(1.5f-xhalf*x*x); */ \ + invSqrt = vmulq(tmp, xStart); \ +} +#endif /* defined (ARM_MATH_HELIUM) || defined(ARM_MATH_MVEF) */ + + +/*************************************** + +Definitions available for f16 datatype with HW acceleration only + +***************************************/ +#if defined(ARM_FLOAT16_SUPPORTED) +#if defined (ARM_MATH_MVE_FLOAT16) && !defined(ARM_MATH_AUTOVECTORIZE) + +__STATIC_FORCEINLINE float16_t vecAddAcrossF16Mve(float16x8_t in) +{ + float16x8_t tmpVec; + _Float16 acc; + + tmpVec = (float16x8_t) vrev32q_s16((int16x8_t) in); + in = vaddq_f16(tmpVec, in); + tmpVec = (float16x8_t) vrev64q_s32((int32x4_t) in); + in = vaddq_f16(tmpVec, in); + acc = (_Float16)vgetq_lane_f16(in, 0) + (_Float16)vgetq_lane_f16(in, 4); + + return acc; +} + +__STATIC_FORCEINLINE float16x8_t __mve_cmplx_sum_intra_vec_f16( + float16x8_t vecIn) +{ + float16x8_t vecTmp, vecOut; + uint32_t tmp; + + vecTmp = (float16x8_t) vrev64q_s32((int32x4_t) vecIn); + // TO TRACK : using canonical addition leads to unefficient code generation for f16 + // vecTmp = vecTmp + vecAccCpx0; + /* + * Compute + * re0+re1 | im0+im1 | re0+re1 | im0+im1 + * re2+re3 | im2+im3 | re2+re3 | im2+im3 + */ + vecTmp = vaddq_f16(vecTmp, vecIn); + vecOut = vecTmp; + /* + * shift left, random tmp insertion in bottom + */ + vecOut = vreinterpretq_f16_s32(vshlcq_s32(vreinterpretq_s32_f16(vecOut) , &tmp, 32)); + /* + * Compute: + * DONTCARE | DONTCARE | re0+re1+re0+re1 |im0+im1+im0+im1 + * re0+re1+re2+re3 | im0+im1+im2+im3 | re2+re3+re2+re3 |im2+im3+im2+im3 + */ + vecOut = vaddq_f16(vecOut, vecTmp); + /* + * Cmplx sum is in 4rd & 5th f16 elt + * return full vector + */ + return vecOut; +} + + +#define mve_cmplx_sum_intra_r_i_f16(vec, Re, Im) \ +{ \ + float16x8_t vecOut = __mve_cmplx_sum_intra_vec_f16(vec); \ + Re = vgetq_lane(vecOut, 4); \ + Im = vgetq_lane(vecOut, 5); \ +} + +__STATIC_FORCEINLINE void mve_cmplx_sum_intra_vec_f16( + float16x8_t vecIn, + float16_t *pOut) +{ + float16x8_t vecOut = __mve_cmplx_sum_intra_vec_f16(vecIn); + /* + * Cmplx sum is in 4rd & 5th f16 elt + * use 32-bit extraction + */ + *(float32_t *) pOut = ((float32x4_t) vecOut)[2]; +} + + +#define INVSQRT_MAGIC_F16 0x59ba /* ( 0x1ba = 0x3759df >> 13) */ + +/* canonical version of INVSQRT_NEWTON_MVE_F16 leads to bad performance */ +#define INVSQRT_NEWTON_MVE_F16(invSqrt, xHalf, xStart) \ +{ \ + float16x8_t tmp; \ + \ + /* tmp = xhalf * x * x */ \ + tmp = vmulq(xStart, xStart); \ + tmp = vmulq(tmp, xHalf); \ + /* (1.5f - xhalf * x * x) */ \ + tmp = vsubq(vdupq_n_f16((float16_t)1.5), tmp); \ + /* x = x*(1.5f-xhalf*x*x); */ \ + invSqrt = vmulq(tmp, xStart); \ +} + +#endif +#endif + +/*************************************** + +Definitions available for MVEI and MVEF only + +***************************************/ +#if (defined (ARM_MATH_HELIUM) || defined(ARM_MATH_MVEF) || defined(ARM_MATH_MVEI)) && !defined(ARM_MATH_AUTOVECTORIZE) +/* Following functions are used to transpose matrix in f32 and q31 cases */ +__STATIC_INLINE arm_status arm_mat_trans_32bit_2x2_mve( + uint32_t * pDataSrc, + uint32_t * pDataDest) +{ + static const uint32x4_t vecOffs = { 0, 2, 1, 3 }; + /* + * + * | 0 1 | => | 0 2 | + * | 2 3 | | 1 3 | + * + */ + uint32x4_t vecIn = vldrwq_u32((uint32_t const *)pDataSrc); + vstrwq_scatter_shifted_offset_u32(pDataDest, vecOffs, vecIn); + + return (ARM_MATH_SUCCESS); +} + +__STATIC_INLINE arm_status arm_mat_trans_32bit_3x3_mve( + uint32_t * pDataSrc, + uint32_t * pDataDest) +{ + const uint32x4_t vecOffs1 = { 0, 3, 6, 1}; + const uint32x4_t vecOffs2 = { 4, 7, 2, 5}; + /* + * + * | 0 1 2 | | 0 3 6 | 4 x 32 flattened version | 0 3 6 1 | + * | 3 4 5 | => | 1 4 7 | => | 4 7 2 5 | + * | 6 7 8 | | 2 5 8 | (row major) | 8 . . . | + * + */ + uint32x4_t vecIn1 = vldrwq_u32((uint32_t const *) pDataSrc); + uint32x4_t vecIn2 = vldrwq_u32((uint32_t const *) &pDataSrc[4]); + + vstrwq_scatter_shifted_offset_u32(pDataDest, vecOffs1, vecIn1); + vstrwq_scatter_shifted_offset_u32(pDataDest, vecOffs2, vecIn2); + + pDataDest[8] = pDataSrc[8]; + + return (ARM_MATH_SUCCESS); +} + +__STATIC_INLINE arm_status arm_mat_trans_32bit_4x4_mve(uint32_t * pDataSrc, uint32_t * pDataDest) +{ + /* + * 4x4 Matrix transposition + * is 4 x de-interleave operation + * + * 0 1 2 3 0 4 8 12 + * 4 5 6 7 1 5 9 13 + * 8 9 10 11 2 6 10 14 + * 12 13 14 15 3 7 11 15 + */ + + uint32x4x4_t vecIn; + + vecIn = vld4q((uint32_t const *) pDataSrc); + vstrwq(pDataDest, vecIn.val[0]); + pDataDest += 4; + vstrwq(pDataDest, vecIn.val[1]); + pDataDest += 4; + vstrwq(pDataDest, vecIn.val[2]); + pDataDest += 4; + vstrwq(pDataDest, vecIn.val[3]); + + return (ARM_MATH_SUCCESS); +} + + +__STATIC_INLINE arm_status arm_mat_trans_32bit_generic_mve( + uint16_t srcRows, + uint16_t srcCols, + uint32_t * pDataSrc, + uint32_t * pDataDest) +{ + uint32x4_t vecOffs; + uint32_t i; + uint32_t blkCnt; + uint32_t const *pDataC; + uint32_t *pDataDestR; + uint32x4_t vecIn; + + vecOffs = vidupq_u32((uint32_t)0, 1); + vecOffs = vecOffs * srcCols; + + i = srcCols; + do + { + pDataC = (uint32_t const *) pDataSrc; + pDataDestR = pDataDest; + + blkCnt = srcRows >> 2; + while (blkCnt > 0U) + { + vecIn = vldrwq_gather_shifted_offset_u32(pDataC, vecOffs); + vstrwq(pDataDestR, vecIn); + pDataDestR += 4; + pDataC = pDataC + srcCols * 4; + /* + * Decrement the blockSize loop counter + */ + blkCnt--; + } + + /* + * tail + */ + blkCnt = srcRows & 3; + if (blkCnt > 0U) + { + mve_pred16_t p0 = vctp32q(blkCnt); + vecIn = vldrwq_gather_shifted_offset_u32(pDataC, vecOffs); + vstrwq_p(pDataDestR, vecIn, p0); + } + + pDataSrc += 1; + pDataDest += srcRows; + } + while (--i); + + return (ARM_MATH_SUCCESS); +} + +__STATIC_INLINE arm_status arm_mat_cmplx_trans_32bit( + uint16_t srcRows, + uint16_t srcCols, + uint32_t *pDataSrc, + uint16_t dstRows, + uint16_t dstCols, + uint32_t *pDataDest) +{ + uint32_t i; + uint32_t const *pDataC; + uint32_t *pDataRow; + uint32_t *pDataDestR, *pDataDestRow; + uint32x4_t vecOffsRef, vecOffsCur; + uint32_t blkCnt; + uint32x4_t vecIn; + +#ifdef ARM_MATH_MATRIX_CHECK + /* + * Check for matrix mismatch condition + */ + if ((srcRows != dstCols) || (srcCols != dstRows)) + { + /* + * Set status as ARM_MATH_SIZE_MISMATCH + */ + return ARM_MATH_SIZE_MISMATCH; + } +#else + (void)dstRows; + (void)dstCols; +#endif + + /* 2x2, 3x3 and 4x4 specialization to be added */ + + vecOffsRef[0] = 0; + vecOffsRef[1] = 1; + vecOffsRef[2] = srcCols << 1; + vecOffsRef[3] = (srcCols << 1) + 1; + + pDataRow = pDataSrc; + pDataDestRow = pDataDest; + i = srcCols; + do + { + pDataC = (uint32_t const *) pDataRow; + pDataDestR = pDataDestRow; + vecOffsCur = vecOffsRef; + + blkCnt = (srcRows * CMPLX_DIM) >> 2; + while (blkCnt > 0U) + { + vecIn = vldrwq_gather_shifted_offset(pDataC, vecOffsCur); + vstrwq(pDataDestR, vecIn); + pDataDestR += 4; + vecOffsCur = vaddq(vecOffsCur, (srcCols << 2)); + /* + * Decrement the blockSize loop counter + */ + blkCnt--; + } + /* + * tail + * (will be merged thru tail predication) + */ + blkCnt = (srcRows * CMPLX_DIM) & 3; + if (blkCnt > 0U) + { + mve_pred16_t p0 = vctp32q(blkCnt); + vecIn = vldrwq_gather_shifted_offset(pDataC, vecOffsCur); + vstrwq_p(pDataDestR, vecIn, p0); + } + + pDataRow += CMPLX_DIM; + pDataDestRow += (srcRows * CMPLX_DIM); + } + while (--i); + + return (ARM_MATH_SUCCESS); +} + +__STATIC_INLINE arm_status arm_mat_trans_16bit_2x2(uint16_t * pDataSrc, uint16_t * pDataDest) +{ + pDataDest[0] = pDataSrc[0]; + pDataDest[3] = pDataSrc[3]; + pDataDest[2] = pDataSrc[1]; + pDataDest[1] = pDataSrc[2]; + + return (ARM_MATH_SUCCESS); +} + +__STATIC_INLINE arm_status arm_mat_trans_16bit_3x3_mve(uint16_t * pDataSrc, uint16_t * pDataDest) +{ + static const uint16_t stridesTr33[8] = { 0, 3, 6, 1, 4, 7, 2, 5 }; + uint16x8_t vecOffs1; + uint16x8_t vecIn1; + /* + * + * | 0 1 2 | | 0 3 6 | 8 x 16 flattened version | 0 3 6 1 4 7 2 5 | + * | 3 4 5 | => | 1 4 7 | => | 8 . . . . . . . | + * | 6 7 8 | | 2 5 8 | (row major) + * + */ + vecOffs1 = vldrhq_u16((uint16_t const *) stridesTr33); + vecIn1 = vldrhq_u16((uint16_t const *) pDataSrc); + + vstrhq_scatter_shifted_offset_u16(pDataDest, vecOffs1, vecIn1); + + pDataDest[8] = pDataSrc[8]; + + return (ARM_MATH_SUCCESS); +} + + +__STATIC_INLINE arm_status arm_mat_trans_16bit_4x4_mve(uint16_t * pDataSrc, uint16_t * pDataDest) +{ + static const uint16_t stridesTr44_1[8] = { 0, 4, 8, 12, 1, 5, 9, 13 }; + static const uint16_t stridesTr44_2[8] = { 2, 6, 10, 14, 3, 7, 11, 15 }; + uint16x8_t vecOffs1, vecOffs2; + uint16x8_t vecIn1, vecIn2; + uint16_t const * pDataSrcVec = (uint16_t const *) pDataSrc; + + /* + * 4x4 Matrix transposition + * + * | 0 1 2 3 | | 0 4 8 12 | 8 x 16 flattened version + * | 4 5 6 7 | => | 1 5 9 13 | => [0 4 8 12 1 5 9 13] + * | 8 9 10 11 | | 2 6 10 14 | [2 6 10 14 3 7 11 15] + * | 12 13 14 15 | | 3 7 11 15 | + */ + + vecOffs1 = vldrhq_u16((uint16_t const *) stridesTr44_1); + vecOffs2 = vldrhq_u16((uint16_t const *) stridesTr44_2); + vecIn1 = vldrhq_u16(pDataSrcVec); + pDataSrcVec += 8; + vecIn2 = vldrhq_u16(pDataSrcVec); + + vstrhq_scatter_shifted_offset_u16(pDataDest, vecOffs1, vecIn1); + vstrhq_scatter_shifted_offset_u16(pDataDest, vecOffs2, vecIn2); + + + return (ARM_MATH_SUCCESS); +} + + + +__STATIC_INLINE arm_status arm_mat_trans_16bit_generic( + uint16_t srcRows, + uint16_t srcCols, + uint16_t * pDataSrc, + uint16_t * pDataDest) +{ + uint16x8_t vecOffs; + uint32_t i; + uint32_t blkCnt; + uint16_t const *pDataC; + uint16_t *pDataDestR; + uint16x8_t vecIn; + + vecOffs = vidupq_u16((uint32_t)0, 1); + vecOffs = vecOffs * srcCols; + + i = srcCols; + while(i > 0U) + { + pDataC = (uint16_t const *) pDataSrc; + pDataDestR = pDataDest; + + blkCnt = srcRows >> 3; + while (blkCnt > 0U) + { + vecIn = vldrhq_gather_shifted_offset_u16(pDataC, vecOffs); + vstrhq_u16(pDataDestR, vecIn); + pDataDestR += 8; + pDataC = pDataC + srcCols * 8; + /* + * Decrement the blockSize loop counter + */ + blkCnt--; + } + + /* + * tail + */ + blkCnt = srcRows & 7; + if (blkCnt > 0U) + { + mve_pred16_t p0 = vctp16q(blkCnt); + vecIn = vldrhq_gather_shifted_offset_u16(pDataC, vecOffs); + vstrhq_p_u16(pDataDestR, vecIn, p0); + } + pDataSrc += 1; + pDataDest += srcRows; + i--; + } + + return (ARM_MATH_SUCCESS); +} + + +__STATIC_INLINE arm_status arm_mat_cmplx_trans_16bit( + uint16_t srcRows, + uint16_t srcCols, + uint16_t *pDataSrc, + uint16_t dstRows, + uint16_t dstCols, + uint16_t *pDataDest) +{ + static const uint16_t loadCmplxCol[8] = { 0, 0, 1, 1, 2, 2, 3, 3 }; + int i; + uint16x8_t vecOffsRef, vecOffsCur; + uint16_t const *pDataC; + uint16_t *pDataRow; + uint16_t *pDataDestR, *pDataDestRow; + uint32_t blkCnt; + uint16x8_t vecIn; + +#ifdef ARM_MATH_MATRIX_CHECK + /* + * Check for matrix mismatch condition + */ + if ((srcRows != dstCols) || (srcCols != dstRows)) + { + /* + * Set status as ARM_MATH_SIZE_MISMATCH + */ + return ARM_MATH_SIZE_MISMATCH; + } +#else + (void)dstRows; + (void)dstCols; +#endif + + /* + * 2x2, 3x3 and 4x4 specialization to be added + */ + + + /* + * build [0, 1, 2xcol, 2xcol+1, 4xcol, 4xcol+1, 6xcol, 6xcol+1] + */ + vecOffsRef = vldrhq_u16((uint16_t const *) loadCmplxCol); + vecOffsRef = vmulq(vecOffsRef, (uint16_t) (srcCols * CMPLX_DIM)) + + viwdupq_u16((uint32_t)0, (uint16_t) 2, 1); + + pDataRow = pDataSrc; + pDataDestRow = pDataDest; + i = srcCols; + do + { + pDataC = (uint16_t const *) pDataRow; + pDataDestR = pDataDestRow; + vecOffsCur = vecOffsRef; + + blkCnt = (srcRows * CMPLX_DIM) >> 3; + while (blkCnt > 0U) + { + vecIn = vldrhq_gather_shifted_offset(pDataC, vecOffsCur); + vstrhq(pDataDestR, vecIn); + pDataDestR+= 8; // VEC_LANES_U16 + vecOffsCur = vaddq(vecOffsCur, (srcCols << 3)); + /* + * Decrement the blockSize loop counter + */ + blkCnt--; + } + /* + * tail + * (will be merged thru tail predication) + */ + blkCnt = (srcRows * CMPLX_DIM) & 0x7; + if (blkCnt > 0U) + { + mve_pred16_t p0 = vctp16q(blkCnt); + vecIn = vldrhq_gather_shifted_offset(pDataC, vecOffsCur); + vstrhq_p(pDataDestR, vecIn, p0); + } + + pDataRow += CMPLX_DIM; + pDataDestRow += (srcRows * CMPLX_DIM); + } + while (--i); + + return (ARM_MATH_SUCCESS); +} +#endif /* MVEF and MVEI */ + +/*************************************** + +Definitions available for MVEI only + +***************************************/ +#if (defined (ARM_MATH_HELIUM) || defined(ARM_MATH_MVEI)) && !defined(ARM_MATH_AUTOVECTORIZE) + +#include "arm_common_tables.h" + +#define MVE_ASRL_SAT16(acc, shift) ((sqrshrl_sat48(acc, -(32-shift)) >> 32) & 0xffffffff) +#define MVE_ASRL_SAT32(acc, shift) ((sqrshrl(acc, -(32-shift)) >> 32) & 0xffffffff) + + +#if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_FAST_SQRT_Q31_MVE) +__STATIC_INLINE q31x4_t FAST_VSQRT_Q31(q31x4_t vecIn) +{ + q63x2_t vecTmpLL; + q31x4_t vecTmp0, vecTmp1; + q31_t scale; + q63_t tmp64; + q31x4_t vecNrm, vecDst, vecIdx, vecSignBits; + + + vecSignBits = vclsq(vecIn); + vecSignBits = vbicq_n_s32(vecSignBits, 1); + /* + * in = in << no_of_sign_bits; + */ + vecNrm = vshlq(vecIn, vecSignBits); + /* + * index = in >> 24; + */ + vecIdx = vecNrm >> 24; + vecIdx = vecIdx << 1; + + vecTmp0 = vldrwq_gather_shifted_offset_s32(sqrtTable_Q31, (uint32x4_t)vecIdx); + + vecIdx = vecIdx + 1; + + vecTmp1 = vldrwq_gather_shifted_offset_s32(sqrtTable_Q31, (uint32x4_t)vecIdx); + + vecTmp1 = vqrdmulhq(vecTmp1, vecNrm); + vecTmp0 = vecTmp0 - vecTmp1; + vecTmp1 = vqrdmulhq(vecTmp0, vecTmp0); + vecTmp1 = vqrdmulhq(vecNrm, vecTmp1); + vecTmp1 = vdupq_n_s32(0x18000000) - vecTmp1; + vecTmp0 = vqrdmulhq(vecTmp0, vecTmp1); + vecTmpLL = vmullbq_int(vecNrm, vecTmp0); + + /* + * scale elements 0, 2 + */ + scale = 26 + (vecSignBits[0] >> 1); + tmp64 = asrl(vecTmpLL[0], scale); + vecDst[0] = (q31_t) tmp64; + + scale = 26 + (vecSignBits[2] >> 1); + tmp64 = asrl(vecTmpLL[1], scale); + vecDst[2] = (q31_t) tmp64; + + vecTmpLL = vmulltq_int(vecNrm, vecTmp0); + + /* + * scale elements 1, 3 + */ + scale = 26 + (vecSignBits[1] >> 1); + tmp64 = asrl(vecTmpLL[0], scale); + vecDst[1] = (q31_t) tmp64; + + scale = 26 + (vecSignBits[3] >> 1); + tmp64 = asrl(vecTmpLL[1], scale); + vecDst[3] = (q31_t) tmp64; + /* + * set negative values to 0 + */ + vecDst = vdupq_m(vecDst, 0, vcmpltq_n_s32(vecIn, 0)); + + return vecDst; +} +#endif + +#if !defined(ARM_DSP_CONFIG_TABLES) || defined(ARM_ALL_FAST_TABLES) || defined(ARM_TABLE_FAST_SQRT_Q15_MVE) +__STATIC_INLINE q15x8_t FAST_VSQRT_Q15(q15x8_t vecIn) +{ + q31x4_t vecTmpLev, vecTmpLodd, vecSignL; + q15x8_t vecTmp0, vecTmp1; + q15x8_t vecNrm, vecDst, vecIdx, vecSignBits; + + vecDst = vuninitializedq_s16(); + + vecSignBits = vclsq(vecIn); + vecSignBits = vbicq_n_s16(vecSignBits, 1); + /* + * in = in << no_of_sign_bits; + */ + vecNrm = vshlq(vecIn, vecSignBits); + + vecIdx = vecNrm >> 8; + vecIdx = vecIdx << 1; + + vecTmp0 = vldrhq_gather_shifted_offset_s16(sqrtTable_Q15, (uint16x8_t)vecIdx); + + vecIdx = vecIdx + 1; + + vecTmp1 = vldrhq_gather_shifted_offset_s16(sqrtTable_Q15, (uint16x8_t)vecIdx); + + vecTmp1 = vqrdmulhq(vecTmp1, vecNrm); + vecTmp0 = vecTmp0 - vecTmp1; + vecTmp1 = vqrdmulhq(vecTmp0, vecTmp0); + vecTmp1 = vqrdmulhq(vecNrm, vecTmp1); + vecTmp1 = vdupq_n_s16(0x1800) - vecTmp1; + vecTmp0 = vqrdmulhq(vecTmp0, vecTmp1); + + vecSignBits = vecSignBits >> 1; + + vecTmpLev = vmullbq_int(vecNrm, vecTmp0); + vecTmpLodd = vmulltq_int(vecNrm, vecTmp0); + + vecTmp0 = vecSignBits + 10; + /* + * negate sign to apply register based vshl + */ + vecTmp0 = -vecTmp0; + + /* + * shift even elements + */ + vecSignL = vmovlbq(vecTmp0); + vecTmpLev = vshlq(vecTmpLev, vecSignL); + /* + * shift odd elements + */ + vecSignL = vmovltq(vecTmp0); + vecTmpLodd = vshlq(vecTmpLodd, vecSignL); + /* + * merge and narrow odd and even parts + */ + vecDst = vmovnbq_s32(vecDst, vecTmpLev); + vecDst = vmovntq_s32(vecDst, vecTmpLodd); + /* + * set negative values to 0 + */ + vecDst = vdupq_m(vecDst, 0, vcmpltq_n_s16(vecIn, 0)); + + return vecDst; +} +#endif + +#endif /* defined (ARM_MATH_HELIUM) || defined(ARM_MATH_MVEI) */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Middlewares/ST/ARM/DSP/Include/arm_math.h b/Middlewares/ST/ARM/DSP/Include/arm_math.h new file mode 100644 index 0000000..59462c2 --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/arm_math.h @@ -0,0 +1,237 @@ +/****************************************************************************** + * @file arm_math.h + * @brief Public header file for CMSIS DSP Library + * @version V1.10.0 + * @date 08 July 2021 + * Target Processor: Cortex-M and Cortex-A cores + ******************************************************************************/ +/* + * Copyright (c) 2010-2021 Arm Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + \mainpage CMSIS DSP Software Library + * + * \section intro Introduction + * + * This user manual describes the CMSIS DSP software library, + * a suite of common compute processing functions for use on Cortex-M and Cortex-A processor + * based devices. + * + * The library is divided into a number of functions each covering a specific category: + * - \ref groupMath "Basic math functions" + * - \ref groupFastMath "Fast math functions" + * - \ref groupCmplxMath "Complex math functions" + * - \ref groupFilters "Filtering functions" + * - \ref groupMatrix "Matrix functions" + * - \ref groupTransforms "Transform functions" + * - \ref groupController "Motor control functions" + * - \ref groupStats "Statistical functions" + * - \ref groupSupport "Support functions" + * - \ref groupInterpolation "Interpolation functions" + * - \ref groupSVM "Support Vector Machine functions (SVM)" + * - \ref groupBayes "Bayes classifier functions" + * - \ref groupDistance "Distance functions" + * - \ref groupQuaternionMath "Quaternion functions" + * - \ref groupWindow "Window functions" + * + * The library has generally separate functions for operating on 8-bit integers, 16-bit integers, + * 32-bit integer and 32-bit floating-point values and 64-bit floating-point values. + * + * The library is providing vectorized versions of most algorithms for Helium + * and of most f32 algorithms for Neon. + * + * When using a vectorized version, provide a little bit of padding after the end of + * a buffer (3 words) because the vectorized code may read a little bit after the end + * of a buffer. You don't have to modify your buffers but just ensure that the + * end of buffer + padding is not outside of a memory region. + * + * CMSIS-DSP pack is containing an optional project : The CMSIS-DSP + * Compute Graph. The documentation for this project is available + * on the CMSIS-DSP github repository. + * + * A Python wrapper is also available with a Python API as close as possible + * to the C one. It can be used to start developing and testing an algorithm with NumPy and + * SciPy before writing the C version. Is is available on PyPI.org. + * It can be installed with : pip install cmsisdsp + * + * + * \section using Using the Library + * + * The library is released in source form. It is strongly advised to compile the library using -Ofast to + * have the best performances. + * + * The library functions are declared in the public file `arm_math.h` which is placed in the `Include` folder. + * Simply include this file. If you don't want to include everything, you can also rely + * on headers in `Include/dsp` folder and use only what you need. + * + * \section example Examples + * + * The library ships with a number of examples which demonstrate how to use the library functions. Please refer to \ref groupExamples. + * + * \section toolchain Toolchain Support + * + * The library is now tested on Fast Models building with cmake. + * Core M0, M4, M7, M33, M55, A32 are tested. + * + * + * \section preprocessor Preprocessor Macros + * + * Each library project has different preprocessor macros. + * + * - `ARM_MATH_BIG_ENDIAN`: + * - Define macro ARM_MATH_BIG_ENDIAN to build the library for big endian targets. By default library builds for little endian targets. + * . + * - `ARM_MATH_MATRIX_CHECK`: + * - Define macro ARM_MATH_MATRIX_CHECK for checking on the input and output sizes of matrices + * . + * - `ARM_MATH_ROUNDING`: + * - Define macro ARM_MATH_ROUNDING for rounding on support functions + * . + * - `ARM_MATH_LOOPUNROLL`: + * - Define macro ARM_MATH_LOOPUNROLL to enable manual loop unrolling in DSP functions + * . + * - `ARM_MATH_NEON`: + * - Define macro ARM_MATH_NEON to enable Neon versions of the DSP functions. + * It is not enabled by default when Neon is available because performances are + * dependent on the compiler and target architecture. + * . + * - `ARM_MATH_NEON_EXPERIMENTAL`: + * - Define macro ARM_MATH_NEON_EXPERIMENTAL to enable experimental Neon versions of + * of some DSP functions. Experimental Neon versions currently do not have better + * performances than the scalar versions. + * . + * - `ARM_MATH_HELIUM`: + * - It implies the flags ARM_MATH_MVEF and ARM_MATH_MVEI and ARM_MATH_MVE_FLOAT16. + * . + * - `ARM_MATH_HELIUM_EXPERIMENTAL`: + * - Only taken into account when ARM_MATH_MVEF, ARM_MATH_MVEI or ARM_MATH_MVE_FLOAT16 are defined. + * Enable some vector versions which may have worse performance than scalar + * depending on the core / compiler configuration. + * . + * - `ARM_MATH_MVEF`: + * - Select Helium versions of the f32 algorithms. + * It implies ARM_MATH_FLOAT16 and ARM_MATH_MVEI. + * . + * - `ARM_MATH_MVEI`: + * - Select Helium versions of the int and fixed point algorithms. + * . + * - `ARM_MATH_MVE_FLOAT16`: + * - MVE Float16 implementations of some algorithms (Requires MVE extension). + * . + * - `DISABLEFLOAT16`: + * - Disable float16 algorithms when __fp16 is not supported for a + * specific compiler / core configuration. + * This is only valid for scalar. When vector architecture is + * supporting f16 then it can't be disabled. + * . + * - `ARM_MATH_AUTOVECTORIZE`: + * - With Helium or Neon, disable the use of vectorized code with C intrinsics + * and use pure C instead. The vectorization is then done by the compiler. + * + * \section pack CMSIS-DSP in ARM::CMSIS Pack + * + * The following files relevant to CMSIS-DSP are present in the ARM::CMSIS Pack directories: + * |File/Folder |Content | + * |---------------------------------|------------------------------------------------------------------------| + * |\b CMSIS\\Documentation\\DSP | This documentation | + * |\b CMSIS\\DSP\\Examples | Example projects demonstrating the usage of the library functions | + * |\b CMSIS\\DSP\\ComputeLibrary | Small Neon kernels when building on Cortex-A + * |\b CMSIS\\DSP\\Include | include files for using and building the lib + * |\b CMSIS\\DSP\\PrivateInclude | private include files for building the lib | + * |\b CMSIS\\DSP\\Source | source files | + * + * \section rev Revision History of CMSIS-DSP + * Please refer to \ref ChangeLog_pg. + * + * \section license License + * + * The CMSIS-DSP is provided free of charge under the Apache 2.0 License. + */ + + + + + + + + + + + +/** + * @defgroup groupExamples Examples + */ + + + + + +#ifndef _ARM_MATH_H +#define _ARM_MATH_H + + +#include "arm_math_types.h" +#include "arm_math_memory.h" + +#include "dsp/none.h" +#include "dsp/utils.h" + +#include "dsp/basic_math_functions.h" +#include "dsp/interpolation_functions.h" +#include "dsp/bayes_functions.h" +#include "dsp/matrix_functions.h" +#include "dsp/complex_math_functions.h" +#include "dsp/statistics_functions.h" +#include "dsp/controller_functions.h" +#include "dsp/support_functions.h" +#include "dsp/distance_functions.h" +#include "dsp/svm_functions.h" +#include "dsp/fast_math_functions.h" +#include "dsp/transform_functions.h" +#include "dsp/filtering_functions.h" +#include "dsp/quaternion_math_functions.h" +#include "dsp/window_functions.h" + + + +#ifdef __cplusplus +extern "C" +{ +#endif + + + + +//#define TABLE_SPACING_Q31 0x400000 +//#define TABLE_SPACING_Q15 0x80 + + + + + +#ifdef __cplusplus +} +#endif + + +#endif /* _ARM_MATH_H */ + +/** + * + * End of file. + */ diff --git a/Middlewares/ST/ARM/DSP/Include/arm_math_f16.h b/Middlewares/ST/ARM/DSP/Include/arm_math_f16.h new file mode 100644 index 0000000..daf0c53 --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/arm_math_f16.h @@ -0,0 +1,59 @@ +/****************************************************************************** + * @file arm_math_f16.h + * @brief Public header file for f16 function of the CMSIS DSP Library + * @version V1.10.0 + * @date 08 July 2021 + * Target Processor: Cortex-M and Cortex-A cores + ******************************************************************************/ +/* + * Copyright (c) 2010-2021 Arm Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ARM_MATH_F16_H +#define _ARM_MATH_F16_H + +#include "arm_math.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "arm_math_types_f16.h" +#include "dsp/none.h" +#include "dsp/utils.h" +#include "dsp/basic_math_functions_f16.h" +#include "dsp/interpolation_functions_f16.h" +#include "dsp/bayes_functions_f16.h" +#include "dsp/matrix_functions_f16.h" +#include "dsp/complex_math_functions_f16.h" +#include "dsp/statistics_functions_f16.h" +#include "dsp/controller_functions_f16.h" +#include "dsp/support_functions_f16.h" +#include "dsp/distance_functions_f16.h" +#include "dsp/svm_functions_f16.h" +#include "dsp/fast_math_functions_f16.h" +#include "dsp/transform_functions_f16.h" +#include "dsp/filtering_functions_f16.h" + +#ifdef __cplusplus +} +#endif + +#endif /* _ARM_MATH_F16_H */ + + diff --git a/Middlewares/ST/ARM/DSP/Include/arm_math_memory.h b/Middlewares/ST/ARM/DSP/Include/arm_math_memory.h new file mode 100644 index 0000000..7bd83dc --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/arm_math_memory.h @@ -0,0 +1,206 @@ +/****************************************************************************** + * @file arm_math_memory.h + * @brief Public header file for CMSIS DSP Library + * @version V1.10.0 + * @date 08 July 2021 + * Target Processor: Cortex-M and Cortex-A cores + ******************************************************************************/ +/* + * Copyright (c) 2010-2021 Arm Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ARM_MATH_MEMORY_H_ + +#define _ARM_MATH_MEMORY_H_ + +#include "arm_math_types.h" + + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + @brief definition to read/write two 16 bit values. + @deprecated + */ +#if defined ( __CC_ARM ) + #define __SIMD32_TYPE int32_t __packed +#elif defined ( __ARMCC_VERSION ) && ( __ARMCC_VERSION >= 6010050 ) + #define __SIMD32_TYPE int32_t +#elif defined ( __GNUC__ ) + #define __SIMD32_TYPE int32_t +#elif defined ( __ICCARM__ ) + #define __SIMD32_TYPE int32_t __packed +#elif defined ( __TI_ARM__ ) + #define __SIMD32_TYPE int32_t +#elif defined ( __CSMC__ ) + #define __SIMD32_TYPE int32_t +#elif defined ( __TASKING__ ) + #define __SIMD32_TYPE __un(aligned) int32_t +#elif defined(_MSC_VER ) + #define __SIMD32_TYPE int32_t +#else + #error Unknown compiler +#endif + +#define __SIMD32(addr) (*(__SIMD32_TYPE **) & (addr)) +#define __SIMD32_CONST(addr) ( (__SIMD32_TYPE * ) (addr)) +#define _SIMD32_OFFSET(addr) (*(__SIMD32_TYPE * ) (addr)) +#define __SIMD64(addr) (*( int64_t **) & (addr)) + + +/* SIMD replacement */ + + +/** + @brief Read 2 Q15 from Q15 pointer. + @param[in] pQ15 points to input value + @return Q31 value + */ +__STATIC_FORCEINLINE q31_t read_q15x2 ( + q15_t const * pQ15) +{ + q31_t val; + +#ifdef __ARM_FEATURE_UNALIGNED + memcpy (&val, pQ15, 4); +#else + val = (pQ15[1] << 16) | (pQ15[0] & 0x0FFFF) ; +#endif + + return (val); +} + +/** + @brief Read 2 Q15 from Q15 pointer and increment pointer afterwards. + @param[in] pQ15 points to input value + @return Q31 value + */ +#define read_q15x2_ia(pQ15) read_q15x2((*(pQ15) += 2) - 2) + +/** + @brief Read 2 Q15 from Q15 pointer and decrement pointer afterwards. + @param[in] pQ15 points to input value + @return Q31 value + */ +#define read_q15x2_da(pQ15) read_q15x2((*(pQ15) -= 2) + 2) + +/** + @brief Write 2 Q15 to Q15 pointer and increment pointer afterwards. + @param[in] pQ15 points to input value + @param[in] value Q31 value + @return none + */ +__STATIC_FORCEINLINE void write_q15x2_ia ( + q15_t ** pQ15, + q31_t value) +{ + q31_t val = value; +#ifdef __ARM_FEATURE_UNALIGNED + memcpy (*pQ15, &val, 4); +#else + (*pQ15)[0] = (q15_t)(val & 0x0FFFF); + (*pQ15)[1] = (q15_t)((val >> 16) & 0x0FFFF); +#endif + + *pQ15 += 2; +} + +/** + @brief Write 2 Q15 to Q15 pointer. + @param[in] pQ15 points to input value + @param[in] value Q31 value + @return none + */ +__STATIC_FORCEINLINE void write_q15x2 ( + q15_t * pQ15, + q31_t value) +{ + q31_t val = value; + +#ifdef __ARM_FEATURE_UNALIGNED + memcpy (pQ15, &val, 4); +#else + pQ15[0] = (q15_t)(val & 0x0FFFF); + pQ15[1] = (q15_t)(val >> 16); +#endif +} + + +/** + @brief Read 4 Q7 from Q7 pointer + @param[in] pQ7 points to input value + @return Q31 value + */ +__STATIC_FORCEINLINE q31_t read_q7x4 ( + q7_t const * pQ7) +{ + q31_t val; + +#ifdef __ARM_FEATURE_UNALIGNED + memcpy (&val, pQ7, 4); +#else + val =((pQ7[3] & 0x0FF) << 24) | ((pQ7[2] & 0x0FF) << 16) | ((pQ7[1] & 0x0FF) << 8) | (pQ7[0] & 0x0FF); +#endif + return (val); +} + +/** + @brief Read 4 Q7 from Q7 pointer and increment pointer afterwards. + @param[in] pQ7 points to input value + @return Q31 value + */ +#define read_q7x4_ia(pQ7) read_q7x4((*(pQ7) += 4) - 4) + +/** + @brief Read 4 Q7 from Q7 pointer and decrement pointer afterwards. + @param[in] pQ7 points to input value + @return Q31 value + */ +#define read_q7x4_da(pQ7) read_q7x4((*(pQ7) -= 4) + 4) + +/** + @brief Write 4 Q7 to Q7 pointer and increment pointer afterwards. + @param[in] pQ7 points to input value + @param[in] value Q31 value + @return none + */ +__STATIC_FORCEINLINE void write_q7x4_ia ( + q7_t ** pQ7, + q31_t value) +{ + q31_t val = value; +#ifdef __ARM_FEATURE_UNALIGNED + memcpy (*pQ7, &val, 4); +#else + (*pQ7)[0] = (q7_t)(val & 0x0FF); + (*pQ7)[1] = (q7_t)((val >> 8) & 0x0FF); + (*pQ7)[2] = (q7_t)((val >> 16) & 0x0FF); + (*pQ7)[3] = (q7_t)((val >> 24) & 0x0FF); + +#endif + *pQ7 += 4; +} + + +#ifdef __cplusplus +} +#endif + +#endif /*ifndef _ARM_MATH_MEMORY_H_ */ diff --git a/Middlewares/ST/ARM/DSP/Include/arm_math_types.h b/Middlewares/ST/ARM/DSP/Include/arm_math_types.h new file mode 100644 index 0000000..c615e66 --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/arm_math_types.h @@ -0,0 +1,616 @@ +/****************************************************************************** + * @file arm_math_types.h + * @brief Public header file for CMSIS DSP Library + * @version V1.10.0 + * @date 08 July 2021 + * Target Processor: Cortex-M and Cortex-A cores + ******************************************************************************/ +/* + * Copyright (c) 2010-2021 Arm Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ARM_MATH_TYPES_H_ + +#define _ARM_MATH_TYPES_H_ + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Compiler specific diagnostic adjustment */ +#if defined ( __CC_ARM ) + +#elif defined ( __ARMCC_VERSION ) && ( __ARMCC_VERSION >= 6010050 ) + +#elif defined ( __APPLE_CC__ ) + #pragma GCC diagnostic ignored "-Wold-style-cast" + +#elif defined ( __GNUC__ ) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wsign-conversion" + #pragma GCC diagnostic ignored "-Wconversion" + #pragma GCC diagnostic ignored "-Wunused-parameter" + +#elif defined ( __ICCARM__ ) + +#elif defined ( __TI_ARM__ ) + +#elif defined ( __CSMC__ ) + +#elif defined ( __TASKING__ ) + +#elif defined ( _MSC_VER ) + +#else + #error Unknown compiler +#endif + + +/* Included for instrinsics definitions */ +#if defined (_MSC_VER ) +#include
*psinVal = y0 + (fract * (y1 - y0)).
+ -# Fetch the value corresponding to \c index from cosine table to \c y0 and also value from \c index+1 to \c y1.
+ -# Cosine value is computed as *pcosVal = y0 + (fract * (y1 - y0)).
+ */
+
+/**
+ * @brief Floating-point sin_cos function.
+ * @param[in] theta input value in degrees
+ * @param[out] pSinVal points to the processed sine output.
+ * @param[out] pCosVal points to the processed cos output.
+ */
+ void arm_sin_cos_f32(
+ float32_t theta,
+ float32_t * pSinVal,
+ float32_t * pCosVal);
+
+
+ /**
+ * @brief Q31 sin_cos function.
+ * @param[in] theta scaled input value in degrees
+ * @param[out] pSinVal points to the processed sine output.
+ * @param[out] pCosVal points to the processed cosine output.
+ */
+ void arm_sin_cos_q31(
+ q31_t theta,
+ q31_t * pSinVal,
+ q31_t * pCosVal);
+
+
+/**
+ @ingroup groupController
+ */
+
+/**
+ * @defgroup PID PID Motor Control
+ *
+ * A Proportional Integral Derivative (PID) controller is a generic feedback control
+ * loop mechanism widely used in industrial control systems.
+ * A PID controller is the most commonly used type of feedback controller.
+ *
+ * This set of functions implements (PID) controllers
+ * for Q15, Q31, and floating-point data types. The functions operate on a single sample
+ * of data and each call to the function returns a single processed value.
+ * S points to an instance of the PID control data structure. in
+ * is the input sample value. The functions return the output value.
+ *
+ * \par Algorithm:
+ * + * y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2] + * A0 = Kp + Ki + Kd + * A1 = (-Kp ) - (2 * Kd ) + * A2 = Kd + *+ * + * \par + * where \c Kp is proportional constant, \c Ki is Integral constant and \c Kd is Derivative constant + * + * \par + * \image html PID.gif "Proportional Integral Derivative Controller" + * + * \par + * The PID controller calculates an "error" value as the difference between + * the measured output and the reference input. + * The controller attempts to minimize the error by adjusting the process control inputs. + * The proportional value determines the reaction to the current error, + * the integral value determines the reaction based on the sum of recent errors, + * and the derivative value determines the reaction based on the rate at which the error has been changing. + * + * \par Instance Structure + * The Gains A0, A1, A2 and state variables for a PID controller are stored together in an instance data structure. + * A separate instance structure must be defined for each PID Controller. + * There are separate instance structure declarations for each of the 3 supported data types. + * + * \par Reset Functions + * There is also an associated reset function for each data type which clears the state array. + * + * \par Initialization Functions + * There is also an associated initialization function for each data type. + * The initialization function performs the following operations: + * - Initializes the Gains A0, A1, A2 from Kp,Ki, Kd gains. + * - Zeros out the values in the state buffer. + * + * \par + * Instance structure cannot be placed into a const data section and it is recommended to use the initialization function. + * + * \par Fixed-Point Behavior + * Care must be taken when using the fixed-point versions of the PID Controller functions. + * In particular, the overflow and saturation behavior of the accumulator used in each function must be considered. + * Refer to the function specific documentation below for usage guidelines. + */ + + + /** + * @ingroup PID + * @brief Instance structure for the Q15 PID Control. + */ + typedef struct + { + q15_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ +#if !defined (ARM_MATH_DSP) + q15_t A1; /**< The derived gain A1 = -Kp - 2Kd */ + q15_t A2; /**< The derived gain A1 = Kd. */ +#else + q31_t A1; /**< The derived gain A1 = -Kp - 2Kd | Kd.*/ +#endif + q15_t state[3]; /**< The state array of length 3. */ + q15_t Kp; /**< The proportional gain. */ + q15_t Ki; /**< The integral gain. */ + q15_t Kd; /**< The derivative gain. */ + } arm_pid_instance_q15; + + /** + * @ingroup PID + * @brief Instance structure for the Q31 PID Control. + */ + typedef struct + { + q31_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ + q31_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */ + q31_t A2; /**< The derived gain, A2 = Kd . */ + q31_t state[3]; /**< The state array of length 3. */ + q31_t Kp; /**< The proportional gain. */ + q31_t Ki; /**< The integral gain. */ + q31_t Kd; /**< The derivative gain. */ + } arm_pid_instance_q31; + + /** + * @ingroup PID + * @brief Instance structure for the floating-point PID Control. + */ + typedef struct + { + float32_t A0; /**< The derived gain, A0 = Kp + Ki + Kd . */ + float32_t A1; /**< The derived gain, A1 = -Kp - 2Kd. */ + float32_t A2; /**< The derived gain, A2 = Kd . */ + float32_t state[3]; /**< The state array of length 3. */ + float32_t Kp; /**< The proportional gain. */ + float32_t Ki; /**< The integral gain. */ + float32_t Kd; /**< The derivative gain. */ + } arm_pid_instance_f32; + + + + /** + * @brief Initialization function for the floating-point PID Control. + * @param[in,out] S points to an instance of the PID structure. + * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. + */ + void arm_pid_init_f32( + arm_pid_instance_f32 * S, + int32_t resetStateFlag); + + + /** + * @brief Reset function for the floating-point PID Control. + * @param[in,out] S is an instance of the floating-point PID Control structure + */ + void arm_pid_reset_f32( + arm_pid_instance_f32 * S); + + + /** + * @brief Initialization function for the Q31 PID Control. + * @param[in,out] S points to an instance of the Q15 PID structure. + * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. + */ + void arm_pid_init_q31( + arm_pid_instance_q31 * S, + int32_t resetStateFlag); + + + /** + * @brief Reset function for the Q31 PID Control. + * @param[in,out] S points to an instance of the Q31 PID Control structure + */ + + void arm_pid_reset_q31( + arm_pid_instance_q31 * S); + + + /** + * @brief Initialization function for the Q15 PID Control. + * @param[in,out] S points to an instance of the Q15 PID structure. + * @param[in] resetStateFlag flag to reset the state. 0 = no change in state 1 = reset the state. + */ + void arm_pid_init_q15( + arm_pid_instance_q15 * S, + int32_t resetStateFlag); + + + /** + * @brief Reset function for the Q15 PID Control. + * @param[in,out] S points to an instance of the q15 PID Control structure + */ + void arm_pid_reset_q15( + arm_pid_instance_q15 * S); + + + + + + /** + * @ingroup PID + * @brief Process function for the floating-point PID Control. + * @param[in,out] S is an instance of the floating-point PID Control structure + * @param[in] in input sample to process + * @return processed output sample. + */ + __STATIC_FORCEINLINE float32_t arm_pid_f32( + arm_pid_instance_f32 * S, + float32_t in) + { + float32_t out; + + /* y[n] = y[n-1] + A0 * x[n] + A1 * x[n-1] + A2 * x[n-2] */ + out = (S->A0 * in) + + (S->A1 * S->state[0]) + (S->A2 * S->state[1]) + (S->state[2]); + + /* Update state */ + S->state[1] = S->state[0]; + S->state[0] = in; + S->state[2] = out; + + /* return to application */ + return (out); + + } + +/** + @ingroup PID + @brief Process function for the Q31 PID Control. + @param[in,out] S points to an instance of the Q31 PID Control structure + @param[in] in input sample to process + @return processed output sample. + + \par Scaling and Overflow Behavior + The function is implemented using an internal 64-bit accumulator. + The accumulator has a 2.62 format and maintains full precision of the intermediate multiplication results but provides only a single guard bit. + Thus, if the accumulator result overflows it wraps around rather than clip. + In order to avoid overflows completely the input signal must be scaled down by 2 bits as there are four additions. + After all multiply-accumulates are performed, the 2.62 accumulator is truncated to 1.32 format and then saturated to 1.31 format. + */ +__STATIC_FORCEINLINE q31_t arm_pid_q31( + arm_pid_instance_q31 * S, + q31_t in) + { + q63_t acc; + q31_t out; + + /* acc = A0 * x[n] */ + acc = (q63_t) S->A0 * in; + + /* acc += A1 * x[n-1] */ + acc += (q63_t) S->A1 * S->state[0]; + + /* acc += A2 * x[n-2] */ + acc += (q63_t) S->A2 * S->state[1]; + + /* convert output to 1.31 format to add y[n-1] */ + out = (q31_t) (acc >> 31U); + + /* out += y[n-1] */ + out += S->state[2]; + + /* Update state */ + S->state[1] = S->state[0]; + S->state[0] = in; + S->state[2] = out; + + /* return to application */ + return (out); + } + + +/** + @ingroup PID + @brief Process function for the Q15 PID Control. + @param[in,out] S points to an instance of the Q15 PID Control structure + @param[in] in input sample to process + @return processed output sample. + + \par Scaling and Overflow Behavior + The function is implemented using a 64-bit internal accumulator. + Both Gains and state variables are represented in 1.15 format and multiplications yield a 2.30 result. + The 2.30 intermediate results are accumulated in a 64-bit accumulator in 34.30 format. + There is no risk of internal overflow with this approach and the full precision of intermediate multiplications is preserved. + After all additions have been performed, the accumulator is truncated to 34.15 format by discarding low 15 bits. + Lastly, the accumulator is saturated to yield a result in 1.15 format. + */ +__STATIC_FORCEINLINE q15_t arm_pid_q15( + arm_pid_instance_q15 * S, + q15_t in) + { + q63_t acc; + q15_t out; + +#if defined (ARM_MATH_DSP) + /* Implementation of PID controller */ + + /* acc = A0 * x[n] */ + acc = (q31_t) __SMUAD((uint32_t)S->A0, (uint32_t)in); + + /* acc += A1 * x[n-1] + A2 * x[n-2] */ + acc = (q63_t)__SMLALD((uint32_t)S->A1, (uint32_t)read_q15x2 (S->state), (uint64_t)acc); +#else + /* acc = A0 * x[n] */ + acc = ((q31_t) S->A0) * in; + + /* acc += A1 * x[n-1] + A2 * x[n-2] */ + acc += (q31_t) S->A1 * S->state[0]; + acc += (q31_t) S->A2 * S->state[1]; +#endif + + /* acc += y[n-1] */ + acc += (q31_t) S->state[2] << 15; + + /* saturate the output */ + out = (q15_t) (__SSAT((q31_t)(acc >> 15), 16)); + + /* Update state */ + S->state[1] = S->state[0]; + S->state[0] = in; + S->state[2] = out; + + /* return to application */ + return (out); + } + + + + /** + * @ingroup groupController + */ + + /** + * @defgroup park Vector Park Transform + * + * Forward Park transform converts the input two-coordinate vector to flux and torque components. + * The Park transform can be used to realize the transformation of the
Ialpha and the Ibeta currents
+ * from the stationary to the moving reference frame and control the spatial relationship between
+ * the stator vector current and rotor flux vector.
+ * If we consider the d axis aligned with the rotor flux, the diagram below shows the
+ * current vector and the relationship from the two reference frames:
+ * \image html park.gif "Stator current space vector and its component in (a,b) and in the d,q rotating reference frame"
+ *
+ * The function operates on a single sample of data and each call to the function returns the processed output.
+ * The library provides separate functions for Q31 and floating-point data types.
+ * \par Algorithm
+ * \image html parkFormula.gif
+ * where Ialpha and Ibeta are the stator vector components,
+ * pId and pIq are rotor vector components and cosVal and sinVal are the
+ * cosine and sine values of theta (rotor flux position).
+ * \par Fixed-Point Behavior
+ * Care must be taken when using the Q31 version of the Park transform.
+ * In particular, the overflow and saturation behavior of the accumulator used must be considered.
+ * Refer to the function specific documentation below for usage guidelines.
+ */
+
+
+
+ /**
+ * @ingroup park
+ * @brief Floating-point Park transform
+ * @param[in] Ialpha input two-phase vector coordinate alpha
+ * @param[in] Ibeta input two-phase vector coordinate beta
+ * @param[out] pId points to output rotor reference frame d
+ * @param[out] pIq points to output rotor reference frame q
+ * @param[in] sinVal sine value of rotation angle theta
+ * @param[in] cosVal cosine value of rotation angle theta
+ * @return none
+ *
+ * The function implements the forward Park transform.
+ *
+ */
+ __STATIC_FORCEINLINE void arm_park_f32(
+ float32_t Ialpha,
+ float32_t Ibeta,
+ float32_t * pId,
+ float32_t * pIq,
+ float32_t sinVal,
+ float32_t cosVal)
+ {
+ /* Calculate pId using the equation, pId = Ialpha * cosVal + Ibeta * sinVal */
+ *pId = Ialpha * cosVal + Ibeta * sinVal;
+
+ /* Calculate pIq using the equation, pIq = - Ialpha * sinVal + Ibeta * cosVal */
+ *pIq = -Ialpha * sinVal + Ibeta * cosVal;
+ }
+
+
+/**
+ @ingroup park
+ @brief Park transform for Q31 version
+ @param[in] Ialpha input two-phase vector coordinate alpha
+ @param[in] Ibeta input two-phase vector coordinate beta
+ @param[out] pId points to output rotor reference frame d
+ @param[out] pIq points to output rotor reference frame q
+ @param[in] sinVal sine value of rotation angle theta
+ @param[in] cosVal cosine value of rotation angle theta
+ @return none
+
+ \par Scaling and Overflow Behavior
+ The function is implemented using an internal 32-bit accumulator.
+ The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
+ There is saturation on the addition and subtraction, hence there is no risk of overflow.
+ */
+__STATIC_FORCEINLINE void arm_park_q31(
+ q31_t Ialpha,
+ q31_t Ibeta,
+ q31_t * pId,
+ q31_t * pIq,
+ q31_t sinVal,
+ q31_t cosVal)
+ {
+ q31_t product1, product2; /* Temporary variables used to store intermediate results */
+ q31_t product3, product4; /* Temporary variables used to store intermediate results */
+
+ /* Intermediate product is calculated by (Ialpha * cosVal) */
+ product1 = (q31_t) (((q63_t) (Ialpha) * (cosVal)) >> 31);
+
+ /* Intermediate product is calculated by (Ibeta * sinVal) */
+ product2 = (q31_t) (((q63_t) (Ibeta) * (sinVal)) >> 31);
+
+
+ /* Intermediate product is calculated by (Ialpha * sinVal) */
+ product3 = (q31_t) (((q63_t) (Ialpha) * (sinVal)) >> 31);
+
+ /* Intermediate product is calculated by (Ibeta * cosVal) */
+ product4 = (q31_t) (((q63_t) (Ibeta) * (cosVal)) >> 31);
+
+ /* Calculate pId by adding the two intermediate products 1 and 2 */
+ *pId = __QADD(product1, product2);
+
+ /* Calculate pIq by subtracting the two intermediate products 3 from 4 */
+ *pIq = __QSUB(product4, product3);
+ }
+
+
+
+ /**
+ * @ingroup groupController
+ */
+
+ /**
+ * @defgroup inv_park Vector Inverse Park transform
+ * Inverse Park transform converts the input flux and torque components to two-coordinate vector.
+ *
+ * The function operates on a single sample of data and each call to the function returns the processed output.
+ * The library provides separate functions for Q31 and floating-point data types.
+ * \par Algorithm
+ * \image html parkInvFormula.gif
+ * where pIalpha and pIbeta are the stator vector components,
+ * Id and Iq are rotor vector components and cosVal and sinVal are the
+ * cosine and sine values of theta (rotor flux position).
+ * \par Fixed-Point Behavior
+ * Care must be taken when using the Q31 version of the Park transform.
+ * In particular, the overflow and saturation behavior of the accumulator used must be considered.
+ * Refer to the function specific documentation below for usage guidelines.
+ */
+
+
+
+ /**
+ * @ingroup inv_park
+ * @brief Floating-point Inverse Park transform
+ * @param[in] Id input coordinate of rotor reference frame d
+ * @param[in] Iq input coordinate of rotor reference frame q
+ * @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
+ * @param[out] pIbeta points to output two-phase orthogonal vector axis beta
+ * @param[in] sinVal sine value of rotation angle theta
+ * @param[in] cosVal cosine value of rotation angle theta
+ * @return none
+ */
+ __STATIC_FORCEINLINE void arm_inv_park_f32(
+ float32_t Id,
+ float32_t Iq,
+ float32_t * pIalpha,
+ float32_t * pIbeta,
+ float32_t sinVal,
+ float32_t cosVal)
+ {
+ /* Calculate pIalpha using the equation, pIalpha = Id * cosVal - Iq * sinVal */
+ *pIalpha = Id * cosVal - Iq * sinVal;
+
+ /* Calculate pIbeta using the equation, pIbeta = Id * sinVal + Iq * cosVal */
+ *pIbeta = Id * sinVal + Iq * cosVal;
+ }
+
+
+/**
+ @ingroup inv_park
+ @brief Inverse Park transform for Q31 version
+ @param[in] Id input coordinate of rotor reference frame d
+ @param[in] Iq input coordinate of rotor reference frame q
+ @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
+ @param[out] pIbeta points to output two-phase orthogonal vector axis beta
+ @param[in] sinVal sine value of rotation angle theta
+ @param[in] cosVal cosine value of rotation angle theta
+ @return none
+
+ @par Scaling and Overflow Behavior
+ The function is implemented using an internal 32-bit accumulator.
+ The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
+ There is saturation on the addition, hence there is no risk of overflow.
+ */
+__STATIC_FORCEINLINE void arm_inv_park_q31(
+ q31_t Id,
+ q31_t Iq,
+ q31_t * pIalpha,
+ q31_t * pIbeta,
+ q31_t sinVal,
+ q31_t cosVal)
+ {
+ q31_t product1, product2; /* Temporary variables used to store intermediate results */
+ q31_t product3, product4; /* Temporary variables used to store intermediate results */
+
+ /* Intermediate product is calculated by (Id * cosVal) */
+ product1 = (q31_t) (((q63_t) (Id) * (cosVal)) >> 31);
+
+ /* Intermediate product is calculated by (Iq * sinVal) */
+ product2 = (q31_t) (((q63_t) (Iq) * (sinVal)) >> 31);
+
+
+ /* Intermediate product is calculated by (Id * sinVal) */
+ product3 = (q31_t) (((q63_t) (Id) * (sinVal)) >> 31);
+
+ /* Intermediate product is calculated by (Iq * cosVal) */
+ product4 = (q31_t) (((q63_t) (Iq) * (cosVal)) >> 31);
+
+ /* Calculate pIalpha by using the two intermediate products 1 and 2 */
+ *pIalpha = __QSUB(product1, product2);
+
+ /* Calculate pIbeta by using the two intermediate products 3 and 4 */
+ *pIbeta = __QADD(product4, product3);
+ }
+
+
+/**
+ * @ingroup groupController
+ */
+
+ /**
+ * @defgroup clarke Vector Clarke Transform
+ * Forward Clarke transform converts the instantaneous stator phases into a two-coordinate time invariant vector.
+ * Generally the Clarke transform uses three-phase currents Ia, Ib and Ic to calculate currents
+ * in the two-phase orthogonal stator axis Ialpha and Ibeta.
+ * When Ialpha is superposed with Ia as shown in the figure below
+ * \image html clarke.gif Stator current space vector and its components in (a,b).
+ * and Ia + Ib + Ic = 0, in this condition Ialpha and Ibeta
+ * can be calculated using only Ia and Ib.
+ *
+ * The function operates on a single sample of data and each call to the function returns the processed output.
+ * The library provides separate functions for Q31 and floating-point data types.
+ * \par Algorithm
+ * \image html clarkeFormula.gif
+ * where Ia and Ib are the instantaneous stator phases and
+ * pIalpha and pIbeta are the two coordinates of time invariant vector.
+ * \par Fixed-Point Behavior
+ * Care must be taken when using the Q31 version of the Clarke transform.
+ * In particular, the overflow and saturation behavior of the accumulator used must be considered.
+ * Refer to the function specific documentation below for usage guidelines.
+ */
+
+
+ /**
+ *
+ * @ingroup clarke
+ * @brief Floating-point Clarke transform
+ * @param[in] Ia input three-phase coordinate a
+ * @param[in] Ib input three-phase coordinate b
+ * @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
+ * @param[out] pIbeta points to output two-phase orthogonal vector axis beta
+ * @return none
+ */
+ __STATIC_FORCEINLINE void arm_clarke_f32(
+ float32_t Ia,
+ float32_t Ib,
+ float32_t * pIalpha,
+ float32_t * pIbeta)
+ {
+ /* Calculate pIalpha using the equation, pIalpha = Ia */
+ *pIalpha = Ia;
+
+ /* Calculate pIbeta using the equation, pIbeta = (1/sqrt(3)) * Ia + (2/sqrt(3)) * Ib */
+ *pIbeta = (0.57735026919f * Ia + 1.15470053838f * Ib);
+ }
+
+
+/**
+ @ingroup clarke
+ @brief Clarke transform for Q31 version
+ @param[in] Ia input three-phase coordinate a
+ @param[in] Ib input three-phase coordinate b
+ @param[out] pIalpha points to output two-phase orthogonal vector axis alpha
+ @param[out] pIbeta points to output two-phase orthogonal vector axis beta
+ @return none
+
+ \par Scaling and Overflow Behavior
+ The function is implemented using an internal 32-bit accumulator.
+ The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
+ There is saturation on the addition, hence there is no risk of overflow.
+ */
+__STATIC_FORCEINLINE void arm_clarke_q31(
+ q31_t Ia,
+ q31_t Ib,
+ q31_t * pIalpha,
+ q31_t * pIbeta)
+ {
+ q31_t product1, product2; /* Temporary variables used to store intermediate results */
+
+ /* Calculating pIalpha from Ia by equation pIalpha = Ia */
+ *pIalpha = Ia;
+
+ /* Intermediate product is calculated by (1/(sqrt(3)) * Ia) */
+ product1 = (q31_t) (((q63_t) Ia * 0x24F34E8B) >> 30);
+
+ /* Intermediate product is calculated by (2/sqrt(3) * Ib) */
+ product2 = (q31_t) (((q63_t) Ib * 0x49E69D16) >> 30);
+
+ /* pIbeta is calculated by adding the intermediate products */
+ *pIbeta = __QADD(product1, product2);
+ }
+
+
+
+ /**
+ * @ingroup groupController
+ */
+
+ /**
+ * @defgroup inv_clarke Vector Inverse Clarke Transform
+ * Inverse Clarke transform converts the two-coordinate time invariant vector into instantaneous stator phases.
+ *
+ * The function operates on a single sample of data and each call to the function returns the processed output.
+ * The library provides separate functions for Q31 and floating-point data types.
+ * \par Algorithm
+ * \image html clarkeInvFormula.gif
+ * where pIa and pIb are the instantaneous stator phases and
+ * Ialpha and Ibeta are the two coordinates of time invariant vector.
+ * \par Fixed-Point Behavior
+ * Care must be taken when using the Q31 version of the Clarke transform.
+ * In particular, the overflow and saturation behavior of the accumulator used must be considered.
+ * Refer to the function specific documentation below for usage guidelines.
+ */
+
+
+
+ /**
+ * @ingroup inv_clarke
+ * @brief Floating-point Inverse Clarke transform
+ * @param[in] Ialpha input two-phase orthogonal vector axis alpha
+ * @param[in] Ibeta input two-phase orthogonal vector axis beta
+ * @param[out] pIa points to output three-phase coordinate a
+ * @param[out] pIb points to output three-phase coordinate b
+ * @return none
+ */
+ __STATIC_FORCEINLINE void arm_inv_clarke_f32(
+ float32_t Ialpha,
+ float32_t Ibeta,
+ float32_t * pIa,
+ float32_t * pIb)
+ {
+ /* Calculating pIa from Ialpha by equation pIa = Ialpha */
+ *pIa = Ialpha;
+
+ /* Calculating pIb from Ialpha and Ibeta by equation pIb = -(1/2) * Ialpha + (sqrt(3)/2) * Ibeta */
+ *pIb = -0.5f * Ialpha + 0.8660254039f * Ibeta;
+ }
+
+
+/**
+ @ingroup inv_clarke
+ @brief Inverse Clarke transform for Q31 version
+ @param[in] Ialpha input two-phase orthogonal vector axis alpha
+ @param[in] Ibeta input two-phase orthogonal vector axis beta
+ @param[out] pIa points to output three-phase coordinate a
+ @param[out] pIb points to output three-phase coordinate b
+ @return none
+
+ \par Scaling and Overflow Behavior
+ The function is implemented using an internal 32-bit accumulator.
+ The accumulator maintains 1.31 format by truncating lower 31 bits of the intermediate multiplication in 2.62 format.
+ There is saturation on the subtraction, hence there is no risk of overflow.
+ */
+__STATIC_FORCEINLINE void arm_inv_clarke_q31(
+ q31_t Ialpha,
+ q31_t Ibeta,
+ q31_t * pIa,
+ q31_t * pIb)
+ {
+ q31_t product1, product2; /* Temporary variables used to store intermediate results */
+
+ /* Calculating pIa from Ialpha by equation pIa = Ialpha */
+ *pIa = Ialpha;
+
+ /* Intermediate product is calculated by (1/(2*sqrt(3)) * Ia) */
+ product1 = (q31_t) (((q63_t) (Ialpha) * (0x40000000)) >> 31);
+
+ /* Intermediate product is calculated by (1/sqrt(3) * pIb) */
+ product2 = (q31_t) (((q63_t) (Ibeta) * (0x6ED9EBA1)) >> 31);
+
+ /* pIb is calculated by subtracting the products */
+ *pIb = __QSUB(product2, product1);
+ }
+
+
+
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _CONTROLLER_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/controller_functions_f16.h b/Middlewares/ST/ARM/DSP/Include/dsp/controller_functions_f16.h
new file mode 100644
index 0000000..8fae483
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/controller_functions_f16.h
@@ -0,0 +1,41 @@
+/******************************************************************************
+ * @file controller_functions_f16.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _CONTROLLER_FUNCTIONS_F16_H_
+#define _CONTROLLER_FUNCTIONS_F16_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if defined(ARM_FLOAT16_SUPPORTED)
+#endif /*defined(ARM_FLOAT16_SUPPORTED)*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _CONTROLLER_FUNCTIONS_F16_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/debug.h b/Middlewares/ST/ARM/DSP/Include/dsp/debug.h
new file mode 100644
index 0000000..c95804c
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/debug.h
@@ -0,0 +1,146 @@
+/******************************************************************************
+ * @file basic_math_functions.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _DEBUG_FUNCTIONS_H_
+#define _DEBUG_FUNCTIONS_H_
+
+#include "arm_math_types.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#include "dsp/matrix_functions.h"
+#include "dsp/matrix_functions_f16.h"
+
+#include + * x1 = x0 - f(x0)/f'(x0) + *+ * where
x1 is the current estimate,
+ * x0 is the previous estimate, and
+ * f'(x0) is the derivative of f() evaluated at x0.
+ * For the square root function, the algorithm reduces to:
+ * + * x0 = in/2 [initial guess] + * x1 = 1/2 * ( x0 + in / x0) [each iteration] + *+ */ + + + /** + * @addtogroup SQRT + * @{ + */ + +/** + @brief Floating-point square root function. + @param[in] in input value + @param[out] pOut square root of input value + @return execution status + - \ref ARM_MATH_SUCCESS : input value is positive + - \ref ARM_MATH_ARGUMENT_ERROR : input value is negative; *pOut is set to 0 + */ +__STATIC_FORCEINLINE arm_status arm_sqrt_f32( + const float32_t in, + float32_t * pOut) + { + if (in >= 0.0f) + { +#if defined ( __CC_ARM ) + #if defined __TARGET_FPU_VFP + *pOut = __sqrtf(in); + #else + *pOut = sqrtf(in); + #endif + +#elif defined ( __ICCARM__ ) + #if defined __ARMVFP__ + __ASM("VSQRT.F32 %0,%1" : "=t"(*pOut) : "t"(in)); + #else + *pOut = sqrtf(in); + #endif + +#elif defined ( __ARMCC_VERSION ) && ( __ARMCC_VERSION >= 6010050 ) + *pOut = _sqrtf(in); +#elif defined(__GNUC_PYTHON__) + *pOut = sqrtf(in); +#elif defined ( __GNUC__ ) + #if defined (__VFP_FP__) && !defined(__SOFTFP__) + __ASM("VSQRT.F32 %0,%1" : "=t"(*pOut) : "t"(in)); + #else + *pOut = sqrtf(in); + #endif +#else + *pOut = sqrtf(in); +#endif + + return (ARM_MATH_SUCCESS); + } + else + { + *pOut = 0.0f; + return (ARM_MATH_ARGUMENT_ERROR); + } + } + + +/** + @brief Q31 square root function. + @param[in] in input value. The range of the input value is [0 +1) or 0x00000000 to 0x7FFFFFFF + @param[out] pOut points to square root of input value + @return execution status + - \ref ARM_MATH_SUCCESS : input value is positive + - \ref ARM_MATH_ARGUMENT_ERROR : input value is negative; *pOut is set to 0 + */ +arm_status arm_sqrt_q31( + q31_t in, + q31_t * pOut); + + +/** + @brief Q15 square root function. + @param[in] in input value. The range of the input value is [0 +1) or 0x0000 to 0x7FFF + @param[out] pOut points to square root of input value + @return execution status + - \ref ARM_MATH_SUCCESS : input value is positive + - \ref ARM_MATH_ARGUMENT_ERROR : input value is negative; *pOut is set to 0 + */ +arm_status arm_sqrt_q15( + q15_t in, + q15_t * pOut); + + + + /** + * @} end of SQRT group + */ + + /** + @brief Fixed point division + @param[in] numerator Numerator + @param[in] denominator Denominator + @param[out] quotient Quotient value normalized between -1.0 and 1.0 + @param[out] shift Shift left value to get the unnormalized quotient + @return error status + + When dividing by 0, an error ARM_MATH_NANINF is returned. And the quotient is forced + to the saturated negative or positive value. + */ + +arm_status arm_divide_q15(q15_t numerator, + q15_t denominator, + q15_t *quotient, + int16_t *shift); + + /** + @brief Fixed point division + @param[in] numerator Numerator + @param[in] denominator Denominator + @param[out] quotient Quotient value normalized between -1.0 and 1.0 + @param[out] shift Shift left value to get the unnormalized quotient + @return error status + + When dividing by 0, an error ARM_MATH_NANINF is returned. And the quotient is forced + to the saturated negative or positive value. + */ + +arm_status arm_divide_q31(q31_t numerator, + q31_t denominator, + q31_t *quotient, + int16_t *shift); + + + + /** + @brief Arc tangent in radian of y/x using sign of x and y to determine right quadrant. + @param[in] y y coordinate + @param[in] x x coordinate + @param[out] result Result + @return error status. + */ + arm_status arm_atan2_f32(float32_t y,float32_t x,float32_t *result); + + + /** + @brief Arc tangent in radian of y/x using sign of x and y to determine right quadrant. + @param[in] y y coordinate + @param[in] x x coordinate + @param[out] result Result in Q2.29 + @return error status. + */ + arm_status arm_atan2_q31(q31_t y,q31_t x,q31_t *result); + + /** + @brief Arc tangent in radian of y/x using sign of x and y to determine right quadrant. + @param[in] y y coordinate + @param[in] x x coordinate + @param[out] result Result in Q2.13 + @return error status. + */ + arm_status arm_atan2_q15(q15_t y,q15_t x,q15_t *result); + +#ifdef __cplusplus +} +#endif + +#endif /* ifndef _FAST_MATH_FUNCTIONS_H_ */ diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/fast_math_functions_f16.h b/Middlewares/ST/ARM/DSP/Include/dsp/fast_math_functions_f16.h new file mode 100644 index 0000000..46ae06d --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/dsp/fast_math_functions_f16.h @@ -0,0 +1,125 @@ +/****************************************************************************** + * @file fast_math_functions_f16.h + * @brief Public header file for CMSIS DSP Library + * @version V1.10.0 + * @date 08 July 2021 + * Target Processor: Cortex-M and Cortex-A cores + ******************************************************************************/ +/* + * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _FAST_MATH_FUNCTIONS_F16_H_ +#define _FAST_MATH_FUNCTIONS_F16_H_ + +#include "arm_math_types_f16.h" +#include "arm_math_memory.h" + +#include "dsp/none.h" +#include "dsp/utils.h" + +/* For sqrt_f32 */ +#include "dsp/fast_math_functions.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if defined(ARM_FLOAT16_SUPPORTED) + + /** + * @addtogroup SQRT + * @{ + */ + +/** + @brief Floating-point square root function. + @param[in] in input value + @param[out] pOut square root of input value + @return execution status + - \ref ARM_MATH_SUCCESS : input value is positive + - \ref ARM_MATH_ARGUMENT_ERROR : input value is negative; *pOut is set to 0 + */ +__STATIC_FORCEINLINE arm_status arm_sqrt_f16( + float16_t in, + float16_t * pOut) + { + float32_t r; + arm_status status; + status=arm_sqrt_f32((float32_t)in,&r); + *pOut=(float16_t)r; + return(status); + } + + +/** + @} end of SQRT group + */ + +/** + @brief Floating-point vector of log values. + @param[in] pSrc points to the input vector + @param[out] pDst points to the output vector + @param[in] blockSize number of samples in each vector + @return none + */ + void arm_vlog_f16( + const float16_t * pSrc, + float16_t * pDst, + uint32_t blockSize); + +/** + @brief Floating-point vector of exp values. + @param[in] pSrc points to the input vector + @param[out] pDst points to the output vector + @param[in] blockSize number of samples in each vector + @return none + */ + void arm_vexp_f16( + const float16_t * pSrc, + float16_t * pDst, + uint32_t blockSize); + + /** + @brief Floating-point vector of inverse values. + @param[in] pSrc points to the input vector + @param[out] pDst points to the output vector + @param[in] blockSize number of samples in each vector + @return none + */ + void arm_vinverse_f16( + const float16_t * pSrc, + float16_t * pDst, + uint32_t blockSize); + + /** + @brief Arc tangent in radian of y/x using sign of x and y to determine right quadrant. + @param[in] y y coordinate + @param[in] x x coordinate + @param[out] result Result + @return error status. + */ + arm_status arm_atan2_f16(float16_t y,float16_t x,float16_t *result); + +#endif /*defined(ARM_FLOAT16_SUPPORTED)*/ +#ifdef __cplusplus +} +#endif + +#endif /* ifndef _FAST_MATH_FUNCTIONS_F16_H_ */ diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/filtering_functions.h b/Middlewares/ST/ARM/DSP/Include/dsp/filtering_functions.h new file mode 100644 index 0000000..28a9568 --- /dev/null +++ b/Middlewares/ST/ARM/DSP/Include/dsp/filtering_functions.h @@ -0,0 +1,2529 @@ +/****************************************************************************** + * @file filtering_functions.h + * @brief Public header file for CMSIS DSP Library + * @version V1.10.0 + * @date 08 July 2021 + * Target Processor: Cortex-M and Cortex-A cores + ******************************************************************************/ +/* + * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the License); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#ifndef _FILTERING_FUNCTIONS_H_ +#define _FILTERING_FUNCTIONS_H_ + +#include "arm_math_types.h" +#include "arm_math_memory.h" + +#include "dsp/none.h" +#include "dsp/utils.h" + +#include "dsp/support_functions.h" +#include "dsp/fast_math_functions.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + + +#define DELTA_Q31 ((q31_t)(0x100)) +#define DELTA_Q15 ((q15_t)0x5) + +/** + * @defgroup groupFilters Filtering Functions + */ + + /** + * @brief Instance structure for the Q7 FIR filter. + */ + typedef struct + { + uint16_t numTaps; /**< number of filter coefficients in the filter. */ + q7_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ + const q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ + } arm_fir_instance_q7; + + /** + * @brief Instance structure for the Q15 FIR filter. + */ + typedef struct + { + uint16_t numTaps; /**< number of filter coefficients in the filter. */ + q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ + const q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/ + } arm_fir_instance_q15; + + /** + * @brief Instance structure for the Q31 FIR filter. + */ + typedef struct + { + uint16_t numTaps; /**< number of filter coefficients in the filter. */ + q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ + const q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ + } arm_fir_instance_q31; + + /** + * @brief Instance structure for the floating-point FIR filter. + */ + typedef struct + { + uint16_t numTaps; /**< number of filter coefficients in the filter. */ + float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ + const float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ + } arm_fir_instance_f32; + + /** + * @brief Instance structure for the floating-point FIR filter. + */ + typedef struct + { + uint16_t numTaps; /**< number of filter coefficients in the filter. */ + float64_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */ + const float64_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */ + } arm_fir_instance_f64; + + /** + * @brief Processing function for the Q7 FIR filter. + * @param[in] S points to an instance of the Q7 FIR filter structure. + * @param[in] pSrc points to the block of input data. + * @param[out] pDst points to the block of output data. + * @param[in] blockSize number of samples to process. + */ + void arm_fir_q7( + const arm_fir_instance_q7 * S, + const q7_t * pSrc, + q7_t * pDst, + uint32_t blockSize); + + /** + * @brief Initialization function for the Q7 FIR filter. + * @param[in,out] S points to an instance of the Q7 FIR structure. + * @param[in] numTaps Number of filter coefficients in the filter. + * @param[in] pCoeffs points to the filter coefficients. + * @param[in] pState points to the state buffer. + * @param[in] blockSize number of samples that are processed. + * + * For the MVE version, the coefficient length must be a multiple of 16. + * You can pad with zeros if you have less coefficients. + */ + void arm_fir_init_q7( + arm_fir_instance_q7 * S, + uint16_t numTaps, + const q7_t * pCoeffs, + q7_t * pState, + uint32_t blockSize); + + /** + * @brief Processing function for the Q15 FIR filter. + * @param[in] S points to an instance of the Q15 FIR structure. + * @param[in] pSrc points to the block of input data. + * @param[out] pDst points to the block of output data. + * @param[in] blockSize number of samples to process. + */ + void arm_fir_q15( + const arm_fir_instance_q15 * S, + const q15_t * pSrc, + q15_t * pDst, + uint32_t blockSize); + + /** + * @brief Processing function for the fast Q15 FIR filter (fast version). + * @param[in] S points to an instance of the Q15 FIR filter structure. + * @param[in] pSrc points to the block of input data. + * @param[out] pDst points to the block of output data. + * @param[in] blockSize number of samples to process. + */ + void arm_fir_fast_q15( + const arm_fir_instance_q15 * S, + const q15_t * pSrc, + q15_t * pDst, + uint32_t blockSize); + + /** + * @brief Initialization function for the Q15 FIR filter. + * @param[in,out] S points to an instance of the Q15 FIR filter structure. + * @param[in] numTaps Number of filter coefficients in the filter. Must be even and greater than or equal to 4. + * @param[in] pCoeffs points to the filter coefficients. + * @param[in] pState points to the state buffer. + * @param[in] blockSize number of samples that are processed at a time. + * @return The function returns either + *
ARM_MATH_SUCCESS if initialization was successful or
+ * ARM_MATH_ARGUMENT_ERROR if numTaps is not a supported value.
+ *
+ * For the MVE version, the coefficient length must be a multiple of 8.
+ * You can pad with zeros if you have less coefficients.
+ *
+ */
+ arm_status arm_fir_init_q15(
+ arm_fir_instance_q15 * S,
+ uint16_t numTaps,
+ const q15_t * pCoeffs,
+ q15_t * pState,
+ uint32_t blockSize);
+
+ /**
+ * @brief Processing function for the Q31 FIR filter.
+ * @param[in] S points to an instance of the Q31 FIR filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_q31(
+ const arm_fir_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Processing function for the fast Q31 FIR filter (fast version).
+ * @param[in] S points to an instance of the Q31 FIR filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_fast_q31(
+ const arm_fir_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Initialization function for the Q31 FIR filter.
+ * @param[in,out] S points to an instance of the Q31 FIR structure.
+ * @param[in] numTaps Number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of samples that are processed at a time.
+ *
+ * For the MVE version, the coefficient length must be a multiple of 4.
+ * You can pad with zeros if you have less coefficients.
+ */
+ void arm_fir_init_q31(
+ arm_fir_instance_q31 * S,
+ uint16_t numTaps,
+ const q31_t * pCoeffs,
+ q31_t * pState,
+ uint32_t blockSize);
+
+ /**
+ * @brief Processing function for the floating-point FIR filter.
+ * @param[in] S points to an instance of the floating-point FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_f32(
+ const arm_fir_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Processing function for the floating-point FIR filter.
+ * @param[in] S points to an instance of the floating-point FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_f64(
+ const arm_fir_instance_f64 * S,
+ const float64_t * pSrc,
+ float64_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Initialization function for the floating-point FIR filter.
+ * @param[in,out] S points to an instance of the floating-point FIR filter structure.
+ * @param[in] numTaps Number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of samples that are processed at a time.
+ */
+ void arm_fir_init_f32(
+ arm_fir_instance_f32 * S,
+ uint16_t numTaps,
+ const float32_t * pCoeffs,
+ float32_t * pState,
+ uint32_t blockSize);
+
+ /**
+ * @brief Initialization function for the floating-point FIR filter.
+ * @param[in,out] S points to an instance of the floating-point FIR filter structure.
+ * @param[in] numTaps Number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of samples that are processed at a time.
+ */
+ void arm_fir_init_f64(
+ arm_fir_instance_f64 * S,
+ uint16_t numTaps,
+ const float64_t * pCoeffs,
+ float64_t * pState,
+ uint32_t blockSize);
+
+ /**
+ * @brief Instance structure for the Q15 Biquad cascade filter.
+ */
+ typedef struct
+ {
+ int8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ q15_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
+ const q15_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
+ int8_t postShift; /**< Additional shift, in bits, applied to each output sample. */
+ } arm_biquad_casd_df1_inst_q15;
+
+ /**
+ * @brief Instance structure for the Q31 Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ q31_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
+ const q31_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
+ uint8_t postShift; /**< Additional shift, in bits, applied to each output sample. */
+ } arm_biquad_casd_df1_inst_q31;
+
+ /**
+ * @brief Instance structure for the floating-point Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float32_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
+ const float32_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_casd_df1_inst_f32;
+
+#if defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE)
+ /**
+ * @brief Instance structure for the modified Biquad coefs required by vectorized code.
+ */
+ typedef struct
+ {
+ float32_t coeffs[8][4]; /**< Points to the array of modified coefficients. The array is of length 32. There is one per stage */
+ } arm_biquad_mod_coef_f32;
+#endif
+
+ /**
+ * @brief Processing function for the Q15 Biquad cascade filter.
+ * @param[in] S points to an instance of the Q15 Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_q15(
+ const arm_biquad_casd_df1_inst_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Initialization function for the Q15 Biquad cascade filter.
+ * @param[in,out] S points to an instance of the Q15 Biquad cascade structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format
+ */
+ void arm_biquad_cascade_df1_init_q15(
+ arm_biquad_casd_df1_inst_q15 * S,
+ uint8_t numStages,
+ const q15_t * pCoeffs,
+ q15_t * pState,
+ int8_t postShift);
+
+ /**
+ * @brief Fast but less precise processing function for the Q15 Biquad cascade filter for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q15 Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_fast_q15(
+ const arm_biquad_casd_df1_inst_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Processing function for the Q31 Biquad cascade filter
+ * @param[in] S points to an instance of the Q31 Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_q31(
+ const arm_biquad_casd_df1_inst_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Fast but less precise processing function for the Q31 Biquad cascade filter for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q31 Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_fast_q31(
+ const arm_biquad_casd_df1_inst_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Initialization function for the Q31 Biquad cascade filter.
+ * @param[in,out] S points to an instance of the Q31 Biquad cascade structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] postShift Shift to be applied to the output. Varies according to the coefficients format
+ */
+ void arm_biquad_cascade_df1_init_q31(
+ arm_biquad_casd_df1_inst_q31 * S,
+ uint8_t numStages,
+ const q31_t * pCoeffs,
+ q31_t * pState,
+ int8_t postShift);
+
+ /**
+ * @brief Processing function for the floating-point Biquad cascade filter.
+ * @param[in] S points to an instance of the floating-point Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_f32(
+ const arm_biquad_casd_df1_inst_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Initialization function for the floating-point Biquad cascade filter.
+ * @param[in,out] S points to an instance of the floating-point Biquad cascade structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pCoeffsMod points to the modified filter coefficients (only MVE version).
+ * @param[in] pState points to the state buffer.
+ */
+#if defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE)
+ void arm_biquad_cascade_df1_mve_init_f32(
+ arm_biquad_casd_df1_inst_f32 * S,
+ uint8_t numStages,
+ const float32_t * pCoeffs,
+ arm_biquad_mod_coef_f32 * pCoeffsMod,
+ float32_t * pState);
+#endif
+
+ void arm_biquad_cascade_df1_init_f32(
+ arm_biquad_casd_df1_inst_f32 * S,
+ uint8_t numStages,
+ const float32_t * pCoeffs,
+ float32_t * pState);
+
+
+/**
+ * @brief Convolution of floating-point sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the location where the output result is written. Length srcALen+srcBLen-1.
+ */
+ void arm_conv_f32(
+ const float32_t * pSrcA,
+ uint32_t srcALen,
+ const float32_t * pSrcB,
+ uint32_t srcBLen,
+ float32_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q15 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ * @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
+ */
+ void arm_conv_opt_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+/**
+ * @brief Convolution of Q15 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the location where the output result is written. Length srcALen+srcBLen-1.
+ */
+ void arm_conv_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ */
+ void arm_conv_fast_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ * @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
+ */
+ void arm_conv_fast_opt_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Convolution of Q31 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ */
+ void arm_conv_q31(
+ const q31_t * pSrcA,
+ uint32_t srcALen,
+ const q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ */
+ void arm_conv_fast_q31(
+ const q31_t * pSrcA,
+ uint32_t srcALen,
+ const q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst);
+
+
+ /**
+ * @brief Convolution of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ * @param[in] pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
+ */
+ void arm_conv_opt_q7(
+ const q7_t * pSrcA,
+ uint32_t srcALen,
+ const q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Convolution of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length srcALen+srcBLen-1.
+ */
+ void arm_conv_q7(
+ const q7_t * pSrcA,
+ uint32_t srcALen,
+ const q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst);
+
+
+ /**
+ * @brief Partial convolution of floating-point sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_f32(
+ const float32_t * pSrcA,
+ uint32_t srcALen,
+ const float32_t * pSrcB,
+ uint32_t srcBLen,
+ float32_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q15 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_opt_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Partial convolution of Q15 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_fast_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @param[in] pScratch1 points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer of size min(srcALen, srcBLen).
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_fast_opt_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Partial convolution of Q31 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_q31(
+ const q31_t * pSrcA,
+ uint32_t srcALen,
+ const q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q31 sequences (fast version) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_fast_q31(
+ const q31_t * pSrcA,
+ uint32_t srcALen,
+ const q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Partial convolution of Q7 sequences
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @param[in] pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_opt_q7(
+ const q7_t * pSrcA,
+ uint32_t srcALen,
+ const q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+/**
+ * @brief Partial convolution of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data
+ * @param[in] firstIndex is the first output sample to start with.
+ * @param[in] numPoints is the number of output points to be computed.
+ * @return Returns either ARM_MATH_SUCCESS if the function completed correctly or ARM_MATH_ARGUMENT_ERROR if the requested subset is not in the range [0 srcALen+srcBLen-2].
+ */
+ arm_status arm_conv_partial_q7(
+ const q7_t * pSrcA,
+ uint32_t srcALen,
+ const q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst,
+ uint32_t firstIndex,
+ uint32_t numPoints);
+
+
+ /**
+ * @brief Instance structure for the Q15 FIR decimator.
+ */
+ typedef struct
+ {
+ uint8_t M; /**< decimation factor. */
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ const q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ } arm_fir_decimate_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 FIR decimator.
+ */
+ typedef struct
+ {
+ uint8_t M; /**< decimation factor. */
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ const q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ } arm_fir_decimate_instance_q31;
+
+/**
+ @brief Instance structure for floating-point FIR decimator.
+ */
+typedef struct
+ {
+ uint8_t M; /**< decimation factor. */
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ const float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ } arm_fir_decimate_instance_f32;
+
+
+/**
+ @brief Processing function for floating-point FIR decimator.
+ @param[in] S points to an instance of the floating-point FIR decimator structure
+ @param[in] pSrc points to the block of input data
+ @param[out] pDst points to the block of output data
+ @param[in] blockSize number of samples to process
+ */
+void arm_fir_decimate_f32(
+ const arm_fir_decimate_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+/**
+ @brief Initialization function for the floating-point FIR decimator.
+ @param[in,out] S points to an instance of the floating-point FIR decimator structure
+ @param[in] numTaps number of coefficients in the filter
+ @param[in] M decimation factor
+ @param[in] pCoeffs points to the filter coefficients
+ @param[in] pState points to the state buffer
+ @param[in] blockSize number of input samples to process per call
+ @return execution status
+ - \ref ARM_MATH_SUCCESS : Operation successful
+ - \ref ARM_MATH_LENGTH_ERROR : blockSize is not a multiple of M
+ */
+arm_status arm_fir_decimate_init_f32(
+ arm_fir_decimate_instance_f32 * S,
+ uint16_t numTaps,
+ uint8_t M,
+ const float32_t * pCoeffs,
+ float32_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q15 FIR decimator.
+ * @param[in] S points to an instance of the Q15 FIR decimator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_decimate_q15(
+ const arm_fir_decimate_instance_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q15 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q15 FIR decimator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_decimate_fast_q15(
+ const arm_fir_decimate_instance_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q15 FIR decimator.
+ * @param[in,out] S points to an instance of the Q15 FIR decimator structure.
+ * @param[in] numTaps number of coefficients in the filter.
+ * @param[in] M decimation factor.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * blockSize is not a multiple of M.
+ */
+ arm_status arm_fir_decimate_init_q15(
+ arm_fir_decimate_instance_q15 * S,
+ uint16_t numTaps,
+ uint8_t M,
+ const q15_t * pCoeffs,
+ q15_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 FIR decimator.
+ * @param[in] S points to an instance of the Q31 FIR decimator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_decimate_q31(
+ const arm_fir_decimate_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Processing function for the Q31 FIR decimator (fast variant) for Cortex-M3 and Cortex-M4.
+ * @param[in] S points to an instance of the Q31 FIR decimator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_decimate_fast_q31(
+ const arm_fir_decimate_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 FIR decimator.
+ * @param[in,out] S points to an instance of the Q31 FIR decimator structure.
+ * @param[in] numTaps number of coefficients in the filter.
+ * @param[in] M decimation factor.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * blockSize is not a multiple of M.
+ */
+ arm_status arm_fir_decimate_init_q31(
+ arm_fir_decimate_instance_q31 * S,
+ uint16_t numTaps,
+ uint8_t M,
+ const q31_t * pCoeffs,
+ q31_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q15 FIR interpolator.
+ */
+ typedef struct
+ {
+ uint8_t L; /**< upsample factor. */
+ uint16_t phaseLength; /**< length of each polyphase filter component. */
+ const q15_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */
+ q15_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */
+ } arm_fir_interpolate_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 FIR interpolator.
+ */
+ typedef struct
+ {
+ uint8_t L; /**< upsample factor. */
+ uint16_t phaseLength; /**< length of each polyphase filter component. */
+ const q31_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */
+ q31_t *pState; /**< points to the state variable array. The array is of length blockSize+phaseLength-1. */
+ } arm_fir_interpolate_instance_q31;
+
+ /**
+ * @brief Instance structure for the floating-point FIR interpolator.
+ */
+ typedef struct
+ {
+ uint8_t L; /**< upsample factor. */
+ uint16_t phaseLength; /**< length of each polyphase filter component. */
+ const float32_t *pCoeffs; /**< points to the coefficient array. The array is of length L*phaseLength. */
+ float32_t *pState; /**< points to the state variable array. The array is of length phaseLength+numTaps-1. */
+ } arm_fir_interpolate_instance_f32;
+
+
+ /**
+ * @brief Processing function for the Q15 FIR interpolator.
+ * @param[in] S points to an instance of the Q15 FIR interpolator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_interpolate_q15(
+ const arm_fir_interpolate_instance_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q15 FIR interpolator.
+ * @param[in,out] S points to an instance of the Q15 FIR interpolator structure.
+ * @param[in] L upsample factor.
+ * @param[in] numTaps number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficient buffer.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * the filter length numTaps is not a multiple of the interpolation factor L.
+ */
+ arm_status arm_fir_interpolate_init_q15(
+ arm_fir_interpolate_instance_q15 * S,
+ uint8_t L,
+ uint16_t numTaps,
+ const q15_t * pCoeffs,
+ q15_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 FIR interpolator.
+ * @param[in] S points to an instance of the Q15 FIR interpolator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_interpolate_q31(
+ const arm_fir_interpolate_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 FIR interpolator.
+ * @param[in,out] S points to an instance of the Q31 FIR interpolator structure.
+ * @param[in] L upsample factor.
+ * @param[in] numTaps number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficient buffer.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * the filter length numTaps is not a multiple of the interpolation factor L.
+ */
+ arm_status arm_fir_interpolate_init_q31(
+ arm_fir_interpolate_instance_q31 * S,
+ uint8_t L,
+ uint16_t numTaps,
+ const q31_t * pCoeffs,
+ q31_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the floating-point FIR interpolator.
+ * @param[in] S points to an instance of the floating-point FIR interpolator structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_interpolate_f32(
+ const arm_fir_interpolate_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point FIR interpolator.
+ * @param[in,out] S points to an instance of the floating-point FIR interpolator structure.
+ * @param[in] L upsample factor.
+ * @param[in] numTaps number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficient buffer.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of input samples to process per call.
+ * @return The function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_LENGTH_ERROR if
+ * the filter length numTaps is not a multiple of the interpolation factor L.
+ */
+ arm_status arm_fir_interpolate_init_f32(
+ arm_fir_interpolate_instance_f32 * S,
+ uint8_t L,
+ uint16_t numTaps,
+ const float32_t * pCoeffs,
+ float32_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the high precision Q31 Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ q63_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */
+ const q31_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ uint8_t postShift; /**< additional shift, in bits, applied to each output sample. */
+ } arm_biquad_cas_df1_32x64_ins_q31;
+
+
+ /**
+ * @param[in] S points to an instance of the high precision Q31 Biquad cascade filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cas_df1_32x64_q31(
+ const arm_biquad_cas_df1_32x64_ins_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @param[in,out] S points to an instance of the high precision Q31 Biquad cascade filter structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] postShift shift to be applied to the output. Varies according to the coefficients format
+ */
+ void arm_biquad_cas_df1_32x64_init_q31(
+ arm_biquad_cas_df1_32x64_ins_q31 * S,
+ uint8_t numStages,
+ const q31_t * pCoeffs,
+ q63_t * pState,
+ uint8_t postShift);
+
+
+ /**
+ * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float32_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */
+ const float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_cascade_df2T_instance_f32;
+
+ /**
+ * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float32_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */
+ const float32_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_cascade_stereo_df2T_instance_f32;
+
+ /**
+ * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float64_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */
+ const float64_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_cascade_df2T_instance_f64;
+
+
+ /**
+ * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in] S points to an instance of the filter data structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df2T_f32(
+ const arm_biquad_cascade_df2T_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. 2 channels
+ * @param[in] S points to an instance of the filter data structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_stereo_df2T_f32(
+ const arm_biquad_cascade_stereo_df2T_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in] S points to an instance of the filter data structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df2T_f64(
+ const arm_biquad_cascade_df2T_instance_f64 * S,
+ const float64_t * pSrc,
+ float64_t * pDst,
+ uint32_t blockSize);
+
+
+#if defined(ARM_MATH_NEON)
+/**
+ @brief Compute new coefficient arrays for use in vectorized filter (Neon only).
+ @param[in] numStages number of 2nd order stages in the filter.
+ @param[in] pCoeffs points to the original filter coefficients.
+ @param[in] pComputedCoeffs points to the new computed coefficients for the vectorized version.
+ @return none
+*/
+void arm_biquad_cascade_df2T_compute_coefs_f32(
+ uint8_t numStages,
+ const float32_t * pCoeffs,
+ float32_t * pComputedCoeffs);
+#endif
+ /**
+ * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in,out] S points to an instance of the filter data structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ */
+ void arm_biquad_cascade_df2T_init_f32(
+ arm_biquad_cascade_df2T_instance_f32 * S,
+ uint8_t numStages,
+ const float32_t * pCoeffs,
+ float32_t * pState);
+
+
+ /**
+ * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in,out] S points to an instance of the filter data structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ */
+ void arm_biquad_cascade_stereo_df2T_init_f32(
+ arm_biquad_cascade_stereo_df2T_instance_f32 * S,
+ uint8_t numStages,
+ const float32_t * pCoeffs,
+ float32_t * pState);
+
+
+ /**
+ * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in,out] S points to an instance of the filter data structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ */
+ void arm_biquad_cascade_df2T_init_f64(
+ arm_biquad_cascade_df2T_instance_f64 * S,
+ uint8_t numStages,
+ const float64_t * pCoeffs,
+ float64_t * pState);
+
+
+ /**
+ * @brief Instance structure for the Q15 FIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of filter stages. */
+ q15_t *pState; /**< points to the state variable array. The array is of length numStages. */
+ const q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */
+ } arm_fir_lattice_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 FIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of filter stages. */
+ q31_t *pState; /**< points to the state variable array. The array is of length numStages. */
+ const q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */
+ } arm_fir_lattice_instance_q31;
+
+ /**
+ * @brief Instance structure for the floating-point FIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of filter stages. */
+ float32_t *pState; /**< points to the state variable array. The array is of length numStages. */
+ const float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numStages. */
+ } arm_fir_lattice_instance_f32;
+
+
+ /**
+ * @brief Initialization function for the Q15 FIR lattice filter.
+ * @param[in] S points to an instance of the Q15 FIR lattice structure.
+ * @param[in] numStages number of filter stages.
+ * @param[in] pCoeffs points to the coefficient buffer. The array is of length numStages.
+ * @param[in] pState points to the state buffer. The array is of length numStages.
+ */
+ void arm_fir_lattice_init_q15(
+ arm_fir_lattice_instance_q15 * S,
+ uint16_t numStages,
+ const q15_t * pCoeffs,
+ q15_t * pState);
+
+
+ /**
+ * @brief Processing function for the Q15 FIR lattice filter.
+ * @param[in] S points to an instance of the Q15 FIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_lattice_q15(
+ const arm_fir_lattice_instance_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 FIR lattice filter.
+ * @param[in] S points to an instance of the Q31 FIR lattice structure.
+ * @param[in] numStages number of filter stages.
+ * @param[in] pCoeffs points to the coefficient buffer. The array is of length numStages.
+ * @param[in] pState points to the state buffer. The array is of length numStages.
+ */
+ void arm_fir_lattice_init_q31(
+ arm_fir_lattice_instance_q31 * S,
+ uint16_t numStages,
+ const q31_t * pCoeffs,
+ q31_t * pState);
+
+
+ /**
+ * @brief Processing function for the Q31 FIR lattice filter.
+ * @param[in] S points to an instance of the Q31 FIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_lattice_q31(
+ const arm_fir_lattice_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+/**
+ * @brief Initialization function for the floating-point FIR lattice filter.
+ * @param[in] S points to an instance of the floating-point FIR lattice structure.
+ * @param[in] numStages number of filter stages.
+ * @param[in] pCoeffs points to the coefficient buffer. The array is of length numStages.
+ * @param[in] pState points to the state buffer. The array is of length numStages.
+ */
+ void arm_fir_lattice_init_f32(
+ arm_fir_lattice_instance_f32 * S,
+ uint16_t numStages,
+ const float32_t * pCoeffs,
+ float32_t * pState);
+
+
+ /**
+ * @brief Processing function for the floating-point FIR lattice filter.
+ * @param[in] S points to an instance of the floating-point FIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_lattice_f32(
+ const arm_fir_lattice_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q15 IIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of stages in the filter. */
+ q15_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */
+ q15_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */
+ q15_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */
+ } arm_iir_lattice_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 IIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of stages in the filter. */
+ q31_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */
+ q31_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */
+ q31_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */
+ } arm_iir_lattice_instance_q31;
+
+ /**
+ * @brief Instance structure for the floating-point IIR lattice filter.
+ */
+ typedef struct
+ {
+ uint16_t numStages; /**< number of stages in the filter. */
+ float32_t *pState; /**< points to the state variable array. The array is of length numStages+blockSize. */
+ float32_t *pkCoeffs; /**< points to the reflection coefficient array. The array is of length numStages. */
+ float32_t *pvCoeffs; /**< points to the ladder coefficient array. The array is of length numStages+1. */
+ } arm_iir_lattice_instance_f32;
+
+
+ /**
+ * @brief Processing function for the floating-point IIR lattice filter.
+ * @param[in] S points to an instance of the floating-point IIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_f32(
+ const arm_iir_lattice_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point IIR lattice filter.
+ * @param[in] S points to an instance of the floating-point IIR lattice structure.
+ * @param[in] numStages number of stages in the filter.
+ * @param[in] pkCoeffs points to the reflection coefficient buffer. The array is of length numStages.
+ * @param[in] pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1.
+ * @param[in] pState points to the state buffer. The array is of length numStages+blockSize-1.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_init_f32(
+ arm_iir_lattice_instance_f32 * S,
+ uint16_t numStages,
+ float32_t * pkCoeffs,
+ float32_t * pvCoeffs,
+ float32_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 IIR lattice filter.
+ * @param[in] S points to an instance of the Q31 IIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_q31(
+ const arm_iir_lattice_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 IIR lattice filter.
+ * @param[in] S points to an instance of the Q31 IIR lattice structure.
+ * @param[in] numStages number of stages in the filter.
+ * @param[in] pkCoeffs points to the reflection coefficient buffer. The array is of length numStages.
+ * @param[in] pvCoeffs points to the ladder coefficient buffer. The array is of length numStages+1.
+ * @param[in] pState points to the state buffer. The array is of length numStages+blockSize.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_init_q31(
+ arm_iir_lattice_instance_q31 * S,
+ uint16_t numStages,
+ q31_t * pkCoeffs,
+ q31_t * pvCoeffs,
+ q31_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q15 IIR lattice filter.
+ * @param[in] S points to an instance of the Q15 IIR lattice structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_iir_lattice_q15(
+ const arm_iir_lattice_instance_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+/**
+ * @brief Initialization function for the Q15 IIR lattice filter.
+ * @param[in] S points to an instance of the fixed-point Q15 IIR lattice structure.
+ * @param[in] numStages number of stages in the filter.
+ * @param[in] pkCoeffs points to reflection coefficient buffer. The array is of length numStages.
+ * @param[in] pvCoeffs points to ladder coefficient buffer. The array is of length numStages+1.
+ * @param[in] pState points to state buffer. The array is of length numStages+blockSize.
+ * @param[in] blockSize number of samples to process per call.
+ */
+ void arm_iir_lattice_init_q15(
+ arm_iir_lattice_instance_q15 * S,
+ uint16_t numStages,
+ q15_t * pkCoeffs,
+ q15_t * pvCoeffs,
+ q15_t * pState,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the floating-point LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ float32_t mu; /**< step size that controls filter coefficient updates. */
+ } arm_lms_instance_f32;
+
+
+ /**
+ * @brief Processing function for floating-point LMS filter.
+ * @param[in] S points to an instance of the floating-point LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_f32(
+ const arm_lms_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pRef,
+ float32_t * pOut,
+ float32_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for floating-point LMS filter.
+ * @param[in] S points to an instance of the floating-point LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to the coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_init_f32(
+ arm_lms_instance_f32 * S,
+ uint16_t numTaps,
+ float32_t * pCoeffs,
+ float32_t * pState,
+ float32_t mu,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q15 LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ q15_t mu; /**< step size that controls filter coefficient updates. */
+ uint32_t postShift; /**< bit shift applied to coefficients. */
+ } arm_lms_instance_q15;
+
+
+ /**
+ * @brief Initialization function for the Q15 LMS filter.
+ * @param[in] S points to an instance of the Q15 LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to the coefficient buffer.
+ * @param[in] pState points to the state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ * @param[in] postShift bit shift applied to coefficients.
+ */
+ void arm_lms_init_q15(
+ arm_lms_instance_q15 * S,
+ uint16_t numTaps,
+ q15_t * pCoeffs,
+ q15_t * pState,
+ q15_t mu,
+ uint32_t blockSize,
+ uint32_t postShift);
+
+
+ /**
+ * @brief Processing function for Q15 LMS filter.
+ * @param[in] S points to an instance of the Q15 LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_q15(
+ const arm_lms_instance_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pRef,
+ q15_t * pOut,
+ q15_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q31 LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ q31_t mu; /**< step size that controls filter coefficient updates. */
+ uint32_t postShift; /**< bit shift applied to coefficients. */
+ } arm_lms_instance_q31;
+
+
+ /**
+ * @brief Processing function for Q31 LMS filter.
+ * @param[in] S points to an instance of the Q15 LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_q31(
+ const arm_lms_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pRef,
+ q31_t * pOut,
+ q31_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for Q31 LMS filter.
+ * @param[in] S points to an instance of the Q31 LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ * @param[in] postShift bit shift applied to coefficients.
+ */
+ void arm_lms_init_q31(
+ arm_lms_instance_q31 * S,
+ uint16_t numTaps,
+ q31_t * pCoeffs,
+ q31_t * pState,
+ q31_t mu,
+ uint32_t blockSize,
+ uint32_t postShift);
+
+
+ /**
+ * @brief Instance structure for the floating-point normalized LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ float32_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ float32_t mu; /**< step size that control filter coefficient updates. */
+ float32_t energy; /**< saves previous frame energy. */
+ float32_t x0; /**< saves previous input sample. */
+ } arm_lms_norm_instance_f32;
+
+
+ /**
+ * @brief Processing function for floating-point normalized LMS filter.
+ * @param[in] S points to an instance of the floating-point normalized LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_norm_f32(
+ arm_lms_norm_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pRef,
+ float32_t * pOut,
+ float32_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for floating-point normalized LMS filter.
+ * @param[in] S points to an instance of the floating-point LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_norm_init_f32(
+ arm_lms_norm_instance_f32 * S,
+ uint16_t numTaps,
+ float32_t * pCoeffs,
+ float32_t * pState,
+ float32_t mu,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the Q31 normalized LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ q31_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ q31_t mu; /**< step size that controls filter coefficient updates. */
+ uint8_t postShift; /**< bit shift applied to coefficients. */
+ const q31_t *recipTable; /**< points to the reciprocal initial value table. */
+ q31_t energy; /**< saves previous frame energy. */
+ q31_t x0; /**< saves previous input sample. */
+ } arm_lms_norm_instance_q31;
+
+
+ /**
+ * @brief Processing function for Q31 normalized LMS filter.
+ * @param[in] S points to an instance of the Q31 normalized LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_norm_q31(
+ arm_lms_norm_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pRef,
+ q31_t * pOut,
+ q31_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for Q31 normalized LMS filter.
+ * @param[in] S points to an instance of the Q31 normalized LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ * @param[in] postShift bit shift applied to coefficients.
+ */
+ void arm_lms_norm_init_q31(
+ arm_lms_norm_instance_q31 * S,
+ uint16_t numTaps,
+ q31_t * pCoeffs,
+ q31_t * pState,
+ q31_t mu,
+ uint32_t blockSize,
+ uint8_t postShift);
+
+
+ /**
+ * @brief Instance structure for the Q15 normalized LMS filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< Number of coefficients in the filter. */
+ q15_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ q15_t mu; /**< step size that controls filter coefficient updates. */
+ uint8_t postShift; /**< bit shift applied to coefficients. */
+ const q15_t *recipTable; /**< Points to the reciprocal initial value table. */
+ q15_t energy; /**< saves previous frame energy. */
+ q15_t x0; /**< saves previous input sample. */
+ } arm_lms_norm_instance_q15;
+
+
+ /**
+ * @brief Processing function for Q15 normalized LMS filter.
+ * @param[in] S points to an instance of the Q15 normalized LMS filter structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[in] pRef points to the block of reference data.
+ * @param[out] pOut points to the block of output data.
+ * @param[out] pErr points to the block of error data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_lms_norm_q15(
+ arm_lms_norm_instance_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pRef,
+ q15_t * pOut,
+ q15_t * pErr,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for Q15 normalized LMS filter.
+ * @param[in] S points to an instance of the Q15 normalized LMS filter structure.
+ * @param[in] numTaps number of filter coefficients.
+ * @param[in] pCoeffs points to coefficient buffer.
+ * @param[in] pState points to state buffer.
+ * @param[in] mu step size that controls filter coefficient updates.
+ * @param[in] blockSize number of samples to process.
+ * @param[in] postShift bit shift applied to coefficients.
+ */
+ void arm_lms_norm_init_q15(
+ arm_lms_norm_instance_q15 * S,
+ uint16_t numTaps,
+ q15_t * pCoeffs,
+ q15_t * pState,
+ q15_t mu,
+ uint32_t blockSize,
+ uint8_t postShift);
+
+
+ /**
+ * @brief Correlation of floating-point sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_f32(
+ const float32_t * pSrcA,
+ uint32_t srcALen,
+ const float32_t * pSrcB,
+ uint32_t srcBLen,
+ float32_t * pDst);
+
+
+ /**
+ * @brief Correlation of floating-point sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_f64(
+ const float64_t * pSrcA,
+ uint32_t srcALen,
+ const float64_t * pSrcB,
+ uint32_t srcBLen,
+ float64_t * pDst);
+
+
+/**
+ @brief Correlation of Q15 sequences
+ @param[in] pSrcA points to the first input sequence
+ @param[in] srcALen length of the first input sequence
+ @param[in] pSrcB points to the second input sequence
+ @param[in] srcBLen length of the second input sequence
+ @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ @param[in] pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+*/
+void arm_correlate_opt_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ q15_t * pScratch);
+
+
+/**
+ @brief Correlation of Q15 sequences.
+ @param[in] pSrcA points to the first input sequence
+ @param[in] srcALen length of the first input sequence
+ @param[in] pSrcB points to the second input sequence
+ @param[in] srcBLen length of the second input sequence
+ @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst);
+
+
+/**
+ @brief Correlation of Q15 sequences (fast version).
+ @param[in] pSrcA points to the first input sequence
+ @param[in] srcALen length of the first input sequence
+ @param[in] pSrcB points to the second input sequence
+ @param[in] srcBLen length of the second input sequence
+ @param[out] pDst points to the location where the output result is written. Length 2 * max(srcALen, srcBLen) - 1.
+ @return none
+ */
+void arm_correlate_fast_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst);
+
+
+/**
+ @brief Correlation of Q15 sequences (fast version).
+ @param[in] pSrcA points to the first input sequence.
+ @param[in] srcALen length of the first input sequence.
+ @param[in] pSrcB points to the second input sequence.
+ @param[in] srcBLen length of the second input sequence.
+ @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ @param[in] pScratch points to scratch buffer of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ */
+void arm_correlate_fast_opt_q15(
+ const q15_t * pSrcA,
+ uint32_t srcALen,
+ const q15_t * pSrcB,
+ uint32_t srcBLen,
+ q15_t * pDst,
+ q15_t * pScratch);
+
+
+ /**
+ * @brief Correlation of Q31 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_q31(
+ const q31_t * pSrcA,
+ uint32_t srcALen,
+ const q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst);
+
+
+/**
+ @brief Correlation of Q31 sequences (fast version).
+ @param[in] pSrcA points to the first input sequence
+ @param[in] srcALen length of the first input sequence
+ @param[in] pSrcB points to the second input sequence
+ @param[in] srcBLen length of the second input sequence
+ @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+void arm_correlate_fast_q31(
+ const q31_t * pSrcA,
+ uint32_t srcALen,
+ const q31_t * pSrcB,
+ uint32_t srcBLen,
+ q31_t * pDst);
+
+
+ /**
+ * @brief Correlation of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ * @param[in] pScratch1 points to scratch buffer(of type q15_t) of size max(srcALen, srcBLen) + 2*min(srcALen, srcBLen) - 2.
+ * @param[in] pScratch2 points to scratch buffer (of type q15_t) of size min(srcALen, srcBLen).
+ */
+ void arm_correlate_opt_q7(
+ const q7_t * pSrcA,
+ uint32_t srcALen,
+ const q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst,
+ q15_t * pScratch1,
+ q15_t * pScratch2);
+
+
+ /**
+ * @brief Correlation of Q7 sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_q7(
+ const q7_t * pSrcA,
+ uint32_t srcALen,
+ const q7_t * pSrcB,
+ uint32_t srcBLen,
+ q7_t * pDst);
+
+
+ /**
+ * @brief Instance structure for the floating-point sparse FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
+ float32_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
+ const float32_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
+ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
+ } arm_fir_sparse_instance_f32;
+
+ /**
+ * @brief Instance structure for the Q31 sparse FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
+ q31_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
+ const q31_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
+ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
+ } arm_fir_sparse_instance_q31;
+
+ /**
+ * @brief Instance structure for the Q15 sparse FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
+ q15_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
+ const q15_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
+ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
+ } arm_fir_sparse_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q7 sparse FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of coefficients in the filter. */
+ uint16_t stateIndex; /**< state buffer index. Points to the oldest sample in the state buffer. */
+ q7_t *pState; /**< points to the state buffer array. The array is of length maxDelay+blockSize-1. */
+ const q7_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps.*/
+ uint16_t maxDelay; /**< maximum offset specified by the pTapDelay array. */
+ int32_t *pTapDelay; /**< points to the array of delay values. The array is of length numTaps. */
+ } arm_fir_sparse_instance_q7;
+
+
+ /**
+ * @brief Processing function for the floating-point sparse FIR filter.
+ * @param[in] S points to an instance of the floating-point sparse FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] pScratchIn points to a temporary buffer of size blockSize.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_sparse_f32(
+ arm_fir_sparse_instance_f32 * S,
+ const float32_t * pSrc,
+ float32_t * pDst,
+ float32_t * pScratchIn,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the floating-point sparse FIR filter.
+ * @param[in,out] S points to an instance of the floating-point sparse FIR structure.
+ * @param[in] numTaps number of nonzero coefficients in the filter.
+ * @param[in] pCoeffs points to the array of filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] pTapDelay points to the array of offset times.
+ * @param[in] maxDelay maximum offset time supported.
+ * @param[in] blockSize number of samples that will be processed per block.
+ */
+ void arm_fir_sparse_init_f32(
+ arm_fir_sparse_instance_f32 * S,
+ uint16_t numTaps,
+ const float32_t * pCoeffs,
+ float32_t * pState,
+ int32_t * pTapDelay,
+ uint16_t maxDelay,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q31 sparse FIR filter.
+ * @param[in] S points to an instance of the Q31 sparse FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] pScratchIn points to a temporary buffer of size blockSize.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_sparse_q31(
+ arm_fir_sparse_instance_q31 * S,
+ const q31_t * pSrc,
+ q31_t * pDst,
+ q31_t * pScratchIn,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q31 sparse FIR filter.
+ * @param[in,out] S points to an instance of the Q31 sparse FIR structure.
+ * @param[in] numTaps number of nonzero coefficients in the filter.
+ * @param[in] pCoeffs points to the array of filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] pTapDelay points to the array of offset times.
+ * @param[in] maxDelay maximum offset time supported.
+ * @param[in] blockSize number of samples that will be processed per block.
+ */
+ void arm_fir_sparse_init_q31(
+ arm_fir_sparse_instance_q31 * S,
+ uint16_t numTaps,
+ const q31_t * pCoeffs,
+ q31_t * pState,
+ int32_t * pTapDelay,
+ uint16_t maxDelay,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q15 sparse FIR filter.
+ * @param[in] S points to an instance of the Q15 sparse FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] pScratchIn points to a temporary buffer of size blockSize.
+ * @param[in] pScratchOut points to a temporary buffer of size blockSize.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_sparse_q15(
+ arm_fir_sparse_instance_q15 * S,
+ const q15_t * pSrc,
+ q15_t * pDst,
+ q15_t * pScratchIn,
+ q31_t * pScratchOut,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q15 sparse FIR filter.
+ * @param[in,out] S points to an instance of the Q15 sparse FIR structure.
+ * @param[in] numTaps number of nonzero coefficients in the filter.
+ * @param[in] pCoeffs points to the array of filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] pTapDelay points to the array of offset times.
+ * @param[in] maxDelay maximum offset time supported.
+ * @param[in] blockSize number of samples that will be processed per block.
+ */
+ void arm_fir_sparse_init_q15(
+ arm_fir_sparse_instance_q15 * S,
+ uint16_t numTaps,
+ const q15_t * pCoeffs,
+ q15_t * pState,
+ int32_t * pTapDelay,
+ uint16_t maxDelay,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Processing function for the Q7 sparse FIR filter.
+ * @param[in] S points to an instance of the Q7 sparse FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] pScratchIn points to a temporary buffer of size blockSize.
+ * @param[in] pScratchOut points to a temporary buffer of size blockSize.
+ * @param[in] blockSize number of input samples to process per call.
+ */
+ void arm_fir_sparse_q7(
+ arm_fir_sparse_instance_q7 * S,
+ const q7_t * pSrc,
+ q7_t * pDst,
+ q7_t * pScratchIn,
+ q31_t * pScratchOut,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Initialization function for the Q7 sparse FIR filter.
+ * @param[in,out] S points to an instance of the Q7 sparse FIR structure.
+ * @param[in] numTaps number of nonzero coefficients in the filter.
+ * @param[in] pCoeffs points to the array of filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] pTapDelay points to the array of offset times.
+ * @param[in] maxDelay maximum offset time supported.
+ * @param[in] blockSize number of samples that will be processed per block.
+ */
+ void arm_fir_sparse_init_q7(
+ arm_fir_sparse_instance_q7 * S,
+ uint16_t numTaps,
+ const q7_t * pCoeffs,
+ q7_t * pState,
+ int32_t * pTapDelay,
+ uint16_t maxDelay,
+ uint32_t blockSize);
+
+
+
+
+
+
+ /**
+ * @brief floating-point Circular write function.
+ */
+ __STATIC_FORCEINLINE void arm_circularWrite_f32(
+ int32_t * circBuffer,
+ int32_t L,
+ uint16_t * writeOffset,
+ int32_t bufferInc,
+ const int32_t * src,
+ int32_t srcInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0U;
+ int32_t wOffset;
+
+ /* Copy the value of Index pointer that points
+ * to the current location where the input samples to be copied */
+ wOffset = *writeOffset;
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the input sample to the circular buffer */
+ circBuffer[wOffset] = *src;
+
+ /* Update the input pointer */
+ src += srcInc;
+
+ /* Circularly update wOffset. Watch out for positive and negative value */
+ wOffset += bufferInc;
+ if (wOffset >= L)
+ wOffset -= L;
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *writeOffset = (uint16_t)wOffset;
+ }
+
+
+
+ /**
+ * @brief floating-point Circular Read function.
+ */
+ __STATIC_FORCEINLINE void arm_circularRead_f32(
+ int32_t * circBuffer,
+ int32_t L,
+ int32_t * readOffset,
+ int32_t bufferInc,
+ int32_t * dst,
+ int32_t * dst_base,
+ int32_t dst_length,
+ int32_t dstInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0U;
+ int32_t rOffset;
+ int32_t* dst_end;
+
+ /* Copy the value of Index pointer that points
+ * to the current location from where the input samples to be read */
+ rOffset = *readOffset;
+ dst_end = dst_base + dst_length;
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the sample from the circular buffer to the destination buffer */
+ *dst = circBuffer[rOffset];
+
+ /* Update the input pointer */
+ dst += dstInc;
+
+ if (dst == dst_end)
+ {
+ dst = dst_base;
+ }
+
+ /* Circularly update rOffset. Watch out for positive and negative value */
+ rOffset += bufferInc;
+
+ if (rOffset >= L)
+ {
+ rOffset -= L;
+ }
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *readOffset = rOffset;
+ }
+
+
+ /**
+ * @brief Q15 Circular write function.
+ */
+ __STATIC_FORCEINLINE void arm_circularWrite_q15(
+ q15_t * circBuffer,
+ int32_t L,
+ uint16_t * writeOffset,
+ int32_t bufferInc,
+ const q15_t * src,
+ int32_t srcInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0U;
+ int32_t wOffset;
+
+ /* Copy the value of Index pointer that points
+ * to the current location where the input samples to be copied */
+ wOffset = *writeOffset;
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the input sample to the circular buffer */
+ circBuffer[wOffset] = *src;
+
+ /* Update the input pointer */
+ src += srcInc;
+
+ /* Circularly update wOffset. Watch out for positive and negative value */
+ wOffset += bufferInc;
+ if (wOffset >= L)
+ wOffset -= L;
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *writeOffset = (uint16_t)wOffset;
+ }
+
+
+ /**
+ * @brief Q15 Circular Read function.
+ */
+ __STATIC_FORCEINLINE void arm_circularRead_q15(
+ q15_t * circBuffer,
+ int32_t L,
+ int32_t * readOffset,
+ int32_t bufferInc,
+ q15_t * dst,
+ q15_t * dst_base,
+ int32_t dst_length,
+ int32_t dstInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0;
+ int32_t rOffset;
+ q15_t* dst_end;
+
+ /* Copy the value of Index pointer that points
+ * to the current location from where the input samples to be read */
+ rOffset = *readOffset;
+
+ dst_end = dst_base + dst_length;
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the sample from the circular buffer to the destination buffer */
+ *dst = circBuffer[rOffset];
+
+ /* Update the input pointer */
+ dst += dstInc;
+
+ if (dst == dst_end)
+ {
+ dst = dst_base;
+ }
+
+ /* Circularly update wOffset. Watch out for positive and negative value */
+ rOffset += bufferInc;
+
+ if (rOffset >= L)
+ {
+ rOffset -= L;
+ }
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *readOffset = rOffset;
+ }
+
+
+ /**
+ * @brief Q7 Circular write function.
+ */
+ __STATIC_FORCEINLINE void arm_circularWrite_q7(
+ q7_t * circBuffer,
+ int32_t L,
+ uint16_t * writeOffset,
+ int32_t bufferInc,
+ const q7_t * src,
+ int32_t srcInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0U;
+ int32_t wOffset;
+
+ /* Copy the value of Index pointer that points
+ * to the current location where the input samples to be copied */
+ wOffset = *writeOffset;
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the input sample to the circular buffer */
+ circBuffer[wOffset] = *src;
+
+ /* Update the input pointer */
+ src += srcInc;
+
+ /* Circularly update wOffset. Watch out for positive and negative value */
+ wOffset += bufferInc;
+ if (wOffset >= L)
+ wOffset -= L;
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *writeOffset = (uint16_t)wOffset;
+ }
+
+
+ /**
+ * @brief Q7 Circular Read function.
+ */
+ __STATIC_FORCEINLINE void arm_circularRead_q7(
+ q7_t * circBuffer,
+ int32_t L,
+ int32_t * readOffset,
+ int32_t bufferInc,
+ q7_t * dst,
+ q7_t * dst_base,
+ int32_t dst_length,
+ int32_t dstInc,
+ uint32_t blockSize)
+ {
+ uint32_t i = 0;
+ int32_t rOffset;
+ q7_t* dst_end;
+
+ /* Copy the value of Index pointer that points
+ * to the current location from where the input samples to be read */
+ rOffset = *readOffset;
+
+ dst_end = dst_base + dst_length;
+
+ /* Loop over the blockSize */
+ i = blockSize;
+
+ while (i > 0U)
+ {
+ /* copy the sample from the circular buffer to the destination buffer */
+ *dst = circBuffer[rOffset];
+
+ /* Update the input pointer */
+ dst += dstInc;
+
+ if (dst == dst_end)
+ {
+ dst = dst_base;
+ }
+
+ /* Circularly update rOffset. Watch out for positive and negative value */
+ rOffset += bufferInc;
+
+ if (rOffset >= L)
+ {
+ rOffset -= L;
+ }
+
+ /* Decrement the loop counter */
+ i--;
+ }
+
+ /* Update the index pointer */
+ *readOffset = rOffset;
+ }
+
+
+/**
+ @brief Levinson Durbin
+ @param[in] phi autocovariance vector starting with lag 0 (length is nbCoefs + 1)
+ @param[out] a autoregressive coefficients
+ @param[out] err prediction error (variance)
+ @param[in] nbCoefs number of autoregressive coefficients
+ @return none
+ */
+void arm_levinson_durbin_f32(const float32_t *phi,
+ float32_t *a,
+ float32_t *err,
+ int nbCoefs);
+
+
+/**
+ @brief Levinson Durbin
+ @param[in] phi autocovariance vector starting with lag 0 (length is nbCoefs + 1)
+ @param[out] a autoregressive coefficients
+ @param[out] err prediction error (variance)
+ @param[in] nbCoefs number of autoregressive coefficients
+ @return none
+ */
+void arm_levinson_durbin_q31(const q31_t *phi,
+ q31_t *a,
+ q31_t *err,
+ int nbCoefs);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _FILTERING_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/filtering_functions_f16.h b/Middlewares/ST/ARM/DSP/Include/dsp/filtering_functions_f16.h
new file mode 100644
index 0000000..fd8b0bb
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/filtering_functions_f16.h
@@ -0,0 +1,237 @@
+/******************************************************************************
+ * @file filtering_functions_f16.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _FILTERING_FUNCTIONS_F16_H_
+#define _FILTERING_FUNCTIONS_F16_H_
+
+#include "arm_math_types_f16.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if defined(ARM_FLOAT16_SUPPORTED)
+
+ /**
+ * @brief Instance structure for the floating-point FIR filter.
+ */
+ typedef struct
+ {
+ uint16_t numTaps; /**< number of filter coefficients in the filter. */
+ float16_t *pState; /**< points to the state variable array. The array is of length numTaps+blockSize-1. */
+ const float16_t *pCoeffs; /**< points to the coefficient array. The array is of length numTaps. */
+ } arm_fir_instance_f16;
+
+ /**
+ * @brief Initialization function for the floating-point FIR filter.
+ * @param[in,out] S points to an instance of the floating-point FIR filter structure.
+ * @param[in] numTaps Number of filter coefficients in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ * @param[in] blockSize number of samples that are processed at a time.
+ */
+ void arm_fir_init_f16(
+ arm_fir_instance_f16 * S,
+ uint16_t numTaps,
+ const float16_t * pCoeffs,
+ float16_t * pState,
+ uint32_t blockSize);
+
+ /**
+ * @brief Processing function for the floating-point FIR filter.
+ * @param[in] S points to an instance of the floating-point FIR structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_fir_f16(
+ const arm_fir_instance_f16 * S,
+ const float16_t * pSrc,
+ float16_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Instance structure for the floating-point Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint32_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float16_t *pState; /**< Points to the array of state coefficients. The array is of length 4*numStages. */
+ const float16_t *pCoeffs; /**< Points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_casd_df1_inst_f16;
+
+#if defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE)
+ /**
+ * @brief Instance structure for the modified Biquad coefs required by vectorized code.
+ */
+ typedef struct
+ {
+ float16_t coeffs[12][8]; /**< Points to the array of modified coefficients. The array is of length 32. There is one per stage */
+ } arm_biquad_mod_coef_f16;
+#endif
+
+ /**
+ * @brief Processing function for the floating-point Biquad cascade filter.
+ * @param[in] S points to an instance of the floating-point Biquad cascade structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df1_f16(
+ const arm_biquad_casd_df1_inst_f16 * S,
+ const float16_t * pSrc,
+ float16_t * pDst,
+ uint32_t blockSize);
+
+#if defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE)
+ void arm_biquad_cascade_df1_mve_init_f16(
+ arm_biquad_casd_df1_inst_f16 * S,
+ uint8_t numStages,
+ const float16_t * pCoeffs,
+ arm_biquad_mod_coef_f16 * pCoeffsMod,
+ float16_t * pState);
+#endif
+
+ void arm_biquad_cascade_df1_init_f16(
+ arm_biquad_casd_df1_inst_f16 * S,
+ uint8_t numStages,
+ const float16_t * pCoeffs,
+ float16_t * pState);
+
+ /**
+ * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float16_t *pState; /**< points to the array of state coefficients. The array is of length 2*numStages. */
+ const float16_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_cascade_df2T_instance_f16;
+
+ /**
+ * @brief Instance structure for the floating-point transposed direct form II Biquad cascade filter.
+ */
+ typedef struct
+ {
+ uint8_t numStages; /**< number of 2nd order stages in the filter. Overall order is 2*numStages. */
+ float16_t *pState; /**< points to the array of state coefficients. The array is of length 4*numStages. */
+ const float16_t *pCoeffs; /**< points to the array of coefficients. The array is of length 5*numStages. */
+ } arm_biquad_cascade_stereo_df2T_instance_f16;
+
+ /**
+ * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in] S points to an instance of the filter data structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_df2T_f16(
+ const arm_biquad_cascade_df2T_instance_f16 * S,
+ const float16_t * pSrc,
+ float16_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Processing function for the floating-point transposed direct form II Biquad cascade filter. 2 channels
+ * @param[in] S points to an instance of the filter data structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_biquad_cascade_stereo_df2T_f16(
+ const arm_biquad_cascade_stereo_df2T_instance_f16 * S,
+ const float16_t * pSrc,
+ float16_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in,out] S points to an instance of the filter data structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ */
+ void arm_biquad_cascade_df2T_init_f16(
+ arm_biquad_cascade_df2T_instance_f16 * S,
+ uint8_t numStages,
+ const float16_t * pCoeffs,
+ float16_t * pState);
+
+ /**
+ * @brief Initialization function for the floating-point transposed direct form II Biquad cascade filter.
+ * @param[in,out] S points to an instance of the filter data structure.
+ * @param[in] numStages number of 2nd order stages in the filter.
+ * @param[in] pCoeffs points to the filter coefficients.
+ * @param[in] pState points to the state buffer.
+ */
+ void arm_biquad_cascade_stereo_df2T_init_f16(
+ arm_biquad_cascade_stereo_df2T_instance_f16 * S,
+ uint8_t numStages,
+ const float16_t * pCoeffs,
+ float16_t * pState);
+
+ /**
+ * @brief Correlation of floating-point sequences.
+ * @param[in] pSrcA points to the first input sequence.
+ * @param[in] srcALen length of the first input sequence.
+ * @param[in] pSrcB points to the second input sequence.
+ * @param[in] srcBLen length of the second input sequence.
+ * @param[out] pDst points to the block of output data Length 2 * max(srcALen, srcBLen) - 1.
+ */
+ void arm_correlate_f16(
+ const float16_t * pSrcA,
+ uint32_t srcALen,
+ const float16_t * pSrcB,
+ uint32_t srcBLen,
+ float16_t * pDst);
+
+
+/**
+ @brief Levinson Durbin
+ @param[in] phi autocovariance vector starting with lag 0 (length is nbCoefs + 1)
+ @param[out] a autoregressive coefficients
+ @param[out] err prediction error (variance)
+ @param[in] nbCoefs number of autoregressive coefficients
+ @return none
+ */
+void arm_levinson_durbin_f16(const float16_t *phi,
+ float16_t *a,
+ float16_t *err,
+ int nbCoefs);
+
+#endif /*defined(ARM_FLOAT16_SUPPORTED)*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _FILTERING_FUNCTIONS_F16_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/interpolation_functions.h b/Middlewares/ST/ARM/DSP/Include/dsp/interpolation_functions.h
new file mode 100644
index 0000000..dbea4eb
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/interpolation_functions.h
@@ -0,0 +1,275 @@
+/******************************************************************************
+ * @file interpolation_functions.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _INTERPOLATION_FUNCTIONS_H_
+#define _INTERPOLATION_FUNCTIONS_H_
+
+#include "arm_math_types.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+/**
+ * @defgroup groupInterpolation Interpolation Functions
+ * These functions perform 1- and 2-dimensional interpolation of data.
+ * Linear interpolation is used for 1-dimensional data and
+ * bilinear interpolation is used for 2-dimensional data.
+ */
+
+
+ /**
+ * @brief Instance structure for the floating-point Linear Interpolate function.
+ */
+ typedef struct
+ {
+ uint32_t nValues; /**< nValues */
+ float32_t x1; /**< x1 */
+ float32_t xSpacing; /**< xSpacing */
+ const float32_t *pYData; /**< pointer to the table of Y values */
+ } arm_linear_interp_instance_f32;
+
+ /**
+ * @brief Instance structure for the floating-point bilinear interpolation function.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows in the data table. */
+ uint16_t numCols; /**< number of columns in the data table. */
+ const float32_t *pData; /**< points to the data table. */
+ } arm_bilinear_interp_instance_f32;
+
+ /**
+ * @brief Instance structure for the Q31 bilinear interpolation function.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows in the data table. */
+ uint16_t numCols; /**< number of columns in the data table. */
+ const q31_t *pData; /**< points to the data table. */
+ } arm_bilinear_interp_instance_q31;
+
+ /**
+ * @brief Instance structure for the Q15 bilinear interpolation function.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows in the data table. */
+ uint16_t numCols; /**< number of columns in the data table. */
+ const q15_t *pData; /**< points to the data table. */
+ } arm_bilinear_interp_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q15 bilinear interpolation function.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows in the data table. */
+ uint16_t numCols; /**< number of columns in the data table. */
+ const q7_t *pData; /**< points to the data table. */
+ } arm_bilinear_interp_instance_q7;
+
+
+ /**
+ * @brief Struct for specifying cubic spline type
+ */
+ typedef enum
+ {
+ ARM_SPLINE_NATURAL = 0, /**< Natural spline */
+ ARM_SPLINE_PARABOLIC_RUNOUT = 1 /**< Parabolic runout spline */
+ } arm_spline_type;
+
+ /**
+ * @brief Instance structure for the floating-point cubic spline interpolation.
+ */
+ typedef struct
+ {
+ arm_spline_type type; /**< Type (boundary conditions) */
+ const float32_t * x; /**< x values */
+ const float32_t * y; /**< y values */
+ uint32_t n_x; /**< Number of known data points */
+ float32_t * coeffs; /**< Coefficients buffer (b,c, and d) */
+ } arm_spline_instance_f32;
+
+
+ /**
+ * @brief Processing function for the floating-point cubic spline interpolation.
+ * @param[in] S points to an instance of the floating-point spline structure.
+ * @param[in] xq points to the x values ot the interpolated data points.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples of output data.
+ */
+ void arm_spline_f32(
+ arm_spline_instance_f32 * S,
+ const float32_t * xq,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Initialization function for the floating-point cubic spline interpolation.
+ * @param[in,out] S points to an instance of the floating-point spline structure.
+ * @param[in] type type of cubic spline interpolation (boundary conditions)
+ * @param[in] x points to the x values of the known data points.
+ * @param[in] y points to the y values of the known data points.
+ * @param[in] n number of known data points.
+ * @param[in] coeffs coefficients array for b, c, and d
+ * @param[in] tempBuffer buffer array for internal computations
+ */
+ void arm_spline_init_f32(
+ arm_spline_instance_f32 * S,
+ arm_spline_type type,
+ const float32_t * x,
+ const float32_t * y,
+ uint32_t n,
+ float32_t * coeffs,
+ float32_t * tempBuffer);
+
+
+ /**
+ * @brief Process function for the floating-point Linear Interpolation Function.
+ * @param[in,out] S is an instance of the floating-point Linear Interpolation structure
+ * @param[in] x input sample to process
+ * @return y processed output sample.
+ *
+ */
+ float32_t arm_linear_interp_f32(
+ arm_linear_interp_instance_f32 * S,
+ float32_t x);
+
+ /**
+ *
+ * @brief Process function for the Q31 Linear Interpolation Function.
+ * @param[in] pYData pointer to Q31 Linear Interpolation table
+ * @param[in] x input sample to process
+ * @param[in] nValues number of table values
+ * @return y processed output sample.
+ *
+ * \par
+ * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part.
+ * This function can support maximum of table size 2^12.
+ *
+ */
+ q31_t arm_linear_interp_q31(
+ const q31_t * pYData,
+ q31_t x,
+ uint32_t nValues);
+
+ /**
+ *
+ * @brief Process function for the Q15 Linear Interpolation Function.
+ * @param[in] pYData pointer to Q15 Linear Interpolation table
+ * @param[in] x input sample to process
+ * @param[in] nValues number of table values
+ * @return y processed output sample.
+ *
+ * \par
+ * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part.
+ * This function can support maximum of table size 2^12.
+ *
+ */
+ q15_t arm_linear_interp_q15(
+ const q15_t * pYData,
+ q31_t x,
+ uint32_t nValues);
+
+ /**
+ *
+ * @brief Process function for the Q7 Linear Interpolation Function.
+ * @param[in] pYData pointer to Q7 Linear Interpolation table
+ * @param[in] x input sample to process
+ * @param[in] nValues number of table values
+ * @return y processed output sample.
+ *
+ * \par
+ * Input sample x is in 12.20 format which contains 12 bits for table index and 20 bits for fractional part.
+ * This function can support maximum of table size 2^12.
+ */
+q7_t arm_linear_interp_q7(
+ const q7_t * pYData,
+ q31_t x,
+ uint32_t nValues);
+
+ /**
+ * @brief Floating-point bilinear interpolation.
+ * @param[in,out] S points to an instance of the interpolation structure.
+ * @param[in] X interpolation coordinate.
+ * @param[in] Y interpolation coordinate.
+ * @return out interpolated value.
+ */
+ float32_t arm_bilinear_interp_f32(
+ const arm_bilinear_interp_instance_f32 * S,
+ float32_t X,
+ float32_t Y);
+
+ /**
+ * @brief Q31 bilinear interpolation.
+ * @param[in,out] S points to an instance of the interpolation structure.
+ * @param[in] X interpolation coordinate in 12.20 format.
+ * @param[in] Y interpolation coordinate in 12.20 format.
+ * @return out interpolated value.
+ */
+ q31_t arm_bilinear_interp_q31(
+ arm_bilinear_interp_instance_q31 * S,
+ q31_t X,
+ q31_t Y);
+
+
+ /**
+ * @brief Q15 bilinear interpolation.
+ * @param[in,out] S points to an instance of the interpolation structure.
+ * @param[in] X interpolation coordinate in 12.20 format.
+ * @param[in] Y interpolation coordinate in 12.20 format.
+ * @return out interpolated value.
+ */
+ q15_t arm_bilinear_interp_q15(
+ arm_bilinear_interp_instance_q15 * S,
+ q31_t X,
+ q31_t Y);
+
+ /**
+ * @brief Q7 bilinear interpolation.
+ * @param[in,out] S points to an instance of the interpolation structure.
+ * @param[in] X interpolation coordinate in 12.20 format.
+ * @param[in] Y interpolation coordinate in 12.20 format.
+ * @return out interpolated value.
+ */
+ q7_t arm_bilinear_interp_q7(
+ arm_bilinear_interp_instance_q7 * S,
+ q31_t X,
+ q31_t Y);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _INTERPOLATION_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/interpolation_functions_f16.h b/Middlewares/ST/ARM/DSP/Include/dsp/interpolation_functions_f16.h
new file mode 100644
index 0000000..7b88048
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/interpolation_functions_f16.h
@@ -0,0 +1,107 @@
+/******************************************************************************
+ * @file interpolation_functions_f16.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _INTERPOLATION_FUNCTIONS_F16_H_
+#define _INTERPOLATION_FUNCTIONS_F16_H_
+
+#include "arm_math_types_f16.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if defined(ARM_FLOAT16_SUPPORTED)
+
+typedef struct
+{
+ uint32_t nValues; /**< nValues */
+ float16_t x1; /**< x1 */
+ float16_t xSpacing; /**< xSpacing */
+ const float16_t *pYData; /**< pointer to the table of Y values */
+} arm_linear_interp_instance_f16;
+
+/**
+ * @brief Instance structure for the floating-point bilinear interpolation function.
+ */
+typedef struct
+{
+ uint16_t numRows;/**< number of rows in the data table. */
+ uint16_t numCols;/**< number of columns in the data table. */
+ const float16_t *pData; /**< points to the data table. */
+} arm_bilinear_interp_instance_f16;
+
+ /**
+ * @addtogroup LinearInterpolate
+ * @{
+ */
+
+ /**
+ * @brief Process function for the floating-point Linear Interpolation Function.
+ * @param[in,out] S is an instance of the floating-point Linear Interpolation structure
+ * @param[in] x input sample to process
+ * @return y processed output sample.
+ *
+ */
+ float16_t arm_linear_interp_f16(
+ arm_linear_interp_instance_f16 * S,
+ float16_t x);
+
+ /**
+ * @} end of LinearInterpolate group
+ */
+
+/**
+ * @addtogroup BilinearInterpolate
+ * @{
+ */
+
+ /**
+ * @brief Floating-point bilinear interpolation.
+ * @param[in,out] S points to an instance of the interpolation structure.
+ * @param[in] X interpolation coordinate.
+ * @param[in] Y interpolation coordinate.
+ * @return out interpolated value.
+ */
+ float16_t arm_bilinear_interp_f16(
+ const arm_bilinear_interp_instance_f16 * S,
+ float16_t X,
+ float16_t Y);
+
+
+ /**
+ * @} end of BilinearInterpolate group
+ */
+#endif /*defined(ARM_FLOAT16_SUPPORTED)*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _INTERPOLATION_FUNCTIONS_F16_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/matrix_functions.h b/Middlewares/ST/ARM/DSP/Include/dsp/matrix_functions.h
new file mode 100644
index 0000000..6ebf720
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/matrix_functions.h
@@ -0,0 +1,856 @@
+/******************************************************************************
+ * @file matrix_functions.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.1
+ * @date 10 August 2022
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _MATRIX_FUNCTIONS_H_
+#define _MATRIX_FUNCTIONS_H_
+
+#include "arm_math_types.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @defgroup groupMatrix Matrix Functions
+ *
+ * This set of functions provides basic matrix math operations.
+ * The functions operate on matrix data structures. For example,
+ * the type
+ * definition for the floating-point matrix structure is shown
+ * below:
+ *
+ * typedef struct
+ * {
+ * uint16_t numRows; // number of rows of the matrix.
+ * uint16_t numCols; // number of columns of the matrix.
+ * float32_t *pData; // points to the data of the matrix.
+ * } arm_matrix_instance_f32;
+ *
+ * There are similar definitions for Q15 and Q31 data types.
+ *
+ * The structure specifies the size of the matrix and then points to
+ * an array of data. The array is of size numRows X numCols
+ * and the values are arranged in row order. That is, the
+ * matrix element (i, j) is stored at:
+ * + * pData[i*numCols + j] + *+ * + * \par Init Functions + * There is an associated initialization function for each type of matrix + * data structure. + * The initialization function sets the values of the internal structure fields. + * Refer to \ref arm_mat_init_f32(), \ref arm_mat_init_q31() and \ref arm_mat_init_q15() + * for floating-point, Q31 and Q15 types, respectively. + * + * \par + * Use of the initialization function is optional. However, if initialization function is used + * then the instance structure cannot be placed into a const data section. + * To place the instance structure in a const data + * section, manually initialize the data structure. For example: + *
+ *+ * wherearm_matrix_instance_f32 S = {nRows, nColumns, pData};+ *arm_matrix_instance_q31 S = {nRows, nColumns, pData};+ *arm_matrix_instance_q15 S = {nRows, nColumns, pData};+ *
nRows specifies the number of rows, nColumns
+ * specifies the number of columns, and pData points to the
+ * data array.
+ *
+ * \par Size Checking
+ * By default all of the matrix functions perform size checking on the input and
+ * output matrices. For example, the matrix addition function verifies that the
+ * two input matrices and the output matrix all have the same number of rows and
+ * columns. If the size check fails the functions return:
+ * + * ARM_MATH_SIZE_MISMATCH + *+ * Otherwise the functions return + *
+ * ARM_MATH_SUCCESS + *+ * There is some overhead associated with this matrix size checking. + * The matrix size checking is enabled via the \#define + *
+ * ARM_MATH_MATRIX_CHECK + *+ * within the library project settings. By default this macro is defined + * and size checking is enabled. By changing the project settings and + * undefining this macro size checking is eliminated and the functions + * run a bit faster. With size checking disabled the functions always + * return
ARM_MATH_SUCCESS.
+ */
+
+ #define DEFAULT_HOUSEHOLDER_THRESHOLD_F64 (1.0e-16)
+ #define DEFAULT_HOUSEHOLDER_THRESHOLD_F32 (1.0e-12f)
+
+ /**
+ * @brief Instance structure for the floating-point matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ float32_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_f32;
+
+ /**
+ * @brief Instance structure for the floating-point matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ float64_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_f64;
+
+ /**
+ * @brief Instance structure for the Q7 matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ q7_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_q7;
+
+ /**
+ * @brief Instance structure for the Q15 matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ q15_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_q15;
+
+ /**
+ * @brief Instance structure for the Q31 matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ q31_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_q31;
+
+ /**
+ * @brief Floating-point matrix addition.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_add_f32(
+ const arm_matrix_instance_f32 * pSrcA,
+ const arm_matrix_instance_f32 * pSrcB,
+ arm_matrix_instance_f32 * pDst);
+
+ /**
+ * @brief Q15 matrix addition.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_add_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst);
+
+ /**
+ * @brief Q31 matrix addition.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_add_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+ /**
+ * @brief Floating-point, complex, matrix multiplication.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_cmplx_mult_f32(
+ const arm_matrix_instance_f32 * pSrcA,
+ const arm_matrix_instance_f32 * pSrcB,
+ arm_matrix_instance_f32 * pDst);
+
+ /**
+ * @brief Q15, complex, matrix multiplication.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_cmplx_mult_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst,
+ q15_t * pScratch);
+
+ /**
+ * @brief Q31, complex, matrix multiplication.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_cmplx_mult_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+ /**
+ * @brief Floating-point matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_trans_f32(
+ const arm_matrix_instance_f32 * pSrc,
+ arm_matrix_instance_f32 * pDst);
+
+/**
+ * @brief Floating-point matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_trans_f64(
+ const arm_matrix_instance_f64 * pSrc,
+ arm_matrix_instance_f64 * pDst);
+
+ /**
+ * @brief Floating-point complex matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_cmplx_trans_f32(
+ const arm_matrix_instance_f32 * pSrc,
+ arm_matrix_instance_f32 * pDst);
+
+
+ /**
+ * @brief Q15 matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_trans_q15(
+ const arm_matrix_instance_q15 * pSrc,
+ arm_matrix_instance_q15 * pDst);
+
+ /**
+ * @brief Q15 complex matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_cmplx_trans_q15(
+ const arm_matrix_instance_q15 * pSrc,
+ arm_matrix_instance_q15 * pDst);
+
+ /**
+ * @brief Q7 matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_trans_q7(
+ const arm_matrix_instance_q7 * pSrc,
+ arm_matrix_instance_q7 * pDst);
+
+ /**
+ * @brief Q31 matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_trans_q31(
+ const arm_matrix_instance_q31 * pSrc,
+ arm_matrix_instance_q31 * pDst);
+
+ /**
+ * @brief Q31 complex matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_cmplx_trans_q31(
+ const arm_matrix_instance_q31 * pSrc,
+ arm_matrix_instance_q31 * pDst);
+
+ /**
+ * @brief Floating-point matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_mult_f32(
+ const arm_matrix_instance_f32 * pSrcA,
+ const arm_matrix_instance_f32 * pSrcB,
+ arm_matrix_instance_f32 * pDst);
+
+ /**
+ * @brief Floating-point matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_mult_f64(
+ const arm_matrix_instance_f64 * pSrcA,
+ const arm_matrix_instance_f64 * pSrcB,
+ arm_matrix_instance_f64 * pDst);
+
+ /**
+ * @brief Floating-point matrix and vector multiplication
+ * @param[in] pSrcMat points to the input matrix structure
+ * @param[in] pVec points to vector
+ * @param[out] pDst points to output vector
+ */
+void arm_mat_vec_mult_f32(
+ const arm_matrix_instance_f32 *pSrcMat,
+ const float32_t *pVec,
+ float32_t *pDst);
+
+ /**
+ * @brief Q7 matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @param[in] pState points to the array for storing intermediate results
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_mult_q7(
+ const arm_matrix_instance_q7 * pSrcA,
+ const arm_matrix_instance_q7 * pSrcB,
+ arm_matrix_instance_q7 * pDst,
+ q7_t * pState);
+
+ /**
+ * @brief Q7 matrix and vector multiplication
+ * @param[in] pSrcMat points to the input matrix structure
+ * @param[in] pVec points to vector
+ * @param[out] pDst points to output vector
+ */
+void arm_mat_vec_mult_q7(
+ const arm_matrix_instance_q7 *pSrcMat,
+ const q7_t *pVec,
+ q7_t *pDst);
+
+ /**
+ * @brief Q15 matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @param[in] pState points to the array for storing intermediate results
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_mult_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst,
+ q15_t * pState);
+
+ /**
+ * @brief Q15 matrix and vector multiplication
+ * @param[in] pSrcMat points to the input matrix structure
+ * @param[in] pVec points to vector
+ * @param[out] pDst points to output vector
+ */
+void arm_mat_vec_mult_q15(
+ const arm_matrix_instance_q15 *pSrcMat,
+ const q15_t *pVec,
+ q15_t *pDst);
+
+ /**
+ * @brief Q15 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @param[in] pState points to the array for storing intermediate results
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_mult_fast_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst,
+ q15_t * pState);
+
+ /**
+ * @brief Q31 matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_mult_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+ /**
+ * @brief Q31 matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @param[in] pState points to the array for storing intermediate results
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_mult_opt_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst,
+ q31_t *pState);
+
+ /**
+ * @brief Q31 matrix and vector multiplication
+ * @param[in] pSrcMat points to the input matrix structure
+ * @param[in] pVec points to vector
+ * @param[out] pDst points to output vector
+ */
+void arm_mat_vec_mult_q31(
+ const arm_matrix_instance_q31 *pSrcMat,
+ const q31_t *pVec,
+ q31_t *pDst);
+
+ /**
+ * @brief Q31 matrix multiplication (fast variant) for Cortex-M3 and Cortex-M4
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_mult_fast_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+ /**
+ * @brief Floating-point matrix subtraction
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_sub_f32(
+ const arm_matrix_instance_f32 * pSrcA,
+ const arm_matrix_instance_f32 * pSrcB,
+ arm_matrix_instance_f32 * pDst);
+
+ /**
+ * @brief Floating-point matrix subtraction
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_sub_f64(
+ const arm_matrix_instance_f64 * pSrcA,
+ const arm_matrix_instance_f64 * pSrcB,
+ arm_matrix_instance_f64 * pDst);
+
+ /**
+ * @brief Q15 matrix subtraction
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_sub_q15(
+ const arm_matrix_instance_q15 * pSrcA,
+ const arm_matrix_instance_q15 * pSrcB,
+ arm_matrix_instance_q15 * pDst);
+
+ /**
+ * @brief Q31 matrix subtraction
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_sub_q31(
+ const arm_matrix_instance_q31 * pSrcA,
+ const arm_matrix_instance_q31 * pSrcB,
+ arm_matrix_instance_q31 * pDst);
+
+ /**
+ * @brief Floating-point matrix scaling.
+ * @param[in] pSrc points to the input matrix
+ * @param[in] scale scale factor
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_scale_f32(
+ const arm_matrix_instance_f32 * pSrc,
+ float32_t scale,
+ arm_matrix_instance_f32 * pDst);
+
+ /**
+ * @brief Q15 matrix scaling.
+ * @param[in] pSrc points to input matrix
+ * @param[in] scaleFract fractional portion of the scale factor
+ * @param[in] shift number of bits to shift the result by
+ * @param[out] pDst points to output matrix
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_scale_q15(
+ const arm_matrix_instance_q15 * pSrc,
+ q15_t scaleFract,
+ int32_t shift,
+ arm_matrix_instance_q15 * pDst);
+
+ /**
+ * @brief Q31 matrix scaling.
+ * @param[in] pSrc points to input matrix
+ * @param[in] scaleFract fractional portion of the scale factor
+ * @param[in] shift number of bits to shift the result by
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_scale_q31(
+ const arm_matrix_instance_q31 * pSrc,
+ q31_t scaleFract,
+ int32_t shift,
+ arm_matrix_instance_q31 * pDst);
+
+ /**
+ * @brief Q31 matrix initialization.
+ * @param[in,out] S points to an instance of the floating-point matrix structure.
+ * @param[in] nRows number of rows in the matrix.
+ * @param[in] nColumns number of columns in the matrix.
+ * @param[in] pData points to the matrix data array.
+ */
+void arm_mat_init_q31(
+ arm_matrix_instance_q31 * S,
+ uint16_t nRows,
+ uint16_t nColumns,
+ q31_t * pData);
+
+ /**
+ * @brief Q15 matrix initialization.
+ * @param[in,out] S points to an instance of the floating-point matrix structure.
+ * @param[in] nRows number of rows in the matrix.
+ * @param[in] nColumns number of columns in the matrix.
+ * @param[in] pData points to the matrix data array.
+ */
+void arm_mat_init_q15(
+ arm_matrix_instance_q15 * S,
+ uint16_t nRows,
+ uint16_t nColumns,
+ q15_t * pData);
+
+ /**
+ * @brief Floating-point matrix initialization.
+ * @param[in,out] S points to an instance of the floating-point matrix structure.
+ * @param[in] nRows number of rows in the matrix.
+ * @param[in] nColumns number of columns in the matrix.
+ * @param[in] pData points to the matrix data array.
+ */
+void arm_mat_init_f32(
+ arm_matrix_instance_f32 * S,
+ uint16_t nRows,
+ uint16_t nColumns,
+ float32_t * pData);
+
+/**
+ * @brief Floating-point matrix initialization.
+ * @param[in,out] S points to an instance of the floating-point matrix structure.
+ * @param[in] nRows number of rows in the matrix.
+ * @param[in] nColumns number of columns in the matrix.
+ * @param[in] pData points to the matrix data array.
+ */
+void arm_mat_init_f64(
+ arm_matrix_instance_f64 * S,
+ uint16_t nRows,
+ uint16_t nColumns,
+ float64_t * pData);
+
+
+
+
+ /**
+ * @brief Floating-point matrix inverse.
+ * @param[in] src points to the instance of the input floating-point matrix structure.
+ * @param[out] dst points to the instance of the output floating-point matrix structure.
+ * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
+ * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR.
+ */
+ arm_status arm_mat_inverse_f32(
+ const arm_matrix_instance_f32 * src,
+ arm_matrix_instance_f32 * dst);
+
+
+ /**
+ * @brief Floating-point matrix inverse.
+ * @param[in] src points to the instance of the input floating-point matrix structure.
+ * @param[out] dst points to the instance of the output floating-point matrix structure.
+ * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
+ * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR.
+ */
+ arm_status arm_mat_inverse_f64(
+ const arm_matrix_instance_f64 * src,
+ arm_matrix_instance_f64 * dst);
+
+ /**
+ * @brief Floating-point Cholesky decomposition of Symmetric Positive Definite Matrix.
+ * @param[in] src points to the instance of the input floating-point matrix structure.
+ * @param[out] dst points to the instance of the output floating-point matrix structure.
+ * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
+ * If the input matrix does not have a decomposition, then the algorithm terminates and returns error status ARM_MATH_DECOMPOSITION_FAILURE.
+ * If the matrix is ill conditioned or only semi-definite, then it is better using the LDL^t decomposition.
+ * The decomposition is returning a lower triangular matrix.
+ */
+ arm_status arm_mat_cholesky_f64(
+ const arm_matrix_instance_f64 * src,
+ arm_matrix_instance_f64 * dst);
+
+ /**
+ * @brief Floating-point Cholesky decomposition of Symmetric Positive Definite Matrix.
+ * @param[in] src points to the instance of the input floating-point matrix structure.
+ * @param[out] dst points to the instance of the output floating-point matrix structure.
+ * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
+ * If the input matrix does not have a decomposition, then the algorithm terminates and returns error status ARM_MATH_DECOMPOSITION_FAILURE.
+ * If the matrix is ill conditioned or only semi-definite, then it is better using the LDL^t decomposition.
+ * The decomposition is returning a lower triangular matrix.
+ */
+ arm_status arm_mat_cholesky_f32(
+ const arm_matrix_instance_f32 * src,
+ arm_matrix_instance_f32 * dst);
+
+ /**
+ * @brief Solve UT . X = A where UT is an upper triangular matrix
+ * @param[in] ut The upper triangular matrix
+ * @param[in] a The matrix a
+ * @param[out] dst The solution X of UT . X = A
+ * @return The function returns ARM_MATH_SINGULAR, if the system can't be solved.
+ */
+ arm_status arm_mat_solve_upper_triangular_f32(
+ const arm_matrix_instance_f32 * ut,
+ const arm_matrix_instance_f32 * a,
+ arm_matrix_instance_f32 * dst);
+
+ /**
+ * @brief Solve LT . X = A where LT is a lower triangular matrix
+ * @param[in] lt The lower triangular matrix
+ * @param[in] a The matrix a
+ * @param[out] dst The solution X of LT . X = A
+ * @return The function returns ARM_MATH_SINGULAR, if the system can't be solved.
+ */
+ arm_status arm_mat_solve_lower_triangular_f32(
+ const arm_matrix_instance_f32 * lt,
+ const arm_matrix_instance_f32 * a,
+ arm_matrix_instance_f32 * dst);
+
+
+ /**
+ * @brief Solve UT . X = A where UT is an upper triangular matrix
+ * @param[in] ut The upper triangular matrix
+ * @param[in] a The matrix a
+ * @param[out] dst The solution X of UT . X = A
+ * @return The function returns ARM_MATH_SINGULAR, if the system can't be solved.
+ */
+ arm_status arm_mat_solve_upper_triangular_f64(
+ const arm_matrix_instance_f64 * ut,
+ const arm_matrix_instance_f64 * a,
+ arm_matrix_instance_f64 * dst);
+
+ /**
+ * @brief Solve LT . X = A where LT is a lower triangular matrix
+ * @param[in] lt The lower triangular matrix
+ * @param[in] a The matrix a
+ * @param[out] dst The solution X of LT . X = A
+ * @return The function returns ARM_MATH_SINGULAR, if the system can't be solved.
+ */
+ arm_status arm_mat_solve_lower_triangular_f64(
+ const arm_matrix_instance_f64 * lt,
+ const arm_matrix_instance_f64 * a,
+ arm_matrix_instance_f64 * dst);
+
+
+ /**
+ * @brief Floating-point LDL decomposition of Symmetric Positive Semi-Definite Matrix.
+ * @param[in] src points to the instance of the input floating-point matrix structure.
+ * @param[out] l points to the instance of the output floating-point triangular matrix structure.
+ * @param[out] d points to the instance of the output floating-point diagonal matrix structure.
+ * @param[out] p points to the instance of the output floating-point permutation vector.
+ * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
+ * If the input matrix does not have a decomposition, then the algorithm terminates and returns error status ARM_MATH_DECOMPOSITION_FAILURE.
+ * The decomposition is returning a lower triangular matrix.
+ */
+ arm_status arm_mat_ldlt_f32(
+ const arm_matrix_instance_f32 * src,
+ arm_matrix_instance_f32 * l,
+ arm_matrix_instance_f32 * d,
+ uint16_t * pp);
+
+ /**
+ * @brief Floating-point LDL decomposition of Symmetric Positive Semi-Definite Matrix.
+ * @param[in] src points to the instance of the input floating-point matrix structure.
+ * @param[out] l points to the instance of the output floating-point triangular matrix structure.
+ * @param[out] d points to the instance of the output floating-point diagonal matrix structure.
+ * @param[out] p points to the instance of the output floating-point permutation vector.
+ * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
+ * If the input matrix does not have a decomposition, then the algorithm terminates and returns error status ARM_MATH_DECOMPOSITION_FAILURE.
+ * The decomposition is returning a lower triangular matrix.
+ */
+ arm_status arm_mat_ldlt_f64(
+ const arm_matrix_instance_f64 * src,
+ arm_matrix_instance_f64 * l,
+ arm_matrix_instance_f64 * d,
+ uint16_t * pp);
+
+/**
+ @brief QR decomposition of a m x n floating point matrix with m >= n.
+ @param[in] pSrc points to input matrix structure. The source matrix is modified by the function.
+ @param[in] threshold norm2 threshold.
+ @param[out] pOutR points to output R matrix structure of dimension m x n
+ @param[out] pOutQ points to output Q matrix structure of dimension m x m
+ @param[out] pOutTau points to Householder scaling factors of dimension n
+ @param[inout] pTmpA points to a temporary vector of dimension m.
+ @param[inout] pTmpB points to a temporary vector of dimension n.
+ @return execution status
+ - \ref ARM_MATH_SUCCESS : Operation successful
+ - \ref ARM_MATH_SIZE_MISMATCH : Matrix size check failed
+ - \ref ARM_MATH_SINGULAR : Input matrix is found to be singular (non-invertible)
+ */
+
+arm_status arm_mat_qr_f32(
+ const arm_matrix_instance_f32 * pSrc,
+ const float32_t threshold,
+ arm_matrix_instance_f32 * pOutR,
+ arm_matrix_instance_f32 * pOutQ,
+ float32_t * pOutTau,
+ float32_t *pTmpA,
+ float32_t *pTmpB
+ );
+
+/**
+ @brief QR decomposition of a m x n floating point matrix with m >= n.
+ @param[in] pSrc points to input matrix structure. The source matrix is modified by the function.
+ @param[in] threshold norm2 threshold.
+ @param[out] pOutR points to output R matrix structure of dimension m x n
+ @param[out] pOutQ points to output Q matrix structure of dimension m x m
+ @param[out] pOutTau points to Householder scaling factors of dimension n
+ @param[inout] pTmpA points to a temporary vector of dimension m.
+ @param[inout] pTmpB points to a temporary vector of dimension n.
+ @return execution status
+ - \ref ARM_MATH_SUCCESS : Operation successful
+ - \ref ARM_MATH_SIZE_MISMATCH : Matrix size check failed
+ - \ref ARM_MATH_SINGULAR : Input matrix is found to be singular (non-invertible)
+ */
+
+arm_status arm_mat_qr_f64(
+ const arm_matrix_instance_f64 * pSrc,
+ const float64_t threshold,
+ arm_matrix_instance_f64 * pOutR,
+ arm_matrix_instance_f64 * pOutQ,
+ float64_t * pOutTau,
+ float64_t *pTmpA,
+ float64_t *pTmpB
+ );
+
+/**
+ @brief Householder transform of a floating point vector.
+ @param[in] pSrc points to the input vector.
+ @param[in] threshold norm2 threshold.
+ @param[in] blockSize dimension of the vector space.
+ @param[outQ] pOut points to the output vector.
+ @return beta return the scaling factor beta
+ */
+
+float32_t arm_householder_f32(
+ const float32_t * pSrc,
+ const float32_t threshold,
+ uint32_t blockSize,
+ float32_t * pOut
+ );
+
+/**
+ @brief Householder transform of a double floating point vector.
+ @param[in] pSrc points to the input vector.
+ @param[in] threshold norm2 threshold.
+ @param[in] blockSize dimension of the vector space.
+ @param[outQ] pOut points to the output vector.
+ @return beta return the scaling factor beta
+ */
+
+float64_t arm_householder_f64(
+ const float64_t * pSrc,
+ const float64_t threshold,
+ uint32_t blockSize,
+ float64_t * pOut
+ );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _MATRIX_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/matrix_functions_f16.h b/Middlewares/ST/ARM/DSP/Include/dsp/matrix_functions_f16.h
new file mode 100644
index 0000000..8ce4bf2
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/matrix_functions_f16.h
@@ -0,0 +1,263 @@
+/******************************************************************************
+ * @file matrix_functions_f16.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _MATRIX_FUNCTIONS_F16_H_
+#define _MATRIX_FUNCTIONS_F16_H_
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#include "arm_math_types_f16.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#if defined(ARM_FLOAT16_SUPPORTED)
+
+ #define DEFAULT_HOUSEHOLDER_THRESHOLD_F16 (1.0e-3f)
+
+ /**
+ * @brief Instance structure for the floating-point matrix structure.
+ */
+ typedef struct
+ {
+ uint16_t numRows; /**< number of rows of the matrix. */
+ uint16_t numCols; /**< number of columns of the matrix. */
+ float16_t *pData; /**< points to the data of the matrix. */
+ } arm_matrix_instance_f16;
+
+ /**
+ * @brief Floating-point matrix addition.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_add_f16(
+ const arm_matrix_instance_f16 * pSrcA,
+ const arm_matrix_instance_f16 * pSrcB,
+ arm_matrix_instance_f16 * pDst);
+
+ /**
+ * @brief Floating-point, complex, matrix multiplication.
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_cmplx_mult_f16(
+ const arm_matrix_instance_f16 * pSrcA,
+ const arm_matrix_instance_f16 * pSrcB,
+ arm_matrix_instance_f16 * pDst);
+
+ /**
+ * @brief Floating-point matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_trans_f16(
+ const arm_matrix_instance_f16 * pSrc,
+ arm_matrix_instance_f16 * pDst);
+
+ /**
+ * @brief Floating-point complex matrix transpose.
+ * @param[in] pSrc points to the input matrix
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either ARM_MATH_SIZE_MISMATCH
+ * or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_cmplx_trans_f16(
+ const arm_matrix_instance_f16 * pSrc,
+ arm_matrix_instance_f16 * pDst);
+
+ /**
+ * @brief Floating-point matrix multiplication
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_mult_f16(
+ const arm_matrix_instance_f16 * pSrcA,
+ const arm_matrix_instance_f16 * pSrcB,
+ arm_matrix_instance_f16 * pDst);
+ /**
+ * @brief Floating-point matrix and vector multiplication
+ * @param[in] pSrcMat points to the input matrix structure
+ * @param[in] pVec points to vector
+ * @param[out] pDst points to output vector
+ */
+void arm_mat_vec_mult_f16(
+ const arm_matrix_instance_f16 *pSrcMat,
+ const float16_t *pVec,
+ float16_t *pDst);
+
+ /**
+ * @brief Floating-point matrix subtraction
+ * @param[in] pSrcA points to the first input matrix structure
+ * @param[in] pSrcB points to the second input matrix structure
+ * @param[out] pDst points to output matrix structure
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_sub_f16(
+ const arm_matrix_instance_f16 * pSrcA,
+ const arm_matrix_instance_f16 * pSrcB,
+ arm_matrix_instance_f16 * pDst);
+
+ /**
+ * @brief Floating-point matrix scaling.
+ * @param[in] pSrc points to the input matrix
+ * @param[in] scale scale factor
+ * @param[out] pDst points to the output matrix
+ * @return The function returns either
+ * ARM_MATH_SIZE_MISMATCH or ARM_MATH_SUCCESS based on the outcome of size checking.
+ */
+arm_status arm_mat_scale_f16(
+ const arm_matrix_instance_f16 * pSrc,
+ float16_t scale,
+ arm_matrix_instance_f16 * pDst);
+
+ /**
+ * @brief Floating-point matrix initialization.
+ * @param[in,out] S points to an instance of the floating-point matrix structure.
+ * @param[in] nRows number of rows in the matrix.
+ * @param[in] nColumns number of columns in the matrix.
+ * @param[in] pData points to the matrix data array.
+ */
+void arm_mat_init_f16(
+ arm_matrix_instance_f16 * S,
+ uint16_t nRows,
+ uint16_t nColumns,
+ float16_t * pData);
+
+
+ /**
+ * @brief Floating-point matrix inverse.
+ * @param[in] src points to the instance of the input floating-point matrix structure.
+ * @param[out] dst points to the instance of the output floating-point matrix structure.
+ * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
+ * If the input matrix is singular (does not have an inverse), then the algorithm terminates and returns error status ARM_MATH_SINGULAR.
+ */
+ arm_status arm_mat_inverse_f16(
+ const arm_matrix_instance_f16 * src,
+ arm_matrix_instance_f16 * dst);
+
+
+ /**
+ * @brief Floating-point Cholesky decomposition of Symmetric Positive Definite Matrix.
+ * @param[in] src points to the instance of the input floating-point matrix structure.
+ * @param[out] dst points to the instance of the output floating-point matrix structure.
+ * @return The function returns ARM_MATH_SIZE_MISMATCH, if the dimensions do not match.
+ * If the input matrix does not have a decomposition, then the algorithm terminates and returns error status ARM_MATH_DECOMPOSITION_FAILURE.
+ * If the matrix is ill conditioned or only semi-definite, then it is better using the LDL^t decomposition.
+ * The decomposition is returning a lower triangular matrix.
+ */
+ arm_status arm_mat_cholesky_f16(
+ const arm_matrix_instance_f16 * src,
+ arm_matrix_instance_f16 * dst);
+
+ /**
+ * @brief Solve UT . X = A where UT is an upper triangular matrix
+ * @param[in] ut The upper triangular matrix
+ * @param[in] a The matrix a
+ * @param[out] dst The solution X of UT . X = A
+ * @return The function returns ARM_MATH_SINGULAR, if the system can't be solved.
+ */
+ arm_status arm_mat_solve_upper_triangular_f16(
+ const arm_matrix_instance_f16 * ut,
+ const arm_matrix_instance_f16 * a,
+ arm_matrix_instance_f16 * dst);
+
+ /**
+ * @brief Solve LT . X = A where LT is a lower triangular matrix
+ * @param[in] lt The lower triangular matrix
+ * @param[in] a The matrix a
+ * @param[out] dst The solution X of LT . X = A
+ * @return The function returns ARM_MATH_SINGULAR, if the system can't be solved.
+ */
+ arm_status arm_mat_solve_lower_triangular_f16(
+ const arm_matrix_instance_f16 * lt,
+ const arm_matrix_instance_f16 * a,
+ arm_matrix_instance_f16 * dst);
+
+
+/**
+ @brief QR decomposition of a m x n floating point matrix with m >= n.
+ @param[in] pSrc points to input matrix structure. The source matrix is modified by the function.
+ @param[in] threshold norm2 threshold.
+ @param[out] pOutR points to output R matrix structure of dimension m x n
+ @param[out] pOutQ points to output Q matrix structure of dimension m x m
+ @param[out] pOutTau points to Householder scaling factors of dimension n
+ @param[inout] pTmpA points to a temporary vector of dimension m.
+ @param[inout] pTmpB points to a temporary vector of dimension n.
+ @return execution status
+ - \ref ARM_MATH_SUCCESS : Operation successful
+ - \ref ARM_MATH_SIZE_MISMATCH : Matrix size check failed
+ - \ref ARM_MATH_SINGULAR : Input matrix is found to be singular (non-invertible)
+ */
+
+arm_status arm_mat_qr_f16(
+ const arm_matrix_instance_f16 * pSrc,
+ const float16_t threshold,
+ arm_matrix_instance_f16 * pOutR,
+ arm_matrix_instance_f16 * pOutQ,
+ float16_t * pOutTau,
+ float16_t *pTmpA,
+ float16_t *pTmpB
+ );
+
+/**
+ @brief Householder transform of a half floating point vector.
+ @param[in] pSrc points to the input vector.
+ @param[in] threshold norm2 threshold.
+ @param[in] blockSize dimension of the vector space.
+ @param[outQ] pOut points to the output vector.
+ @return beta return the scaling factor beta
+ */
+
+float16_t arm_householder_f16(
+ const float16_t * pSrc,
+ const float16_t threshold,
+ uint32_t blockSize,
+ float16_t * pOut
+ );
+
+#endif /*defined(ARM_FLOAT16_SUPPORTED)*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _MATRIX_FUNCTIONS_F16_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/matrix_utils.h b/Middlewares/ST/ARM/DSP/Include/dsp/matrix_utils.h
new file mode 100644
index 0000000..92ed279
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/matrix_utils.h
@@ -0,0 +1,640 @@
+/******************************************************************************
+ * @file matrix_utils.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.11.0
+ * @date 30 May 2022
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2022 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _MATRIX_UTILS_H_
+#define _MATRIX_UTILS_H_
+
+#include "arm_math_types.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#define ELEM(A,ROW,COL) &((A)->pData[(A)->numCols* (ROW) + (COL)])
+
+#define SCALE_COL_T(T,CAST,A,ROW,v,i) \
+{ \
+ int32_t w; \
+ T *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ const int32_t nb = (A)->numRows - ROW;\
+ \
+ data += i + numCols * (ROW); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *data *= CAST v; \
+ data += numCols; \
+ } \
+}
+
+#define COPY_COL_T(T,A,ROW,COL,DST) \
+{ \
+ uint32_t row; \
+ T *pb=DST; \
+ T *pa = (A)->pData + ROW * (A)->numCols + COL;\
+ for(row = ROW; row < (A)->numRows; row ++) \
+ { \
+ *pb++ = *pa; \
+ pa += (A)->numCols; \
+ } \
+}
+
+#if defined(ARM_FLOAT16_SUPPORTED)
+#if defined(ARM_MATH_MVE_FLOAT16) && !defined(ARM_MATH_AUTOVECTORIZE)
+
+#define SWAP_ROWS_F16(A,COL,i,j) \
+ { \
+ int cnt = ((A)->numCols)-(COL); \
+ int32_t w; \
+ float16_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ \
+ for(w=(COL);w < numCols; w+=8) \
+ { \
+ f16x8_t tmpa,tmpb; \
+ mve_pred16_t p0 = vctp16q(cnt); \
+ \
+ tmpa=vldrhq_z_f16(&data[i*numCols + w],p0);\
+ tmpb=vldrhq_z_f16(&data[j*numCols + w],p0);\
+ \
+ vstrhq_p(&data[i*numCols + w], tmpb, p0); \
+ vstrhq_p(&data[j*numCols + w], tmpa, p0); \
+ \
+ cnt -= 8; \
+ } \
+ }
+
+#define SCALE_ROW_F16(A,COL,v,i) \
+{ \
+ int cnt = ((A)->numCols)-(COL); \
+ int32_t w; \
+ float16_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ \
+ for(w=(COL);w < numCols; w+=8) \
+ { \
+ f16x8_t tmpa; \
+ mve_pred16_t p0 = vctp16q(cnt); \
+ tmpa = vldrhq_z_f16(&data[i*numCols + w],p0);\
+ tmpa = vmulq_n_f16(tmpa,(_Float16)v); \
+ vstrhq_p(&data[i*numCols + w], tmpa, p0); \
+ cnt -= 8; \
+ } \
+ \
+}
+
+#define MAC_ROW_F16(COL,A,i,v,B,j) \
+{ \
+ int cnt = ((A)->numCols)-(COL); \
+ int32_t w; \
+ float16_t *dataA = (A)->pData; \
+ float16_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ \
+ for(w=(COL);w < numCols; w+=8) \
+ { \
+ f16x8_t tmpa,tmpb; \
+ mve_pred16_t p0 = vctp16q(cnt); \
+ tmpa = vldrhq_z_f16(&dataA[i*numCols + w],p0);\
+ tmpb = vldrhq_z_f16(&dataB[j*numCols + w],p0);\
+ tmpa = vfmaq_n_f16(tmpa,tmpb,v); \
+ vstrhq_p(&dataA[i*numCols + w], tmpa, p0); \
+ cnt -= 8; \
+ } \
+ \
+}
+
+#define MAS_ROW_F16(COL,A,i,v,B,j) \
+{ \
+ int cnt = ((A)->numCols)-(COL); \
+ int32_t w; \
+ float16_t *dataA = (A)->pData; \
+ float16_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ f16x8_t vec=vdupq_n_f16(v); \
+ \
+ for(w=(COL);w < numCols; w+=8) \
+ { \
+ f16x8_t tmpa,tmpb; \
+ mve_pred16_t p0 = vctp16q(cnt); \
+ tmpa = vldrhq_z_f16(&dataA[i*numCols + w],p0);\
+ tmpb = vldrhq_z_f16(&dataB[j*numCols + w],p0);\
+ tmpa = vfmsq_f16(tmpa,tmpb,vec); \
+ vstrhq_p(&dataA[i*numCols + w], tmpa, p0); \
+ cnt -= 8; \
+ } \
+ \
+}
+
+#else
+
+
+#define SWAP_ROWS_F16(A,COL,i,j) \
+{ \
+ int32_t w; \
+ float16_t *dataI = (A)->pData; \
+ float16_t *dataJ = (A)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols-(COL); \
+ \
+ dataI += i*numCols + (COL); \
+ dataJ += j*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ float16_t tmp; \
+ tmp = *dataI; \
+ *dataI++ = *dataJ; \
+ *dataJ++ = tmp; \
+ } \
+}
+
+#define SCALE_ROW_F16(A,COL,v,i) \
+{ \
+ int32_t w; \
+ float16_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols-(COL); \
+ \
+ data += i*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *data++ *= (_Float16)v; \
+ } \
+}
+
+
+#define MAC_ROW_F16(COL,A,i,v,B,j) \
+{ \
+ int32_t w; \
+ float16_t *dataA = (A)->pData; \
+ float16_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ const int32_t nb = numCols-(COL); \
+ \
+ dataA += i*numCols + (COL); \
+ dataB += j*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *dataA++ += (_Float16)v * (_Float16)*dataB++;\
+ } \
+}
+
+#define MAS_ROW_F16(COL,A,i,v,B,j) \
+{ \
+ int32_t w; \
+ float16_t *dataA = (A)->pData; \
+ float16_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ const int32_t nb = numCols-(COL); \
+ \
+ dataA += i*numCols + (COL); \
+ dataB += j*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *dataA++ -= (_Float16)v * (_Float16)*dataB++;\
+ } \
+}
+
+#endif /*defined(ARM_MATH_MVE_FLOAT16) && !defined(ARM_MATH_AUTOVECTORIZE)*/
+
+/* Functions with only a scalar version */
+#define COPY_COL_F16(A,ROW,COL,DST) \
+ COPY_COL_T(float16_t,A,ROW,COL,DST)
+
+#define SCALE_COL_F16(A,ROW,v,i) \
+ SCALE_COL_T(float16_t,(_Float16),A,ROW,v,i)
+
+#endif /* defined(ARM_FLOAT16_SUPPORTED)*/
+
+#if defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE)
+
+#define SWAP_ROWS_F32(A,COL,i,j) \
+ { \
+ int cnt = ((A)->numCols)-(COL); \
+ float32_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ int32_t w; \
+ \
+ for(w=(COL);w < numCols; w+=4) \
+ { \
+ f32x4_t tmpa,tmpb; \
+ mve_pred16_t p0 = vctp32q(cnt); \
+ \
+ tmpa=vldrwq_z_f32(&data[i*numCols + w],p0);\
+ tmpb=vldrwq_z_f32(&data[j*numCols + w],p0);\
+ \
+ vstrwq_p(&data[i*numCols + w], tmpb, p0); \
+ vstrwq_p(&data[j*numCols + w], tmpa, p0); \
+ \
+ cnt -= 4; \
+ } \
+ }
+
+#define MAC_ROW_F32(COL,A,i,v,B,j) \
+{ \
+ int cnt = ((A)->numCols)-(COL); \
+ float32_t *dataA = (A)->pData; \
+ float32_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ int32_t w; \
+ \
+ for(w=(COL);w < numCols; w+=4) \
+ { \
+ f32x4_t tmpa,tmpb; \
+ mve_pred16_t p0 = vctp32q(cnt); \
+ tmpa = vldrwq_z_f32(&dataA[i*numCols + w],p0);\
+ tmpb = vldrwq_z_f32(&dataB[j*numCols + w],p0);\
+ tmpa = vfmaq_n_f32(tmpa,tmpb,v); \
+ vstrwq_p(&dataA[i*numCols + w], tmpa, p0); \
+ cnt -= 4; \
+ } \
+ \
+}
+
+#define MAS_ROW_F32(COL,A,i,v,B,j) \
+{ \
+ int cnt = ((A)->numCols)-(COL); \
+ float32_t *dataA = (A)->pData; \
+ float32_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ int32_t w; \
+ f32x4_t vec=vdupq_n_f32(v); \
+ \
+ for(w=(COL);w < numCols; w+=4) \
+ { \
+ f32x4_t tmpa,tmpb; \
+ mve_pred16_t p0 = vctp32q(cnt); \
+ tmpa = vldrwq_z_f32(&dataA[i*numCols + w],p0);\
+ tmpb = vldrwq_z_f32(&dataB[j*numCols + w],p0);\
+ tmpa = vfmsq_f32(tmpa,tmpb,vec); \
+ vstrwq_p(&dataA[i*numCols + w], tmpa, p0); \
+ cnt -= 4; \
+ } \
+ \
+}
+
+#define SCALE_ROW_F32(A,COL,v,i) \
+{ \
+ int cnt = ((A)->numCols)-(COL); \
+ float32_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ int32_t w; \
+ \
+ for(w=(COL);w < numCols; w+=4) \
+ { \
+ f32x4_t tmpa; \
+ mve_pred16_t p0 = vctp32q(cnt); \
+ tmpa = vldrwq_z_f32(&data[i*numCols + w],p0);\
+ tmpa = vmulq_n_f32(tmpa,v); \
+ vstrwq_p(&data[i*numCols + w], tmpa, p0); \
+ cnt -= 4; \
+ } \
+ \
+}
+
+#elif defined(ARM_MATH_NEON) && !defined(ARM_MATH_AUTOVECTORIZE)
+
+#define SWAP_ROWS_F32(A,COL,i,j) \
+{ \
+ int32_t w; \
+ float32_t *dataI = (A)->pData; \
+ float32_t *dataJ = (A)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols - COL; \
+ \
+ dataI += i*numCols + (COL); \
+ dataJ += j*numCols + (COL); \
+ \
+ float32_t tmp; \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ tmp = *dataI; \
+ *dataI++ = *dataJ; \
+ *dataJ++ = tmp; \
+ } \
+}
+
+#define MAC_ROW_F32(COL,A,i,v,B,j) \
+{ \
+ float32_t *dataA = (A)->pData; \
+ float32_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols - (COL); \
+ int32_t nbElems; \
+ f32x4_t vec = vdupq_n_f32(v); \
+ \
+ nbElems = nb >> 2; \
+ \
+ dataA += i*numCols + (COL); \
+ dataB += j*numCols + (COL); \
+ \
+ while(nbElems>0) \
+ { \
+ f32x4_t tmpa,tmpb; \
+ tmpa = vld1q_f32(dataA,p0); \
+ tmpb = vld1q_f32(dataB,p0); \
+ tmpa = vmlaq_f32(tmpa,tmpb,vec);\
+ vst1q_f32(dataA, tmpa, p0); \
+ nbElems--; \
+ dataA += 4; \
+ dataB += 4; \
+ } \
+ \
+ nbElems = nb & 3; \
+ while(nbElems > 0) \
+ { \
+ *dataA++ += v* *dataB++; \
+ nbElems--; \
+ } \
+}
+
+#define MAS_ROW_F32(COL,A,i,v,B,j) \
+{ \
+ float32_t *dataA = (A)->pData; \
+ float32_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols - (COL); \
+ int32_t nbElems; \
+ f32x4_t vec = vdupq_n_f32(v); \
+ \
+ nbElems = nb >> 2; \
+ \
+ dataA += i*numCols + (COL); \
+ dataB += j*numCols + (COL); \
+ \
+ while(nbElems>0) \
+ { \
+ f32x4_t tmpa,tmpb; \
+ tmpa = vld1q_f32(dataA); \
+ tmpb = vld1q_f32(dataB); \
+ tmpa = vmlsq_f32(tmpa,tmpb,vec);\
+ vst1q_f32(dataA, tmpa); \
+ nbElems--; \
+ dataA += 4; \
+ dataB += 4; \
+ } \
+ \
+ nbElems = nb & 3; \
+ while(nbElems > 0) \
+ { \
+ *dataA++ -= v* *dataB++; \
+ nbElems--; \
+ } \
+}
+
+#define SCALE_ROW_F32(A,COL,v,i) \
+{ \
+ float32_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ const int32_t nb = numCols - (COL); \
+ int32_t nbElems; \
+ f32x4_t vec = vdupq_n_f32(v); \
+ \
+ nbElems = nb >> 2; \
+ \
+ data += i*numCols + (COL); \
+ while(nbElems>0) \
+ { \
+ f32x4_t tmpa; \
+ tmpa = vld1q_f32(data); \
+ tmpa = vmulq_f32(tmpa,vec); \
+ vst1q_f32(data, tmpa); \
+ data += 4; \
+ nbElems --; \
+ } \
+ \
+ nbElems = nb & 3; \
+ while(nbElems > 0) \
+ { \
+ *data++ *= v; \
+ nbElems--; \
+ } \
+ \
+}
+
+#else
+
+#define SWAP_ROWS_F32(A,COL,i,j) \
+{ \
+ int32_t w; \
+ float32_t tmp; \
+ float32_t *dataI = (A)->pData; \
+ float32_t *dataJ = (A)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols - COL; \
+ \
+ dataI += i*numCols + (COL); \
+ dataJ += j*numCols + (COL); \
+ \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ tmp = *dataI; \
+ *dataI++ = *dataJ; \
+ *dataJ++ = tmp; \
+ } \
+}
+
+#define SCALE_ROW_F32(A,COL,v,i) \
+{ \
+ int32_t w; \
+ float32_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols - COL; \
+ \
+ data += i*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *data++ *= v; \
+ } \
+}
+
+
+#define MAC_ROW_F32(COL,A,i,v,B,j) \
+{ \
+ int32_t w; \
+ float32_t *dataA = (A)->pData; \
+ float32_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols-(COL); \
+ \
+ dataA = dataA + i*numCols + (COL); \
+ dataB = dataB + j*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *dataA++ += v* *dataB++; \
+ } \
+}
+
+#define MAS_ROW_F32(COL,A,i,v,B,j) \
+{ \
+ int32_t w; \
+ float32_t *dataA = (A)->pData; \
+ float32_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols-(COL); \
+ \
+ dataA = dataA + i*numCols + (COL); \
+ dataB = dataB + j*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *dataA++ -= v* *dataB++; \
+ } \
+}
+
+#endif /* defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE) */
+
+
+/* Functions with only a scalar version */
+
+#define COPY_COL_F32(A,ROW,COL,DST) \
+ COPY_COL_T(float32_t,A,ROW,COL,DST)
+
+#define COPY_COL_F64(A,ROW,COL,DST) \
+ COPY_COL_T(float64_t,A,ROW,COL,DST)
+
+#define SWAP_COLS_F32(A,COL,i,j) \
+{ \
+ int32_t w; \
+ float32_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ for(w=(COL);w < numCols; w++) \
+ { \
+ float32_t tmp; \
+ tmp = data[w*numCols + i]; \
+ data[w*numCols + i] = data[w*numCols + j];\
+ data[w*numCols + j] = tmp; \
+ } \
+}
+
+#define SCALE_COL_F32(A,ROW,v,i) \
+ SCALE_COL_T(float32_t,,A,ROW,v,i)
+
+#define SWAP_ROWS_F64(A,COL,i,j) \
+{ \
+ int32_t w; \
+ float64_t *dataI = (A)->pData; \
+ float64_t *dataJ = (A)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols-(COL); \
+ \
+ dataI += i*numCols + (COL); \
+ dataJ += j*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ float64_t tmp; \
+ tmp = *dataI; \
+ *dataI++ = *dataJ; \
+ *dataJ++ = tmp; \
+ } \
+}
+
+#define SWAP_COLS_F64(A,COL,i,j) \
+{ \
+ int32_t w; \
+ float64_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols; \
+ for(w=(COL);w < numCols; w++) \
+ { \
+ float64_t tmp; \
+ tmp = data[w*numCols + i]; \
+ data[w*numCols + i] = data[w*numCols + j];\
+ data[w*numCols + j] = tmp; \
+ } \
+}
+
+#define SCALE_ROW_F64(A,COL,v,i) \
+{ \
+ int32_t w; \
+ float64_t *data = (A)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols-(COL); \
+ \
+ data += i*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *data++ *= v; \
+ } \
+}
+
+#define SCALE_COL_F64(A,ROW,v,i) \
+ SCALE_COL_T(float64_t,,A,ROW,v,i)
+
+#define MAC_ROW_F64(COL,A,i,v,B,j) \
+{ \
+ int32_t w; \
+ float64_t *dataA = (A)->pData; \
+ float64_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols-(COL); \
+ \
+ dataA += i*numCols + (COL); \
+ dataB += j*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *dataA++ += v* *dataB++; \
+ } \
+}
+
+#define MAS_ROW_F64(COL,A,i,v,B,j) \
+{ \
+ int32_t w; \
+ float64_t *dataA = (A)->pData; \
+ float64_t *dataB = (B)->pData; \
+ const int32_t numCols = (A)->numCols;\
+ const int32_t nb = numCols-(COL); \
+ \
+ dataA += i*numCols + (COL); \
+ dataB += j*numCols + (COL); \
+ \
+ for(w=0;w < nb; w++) \
+ { \
+ *dataA++ -= v* *dataB++; \
+ } \
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _MATRIX_UTILS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/none.h b/Middlewares/ST/ARM/DSP/Include/dsp/none.h
new file mode 100644
index 0000000..130386e
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/none.h
@@ -0,0 +1,576 @@
+/******************************************************************************
+ * @file none.h
+ * @brief Intrinsincs when no DSP extension available
+ * @version V1.9.0
+ * @date 20. July 2020
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+
+Definitions in this file are allowing to reuse some versions of the
+CMSIS-DSP to build on a core (M0 for instance) or a host where
+DSP extension are not available.
+
+Ideally a pure C version should have been used instead.
+But those are not always available or use a restricted set
+of intrinsics.
+
+*/
+
+#ifndef _NONE_H_
+#define _NONE_H_
+
+#include "arm_math_types.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+
+/*
+
+Normally those kind of definitions are in a compiler file
+in Core or Core_A.
+
+But for MSVC compiler it is a bit special. The goal is very specific
+to CMSIS-DSP and only to allow the use of this library from other
+systems like Python or Matlab.
+
+MSVC is not going to be used to cross-compile to ARM. So, having a MSVC
+compiler file in Core or Core_A would not make sense.
+
+*/
+#if defined ( _MSC_VER ) || defined(__GNUC_PYTHON__) || defined(__APPLE_CC__)
+ __STATIC_FORCEINLINE uint8_t __CLZ(uint32_t data)
+ {
+ if (data == 0U) { return 32U; }
+
+ uint32_t count = 0U;
+ uint32_t mask = 0x80000000U;
+
+ while ((data & mask) == 0U)
+ {
+ count += 1U;
+ mask = mask >> 1U;
+ }
+ return count;
+ }
+
+ __STATIC_FORCEINLINE int32_t __SSAT(int32_t val, uint32_t sat)
+ {
+ if ((sat >= 1U) && (sat <= 32U))
+ {
+ const int32_t max = (int32_t)((1U << (sat - 1U)) - 1U);
+ const int32_t min = -1 - max ;
+ if (val > max)
+ {
+ return max;
+ }
+ else if (val < min)
+ {
+ return min;
+ }
+ }
+ return val;
+ }
+
+ __STATIC_FORCEINLINE uint32_t __USAT(int32_t val, uint32_t sat)
+ {
+ if (sat <= 31U)
+ {
+ const uint32_t max = ((1U << sat) - 1U);
+ if (val > (int32_t)max)
+ {
+ return max;
+ }
+ else if (val < 0)
+ {
+ return 0U;
+ }
+ }
+ return (uint32_t)val;
+ }
+
+ /**
+ \brief Rotate Right in unsigned value (32 bit)
+ \details Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
+ \param [in] op1 Value to rotate
+ \param [in] op2 Number of Bits to rotate
+ \return Rotated value
+ */
+__STATIC_FORCEINLINE uint32_t __ROR(uint32_t op1, uint32_t op2)
+{
+ op2 %= 32U;
+ if (op2 == 0U)
+ {
+ return op1;
+ }
+ return (op1 >> op2) | (op1 << (32U - op2));
+}
+
+
+#endif
+
+/**
+ * @brief Clips Q63 to Q31 values.
+ */
+ __STATIC_FORCEINLINE q31_t clip_q63_to_q31(
+ q63_t x)
+ {
+ return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ?
+ ((0x7FFFFFFF ^ ((q31_t) (x >> 63)))) : (q31_t) x;
+ }
+
+ /**
+ * @brief Clips Q63 to Q15 values.
+ */
+ __STATIC_FORCEINLINE q15_t clip_q63_to_q15(
+ q63_t x)
+ {
+ return ((q31_t) (x >> 32) != ((q31_t) x >> 31)) ?
+ ((0x7FFF ^ ((q15_t) (x >> 63)))) : (q15_t) (x >> 15);
+ }
+
+ /**
+ * @brief Clips Q31 to Q7 values.
+ */
+ __STATIC_FORCEINLINE q7_t clip_q31_to_q7(
+ q31_t x)
+ {
+ return ((q31_t) (x >> 24) != ((q31_t) x >> 23)) ?
+ ((0x7F ^ ((q7_t) (x >> 31)))) : (q7_t) x;
+ }
+
+ /**
+ * @brief Clips Q31 to Q15 values.
+ */
+ __STATIC_FORCEINLINE q15_t clip_q31_to_q15(
+ q31_t x)
+ {
+ return ((q31_t) (x >> 16) != ((q31_t) x >> 15)) ?
+ ((0x7FFF ^ ((q15_t) (x >> 31)))) : (q15_t) x;
+ }
+
+ /**
+ * @brief Multiplies 32 X 64 and returns 32 bit result in 2.30 format.
+ */
+ __STATIC_FORCEINLINE q63_t mult32x64(
+ q63_t x,
+ q31_t y)
+ {
+ return ((((q63_t) (x & 0x00000000FFFFFFFF) * y) >> 32) +
+ (((q63_t) (x >> 32) * y) ) );
+ }
+
+/* SMMLAR */
+#define multAcc_32x32_keep32_R(a, x, y) \
+ a = (q31_t) (((((q63_t) a) << 32) + ((q63_t) x * y) + 0x80000000LL ) >> 32)
+
+/* SMMLSR */
+#define multSub_32x32_keep32_R(a, x, y) \
+ a = (q31_t) (((((q63_t) a) << 32) - ((q63_t) x * y) + 0x80000000LL ) >> 32)
+
+/* SMMULR */
+#define mult_32x32_keep32_R(a, x, y) \
+ a = (q31_t) (((q63_t) x * y + 0x80000000LL ) >> 32)
+
+/* SMMLA */
+#define multAcc_32x32_keep32(a, x, y) \
+ a += (q31_t) (((q63_t) x * y) >> 32)
+
+/* SMMLS */
+#define multSub_32x32_keep32(a, x, y) \
+ a -= (q31_t) (((q63_t) x * y) >> 32)
+
+/* SMMUL */
+#define mult_32x32_keep32(a, x, y) \
+ a = (q31_t) (((q63_t) x * y ) >> 32)
+
+#ifndef ARM_MATH_DSP
+ /**
+ * @brief definition to pack two 16 bit values.
+ */
+ #define __PKHBT(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0x0000FFFF) | \
+ (((int32_t)(ARG2) << ARG3) & (int32_t)0xFFFF0000) )
+ #define __PKHTB(ARG1, ARG2, ARG3) ( (((int32_t)(ARG1) << 0) & (int32_t)0xFFFF0000) | \
+ (((int32_t)(ARG2) >> ARG3) & (int32_t)0x0000FFFF) )
+#endif
+
+ /**
+ * @brief definition to pack four 8 bit values.
+ */
+#ifndef ARM_MATH_BIG_ENDIAN
+ #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v0) << 0) & (int32_t)0x000000FF) | \
+ (((int32_t)(v1) << 8) & (int32_t)0x0000FF00) | \
+ (((int32_t)(v2) << 16) & (int32_t)0x00FF0000) | \
+ (((int32_t)(v3) << 24) & (int32_t)0xFF000000) )
+#else
+ #define __PACKq7(v0,v1,v2,v3) ( (((int32_t)(v3) << 0) & (int32_t)0x000000FF) | \
+ (((int32_t)(v2) << 8) & (int32_t)0x0000FF00) | \
+ (((int32_t)(v1) << 16) & (int32_t)0x00FF0000) | \
+ (((int32_t)(v0) << 24) & (int32_t)0xFF000000) )
+#endif
+
+
+
+
+/*
+ * @brief C custom defined intrinsic functions
+ */
+#if !defined (ARM_MATH_DSP)
+
+
+ /*
+ * @brief C custom defined QADD8
+ */
+ __STATIC_FORCEINLINE uint32_t __QADD8(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s, t, u;
+
+ r = __SSAT(((((q31_t)x << 24) >> 24) + (((q31_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF;
+ s = __SSAT(((((q31_t)x << 16) >> 24) + (((q31_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF;
+ t = __SSAT(((((q31_t)x << 8) >> 24) + (((q31_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF;
+ u = __SSAT(((((q31_t)x ) >> 24) + (((q31_t)y ) >> 24)), 8) & (int32_t)0x000000FF;
+
+ return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QSUB8
+ */
+ __STATIC_FORCEINLINE uint32_t __QSUB8(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s, t, u;
+
+ r = __SSAT(((((q31_t)x << 24) >> 24) - (((q31_t)y << 24) >> 24)), 8) & (int32_t)0x000000FF;
+ s = __SSAT(((((q31_t)x << 16) >> 24) - (((q31_t)y << 16) >> 24)), 8) & (int32_t)0x000000FF;
+ t = __SSAT(((((q31_t)x << 8) >> 24) - (((q31_t)y << 8) >> 24)), 8) & (int32_t)0x000000FF;
+ u = __SSAT(((((q31_t)x ) >> 24) - (((q31_t)y ) >> 24)), 8) & (int32_t)0x000000FF;
+
+ return ((uint32_t)((u << 24) | (t << 16) | (s << 8) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QADD16
+ */
+ __STATIC_FORCEINLINE uint32_t __QADD16(
+ uint32_t x,
+ uint32_t y)
+ {
+/* q31_t r, s; without initialisation 'arm_offset_q15 test' fails but 'intrinsic' tests pass! for armCC */
+ q31_t r = 0, s = 0;
+
+ r = __SSAT(((((q31_t)x << 16) >> 16) + (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
+ s = __SSAT(((((q31_t)x ) >> 16) + (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SHADD16
+ */
+ __STATIC_FORCEINLINE uint32_t __SHADD16(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = (((((q31_t)x << 16) >> 16) + (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+ s = (((((q31_t)x ) >> 16) + (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QSUB16
+ */
+ __STATIC_FORCEINLINE uint32_t __QSUB16(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = __SSAT(((((q31_t)x << 16) >> 16) - (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
+ s = __SSAT(((((q31_t)x ) >> 16) - (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SHSUB16
+ */
+ __STATIC_FORCEINLINE uint32_t __SHSUB16(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = (((((q31_t)x << 16) >> 16) - (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+ s = (((((q31_t)x ) >> 16) - (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QASX
+ */
+ __STATIC_FORCEINLINE uint32_t __QASX(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = __SSAT(((((q31_t)x << 16) >> 16) - (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
+ s = __SSAT(((((q31_t)x ) >> 16) + (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SHASX
+ */
+ __STATIC_FORCEINLINE uint32_t __SHASX(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = (((((q31_t)x << 16) >> 16) - (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+ s = (((((q31_t)x ) >> 16) + (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined QSAX
+ */
+ __STATIC_FORCEINLINE uint32_t __QSAX(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = __SSAT(((((q31_t)x << 16) >> 16) + (((q31_t)y ) >> 16)), 16) & (int32_t)0x0000FFFF;
+ s = __SSAT(((((q31_t)x ) >> 16) - (((q31_t)y << 16) >> 16)), 16) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SHSAX
+ */
+ __STATIC_FORCEINLINE uint32_t __SHSAX(
+ uint32_t x,
+ uint32_t y)
+ {
+ q31_t r, s;
+
+ r = (((((q31_t)x << 16) >> 16) + (((q31_t)y ) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+ s = (((((q31_t)x ) >> 16) - (((q31_t)y << 16) >> 16)) >> 1) & (int32_t)0x0000FFFF;
+
+ return ((uint32_t)((s << 16) | (r )));
+ }
+
+
+ /*
+ * @brief C custom defined SMUSDX
+ */
+ __STATIC_FORCEINLINE uint32_t __SMUSDX(
+ uint32_t x,
+ uint32_t y)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) -
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) ));
+ }
+
+ /*
+ * @brief C custom defined SMUADX
+ */
+ __STATIC_FORCEINLINE uint32_t __SMUADX(
+ uint32_t x,
+ uint32_t y)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) ));
+ }
+
+
+ /*
+ * @brief C custom defined QADD
+ */
+ __STATIC_FORCEINLINE int32_t __QADD(
+ int32_t x,
+ int32_t y)
+ {
+ return ((int32_t)(clip_q63_to_q31((q63_t)x + (q31_t)y)));
+ }
+
+
+ /*
+ * @brief C custom defined QSUB
+ */
+ __STATIC_FORCEINLINE int32_t __QSUB(
+ int32_t x,
+ int32_t y)
+ {
+ return ((int32_t)(clip_q63_to_q31((q63_t)x - (q31_t)y)));
+ }
+
+
+ /*
+ * @brief C custom defined SMLAD
+ */
+ __STATIC_FORCEINLINE uint32_t __SMLAD(
+ uint32_t x,
+ uint32_t y,
+ uint32_t sum)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) +
+ ( ((q31_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMLADX
+ */
+ __STATIC_FORCEINLINE uint32_t __SMLADX(
+ uint32_t x,
+ uint32_t y,
+ uint32_t sum)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ( ((q31_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMLSDX
+ */
+ __STATIC_FORCEINLINE uint32_t __SMLSDX(
+ uint32_t x,
+ uint32_t y,
+ uint32_t sum)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) -
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ( ((q31_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMLALD
+ */
+ __STATIC_FORCEINLINE uint64_t __SMLALD(
+ uint32_t x,
+ uint32_t y,
+ uint64_t sum)
+ {
+/* return (sum + ((q15_t) (x >> 16) * (q15_t) (y >> 16)) + ((q15_t) x * (q15_t) y)); */
+ return ((uint64_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) +
+ ( ((q63_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMLALDX
+ */
+ __STATIC_FORCEINLINE uint64_t __SMLALDX(
+ uint32_t x,
+ uint32_t y,
+ uint64_t sum)
+ {
+/* return (sum + ((q15_t) (x >> 16) * (q15_t) y)) + ((q15_t) x * (q15_t) (y >> 16)); */
+ return ((uint64_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y ) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ( ((q63_t)sum ) ) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMUAD
+ */
+ __STATIC_FORCEINLINE uint32_t __SMUAD(
+ uint32_t x,
+ uint32_t y)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) +
+ ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) ));
+ }
+
+
+ /*
+ * @brief C custom defined SMUSD
+ */
+ __STATIC_FORCEINLINE uint32_t __SMUSD(
+ uint32_t x,
+ uint32_t y)
+ {
+ return ((uint32_t)(((((q31_t)x << 16) >> 16) * (((q31_t)y << 16) >> 16)) -
+ ((((q31_t)x ) >> 16) * (((q31_t)y ) >> 16)) ));
+ }
+
+
+ /*
+ * @brief C custom defined SXTB16
+ */
+ __STATIC_FORCEINLINE uint32_t __SXTB16(
+ uint32_t x)
+ {
+ return ((uint32_t)(((((q31_t)x << 24) >> 24) & (q31_t)0x0000FFFF) |
+ ((((q31_t)x << 8) >> 8) & (q31_t)0xFFFF0000) ));
+ }
+
+ /*
+ * @brief C custom defined SMMLA
+ */
+ __STATIC_FORCEINLINE int32_t __SMMLA(
+ int32_t x,
+ int32_t y,
+ int32_t sum)
+ {
+ return (sum + (int32_t) (((int64_t) x * y) >> 32));
+ }
+
+#endif /* !defined (ARM_MATH_DSP) */
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _TRANSFORM_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/quaternion_math_functions.h b/Middlewares/ST/ARM/DSP/Include/dsp/quaternion_math_functions.h
new file mode 100644
index 0000000..0c5d067
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/quaternion_math_functions.h
@@ -0,0 +1,159 @@
+/******************************************************************************
+ * @file quaternion_math_functions.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ *
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2021 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _QUATERNION_MATH_FUNCTIONS_H_
+#define _QUATERNION_MATH_FUNCTIONS_H_
+
+#include "arm_math_types.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @defgroup groupQuaternionMath Quaternion Math Functions
+ * Functions to operates on quaternions and convert between a
+ * rotation and quaternion representation.
+ */
+
+
+/**
+ @brief Floating-point quaternion Norm.
+ @param[in] pInputQuaternions points to the input vector of quaternions
+ @param[out] pNorms points to the output vector of norms
+ @param[in] nbQuaternions number of quaternions in each vector
+ @return none
+ */
+
+
+
+void arm_quaternion_norm_f32(const float32_t *pInputQuaternions,
+ float32_t *pNorms,
+ uint32_t nbQuaternions);
+
+
+/**
+ @brief Floating-point quaternion inverse.
+ @param[in] pInputQuaternions points to the input vector of quaternions
+ @param[out] pInverseQuaternions points to the output vector of inverse quaternions
+ @param[in] nbQuaternions number of quaternions in each vector
+ @return none
+ */
+
+void arm_quaternion_inverse_f32(const float32_t *pInputQuaternions,
+ float32_t *pInverseQuaternions,
+ uint32_t nbQuaternions);
+
+/**
+ @brief Floating-point quaternion conjugates.
+ @param[in] pInputQuaternions points to the input vector of quaternions
+ @param[out] pConjugateQuaternions points to the output vector of conjugate quaternions
+ @param[in] nbQuaternions number of quaternions in each vector
+ @return none
+ */
+void arm_quaternion_conjugate_f32(const float32_t *inputQuaternions,
+ float32_t *pConjugateQuaternions,
+ uint32_t nbQuaternions);
+
+/**
+ @brief Floating-point normalization of quaternions.
+ @param[in] pInputQuaternions points to the input vector of quaternions
+ @param[out] pNormalizedQuaternions points to the output vector of normalized quaternions
+ @param[in] nbQuaternions number of quaternions in each vector
+ @return none
+ */
+void arm_quaternion_normalize_f32(const float32_t *inputQuaternions,
+ float32_t *pNormalizedQuaternions,
+ uint32_t nbQuaternions);
+
+
+/**
+ @brief Floating-point product of two quaternions.
+ @param[in] qa First quaternion
+ @param[in] qb Second quaternion
+ @param[out] r Product of two quaternions
+ @return none
+ */
+void arm_quaternion_product_single_f32(const float32_t *qa,
+ const float32_t *qb,
+ float32_t *r);
+
+/**
+ @brief Floating-point elementwise product two quaternions.
+ @param[in] qa First array of quaternions
+ @param[in] qb Second array of quaternions
+ @param[out] r Elementwise product of quaternions
+ @param[in] nbQuaternions Number of quaternions in the array
+ @return none
+ */
+void arm_quaternion_product_f32(const float32_t *qa,
+ const float32_t *qb,
+ float32_t *r,
+ uint32_t nbQuaternions);
+
+/**
+ * @brief Conversion of quaternion to equivalent rotation matrix.
+ * @param[in] pInputQuaternions points to an array of normalized quaternions
+ * @param[out] pOutputRotations points to an array of 3x3 rotations (in row order)
+ * @param[in] nbQuaternions in the array
+ * @return none.
+ *
+ * Format of rotation matrix
+ * \par
+ * The quaternion a + ib + jc + kd is converted into rotation matrix:
+ * a^2 + b^2 - c^2 - d^2 2bc - 2ad 2bd + 2ac
+ * 2bc + 2ad a^2 - b^2 + c^2 - d^2 2cd - 2ab
+ * 2bd - 2ac 2cd + 2ab a^2 - b^2 - c^2 + d^2
+ *
+ * Rotation matrix is saved in row order : R00 R01 R02 R10 R11 R12 R20 R21 R22
+ */
+void arm_quaternion2rotation_f32(const float32_t *pInputQuaternions,
+ float32_t *pOutputRotations,
+ uint32_t nbQuaternions);
+
+/**
+ * @brief Conversion of a rotation matrix to equivalent quaternion.
+ * @param[in] pInputRotations points to an array 3x3 rotation matrix (in row order)
+ * @param[out] pOutputQuaternions points to an array of quaternions
+ * @param[in] nbQuaternions in the array
+ * @return none.
+*/
+void arm_rotation2quaternion_f32(const float32_t *pInputRotations,
+ float32_t *pOutputQuaternions,
+ uint32_t nbQuaternions);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _QUATERNION_MATH_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/statistics_functions.h b/Middlewares/ST/ARM/DSP/Include/dsp/statistics_functions.h
new file mode 100644
index 0000000..805b45d
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/statistics_functions.h
@@ -0,0 +1,1003 @@
+/******************************************************************************
+ * @file statistics_functions.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.1
+ * @date 14 July 2022
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _STATISTICS_FUNCTIONS_H_
+#define _STATISTICS_FUNCTIONS_H_
+
+#include "arm_math_types.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#include "dsp/basic_math_functions.h"
+#include "dsp/fast_math_functions.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+/**
+ * @defgroup groupStats Statistics Functions
+ */
+
+/**
+ * @brief Computation of the LogSumExp
+ *
+ * In probabilistic computations, the dynamic of the probability values can be very
+ * wide because they come from gaussian functions.
+ * To avoid underflow and overflow issues, the values are represented by their log.
+ * In this representation, multiplying the original exp values is easy : their logs are added.
+ * But adding the original exp values is requiring some special handling and it is the
+ * goal of the LogSumExp function.
+ *
+ * If the values are x1...xn, the function is computing:
+ *
+ * ln(exp(x1) + ... + exp(xn)) and the computation is done in such a way that
+ * rounding issues are minimised.
+ *
+ * The max xm of the values is extracted and the function is computing:
+ * xm + ln(exp(x1 - xm) + ... + exp(xn - xm))
+ *
+ * @param[in] *in Pointer to an array of input values.
+ * @param[in] blockSize Number of samples in the input array.
+ * @return LogSumExp
+ *
+ */
+
+
+float32_t arm_logsumexp_f32(const float32_t *in, uint32_t blockSize);
+
+/**
+ * @brief Dot product with log arithmetic
+ *
+ * Vectors are containing the log of the samples
+ *
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[in] blockSize number of samples in each vector
+ * @param[in] pTmpBuffer temporary buffer of length blockSize
+ * @return The log of the dot product .
+ *
+ */
+
+
+float32_t arm_logsumexp_dot_prod_f32(const float32_t * pSrcA,
+ const float32_t * pSrcB,
+ uint32_t blockSize,
+ float32_t *pTmpBuffer);
+
+/**
+ * @brief Entropy
+ *
+ * @param[in] pSrcA Array of input values.
+ * @param[in] blockSize Number of samples in the input array.
+ * @return Entropy -Sum(p ln p)
+ *
+ */
+
+
+float32_t arm_entropy_f32(const float32_t * pSrcA,uint32_t blockSize);
+
+
+/**
+ * @brief Entropy
+ *
+ * @param[in] pSrcA Array of input values.
+ * @param[in] blockSize Number of samples in the input array.
+ * @return Entropy -Sum(p ln p)
+ *
+ */
+
+
+float64_t arm_entropy_f64(const float64_t * pSrcA, uint32_t blockSize);
+
+
+/**
+ * @brief Kullback-Leibler
+ *
+ * @param[in] pSrcA Pointer to an array of input values for probability distribution A.
+ * @param[in] pSrcB Pointer to an array of input values for probability distribution B.
+ * @param[in] blockSize Number of samples in the input array.
+ * @return Kullback-Leibler Divergence D(A || B)
+ *
+ */
+float32_t arm_kullback_leibler_f32(const float32_t * pSrcA
+ ,const float32_t * pSrcB
+ ,uint32_t blockSize);
+
+
+/**
+ * @brief Kullback-Leibler
+ *
+ * @param[in] pSrcA Pointer to an array of input values for probability distribution A.
+ * @param[in] pSrcB Pointer to an array of input values for probability distribution B.
+ * @param[in] blockSize Number of samples in the input array.
+ * @return Kullback-Leibler Divergence D(A || B)
+ *
+ */
+float64_t arm_kullback_leibler_f64(const float64_t * pSrcA,
+ const float64_t * pSrcB,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Sum of the squares of the elements of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q63_t * pResult);
+
+
+ /**
+ * @brief Sum of the squares of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Sum of the squares of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult);
+
+
+ /**
+ * @brief Sum of the squares of the elements of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q63_t * pResult);
+
+
+ /**
+ * @brief Sum of the squares of the elements of a Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_q7(
+ const q7_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Mean value of a Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_q7(
+ const q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * pResult);
+
+
+ /**
+ * @brief Mean value of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+
+ /**
+ * @brief Mean value of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Mean value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Mean value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult);
+
+
+ /**
+ * @brief Variance of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_var_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Variance of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_var_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult);
+
+
+ /**
+ * @brief Variance of the elements of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_var_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Variance of the elements of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_var_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+
+ /**
+ * @brief Root Mean Square of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_rms_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Root Mean Square of the elements of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_rms_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Root Mean Square of the elements of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_rms_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+
+ /**
+ * @brief Standard deviation of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_std_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Standard deviation of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_std_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult);
+
+
+ /**
+ * @brief Standard deviation of the elements of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_std_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Standard deviation of the elements of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_std_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+
+
+ /**
+ * @brief Minimum value of a Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[in] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_q7(
+ const q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[in] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_absmin_q7(
+ const q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ */
+ void arm_absmin_no_idx_q7(
+ const q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * pResult);
+
+
+ /**
+ * @brief Minimum value of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[in] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Minimum value of absolute values of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[in] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_absmin_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ */
+ void arm_absmin_no_idx_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+
+ /**
+ * @brief Minimum value of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_absmin_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ */
+ void arm_absmin_no_idx_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+
+ /**
+ * @brief Minimum value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_absmin_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ */
+ void arm_absmin_no_idx_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+
+ /**
+ * @brief Minimum value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_absmin_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ */
+ void arm_absmin_no_idx_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult);
+
+
+/**
+ * @brief Maximum value of a Q7 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_q7(
+ const q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Maximum value of absolute values of a Q7 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_absmax_q7(
+ const q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Maximum value of absolute values of a Q7 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ */
+ void arm_absmax_no_idx_q7(
+ const q7_t * pSrc,
+ uint32_t blockSize,
+ q7_t * pResult);
+
+
+/**
+ * @brief Maximum value of a Q15 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Maximum value of absolute values of a Q15 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_absmax_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Maximum value of absolute values of a Q15 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ */
+ void arm_absmax_no_idx_q15(
+ const q15_t * pSrc,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+/**
+ * @brief Maximum value of a Q31 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Maximum value of absolute values of a Q31 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_absmax_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Maximum value of absolute values of a Q31 vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ */
+ void arm_absmax_no_idx_q31(
+ const q31_t * pSrc,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+/**
+ * @brief Maximum value of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Maximum value of absolute values of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_absmax_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Maximum value of absolute values of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ */
+ void arm_absmax_no_idx_f32(
+ const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+/**
+ * @brief Maximum value of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Maximum value of absolute values of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_absmax_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Maximum value of absolute values of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ */
+ void arm_absmax_no_idx_f64(
+ const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult);
+
+ /**
+ @brief Maximum value of a floating-point vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult maximum value returned here
+ @return none
+ */
+ void arm_max_no_idx_f32(
+ const float32_t *pSrc,
+ uint32_t blockSize,
+ float32_t *pResult);
+
+ /**
+ @brief Minimum value of a floating-point vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult minimum value returned here
+ @return none
+ */
+ void arm_min_no_idx_f32(
+ const float32_t *pSrc,
+ uint32_t blockSize,
+ float32_t *pResult);
+
+ /**
+ @brief Maximum value of a floating-point vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult maximum value returned here
+ @return none
+ */
+ void arm_max_no_idx_f64(
+ const float64_t *pSrc,
+ uint32_t blockSize,
+ float64_t *pResult);
+
+ /**
+ @brief Maximum value of a q31 vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult maximum value returned here
+ @return none
+ */
+ void arm_max_no_idx_q31(
+ const q31_t *pSrc,
+ uint32_t blockSize,
+ q31_t *pResult);
+
+ /**
+ @brief Maximum value of a q15 vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult maximum value returned here
+ @return none
+ */
+ void arm_max_no_idx_q15(
+ const q15_t *pSrc,
+ uint32_t blockSize,
+ q15_t *pResult);
+
+ /**
+ @brief Maximum value of a q7 vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult maximum value returned here
+ @return none
+ */
+ void arm_max_no_idx_q7(
+ const q7_t *pSrc,
+ uint32_t blockSize,
+ q7_t *pResult);
+
+ /**
+ @brief Minimum value of a floating-point vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult minimum value returned here
+ @return none
+ */
+ void arm_min_no_idx_f64(
+ const float64_t *pSrc,
+ uint32_t blockSize,
+ float64_t *pResult);
+
+/**
+ @brief Minimum value of a q31 vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult minimum value returned here
+ @return none
+ */
+ void arm_min_no_idx_q31(
+ const q31_t *pSrc,
+ uint32_t blockSize,
+ q31_t *pResult);
+
+ /**
+ @brief Minimum value of a q15 vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult minimum value returned here
+ @return none
+ */
+ void arm_min_no_idx_q15(
+ const q15_t *pSrc,
+ uint32_t blockSize,
+ q15_t *pResult);
+
+ /**
+ @brief Minimum value of a q7 vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult minimum value returned here
+ @return none
+ */
+ void arm_min_no_idx_q7(
+ const q7_t *pSrc,
+ uint32_t blockSize,
+ q7_t *pResult);
+
+/**
+ @brief Mean square error between two Q7 vectors.
+ @param[in] pSrcA points to the first input vector
+ @param[in] pSrcB points to the second input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult mean square error
+ @return none
+*/
+
+void arm_mse_q7(
+ const q7_t * pSrcA,
+ const q7_t * pSrcB,
+ uint32_t blockSize,
+ q7_t * pResult);
+
+/**
+ @brief Mean square error between two Q15 vectors.
+ @param[in] pSrcA points to the first input vector
+ @param[in] pSrcB points to the second input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult mean square error
+ @return none
+*/
+
+void arm_mse_q15(
+ const q15_t * pSrcA,
+ const q15_t * pSrcB,
+ uint32_t blockSize,
+ q15_t * pResult);
+
+/**
+ @brief Mean square error between two Q31 vectors.
+ @param[in] pSrcA points to the first input vector
+ @param[in] pSrcB points to the second input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult mean square error
+ @return none
+*/
+
+void arm_mse_q31(
+ const q31_t * pSrcA,
+ const q31_t * pSrcB,
+ uint32_t blockSize,
+ q31_t * pResult);
+
+/**
+ @brief Mean square error between two single precision float vectors.
+ @param[in] pSrcA points to the first input vector
+ @param[in] pSrcB points to the second input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult mean square error
+ @return none
+*/
+
+void arm_mse_f32(
+ const float32_t * pSrcA,
+ const float32_t * pSrcB,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+/**
+ @brief Mean square error between two double precision float vectors.
+ @param[in] pSrcA points to the first input vector
+ @param[in] pSrcB points to the second input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult mean square error
+ @return none
+*/
+
+void arm_mse_f64(
+ const float64_t * pSrcA,
+ const float64_t * pSrcB,
+ uint32_t blockSize,
+ float64_t * pResult);
+
+
+/**
+ * @brief Accumulation value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+
+void arm_accumulate_f32(
+const float32_t * pSrc,
+ uint32_t blockSize,
+ float32_t * pResult);
+
+/**
+ * @brief Accumulation value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+
+void arm_accumulate_f64(
+const float64_t * pSrc,
+ uint32_t blockSize,
+ float64_t * pResult);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _STATISTICS_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/statistics_functions_f16.h b/Middlewares/ST/ARM/DSP/Include/dsp/statistics_functions_f16.h
new file mode 100644
index 0000000..33b12c4
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/statistics_functions_f16.h
@@ -0,0 +1,279 @@
+/******************************************************************************
+ * @file statistics_functions_f16.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.1
+ * @date 14 July 2022
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _STATISTICS_FUNCTIONS_F16_H_
+#define _STATISTICS_FUNCTIONS_F16_H_
+
+#include "arm_math_types_f16.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#include "dsp/basic_math_functions_f16.h"
+#include "dsp/fast_math_functions_f16.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if defined(ARM_FLOAT16_SUPPORTED)
+
+ /**
+ * @brief Sum of the squares of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_power_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult);
+
+ /**
+ * @brief Mean value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_mean_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult);
+
+ /**
+ * @brief Variance of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_var_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult);
+
+ /**
+ * @brief Root Mean Square of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_rms_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult);
+
+ /**
+ * @brief Standard deviation of the elements of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_std_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult);
+
+ /**
+ * @brief Minimum value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_min_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ * @param[out] pIndex is the array index of the minimum value in the input buffer.
+ */
+ void arm_absmin_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Maximum value of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_max_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult,
+ uint32_t * pIndex);
+
+/**
+ * @brief Maximum value of absolute values of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ * @param[out] pIndex index of maximum value returned here
+ */
+ void arm_absmax_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult,
+ uint32_t * pIndex);
+
+ /**
+ * @brief Minimum value of absolute values of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output pointer
+ */
+ void arm_absmin_no_idx_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult);
+
+/**
+ * @brief Maximum value of a floating-point vector.
+ * @param[in] pSrc points to the input buffer
+ * @param[in] blockSize length of the input vector
+ * @param[out] pResult maximum value returned here
+ */
+ void arm_absmax_no_idx_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult);
+
+
+/**
+ * @brief Entropy
+ *
+ * @param[in] pSrcA Array of input values.
+ * @param[in] blockSize Number of samples in the input array.
+ * @return Entropy -Sum(p ln p)
+ *
+ */
+
+
+float16_t arm_entropy_f16(const float16_t * pSrcA,uint32_t blockSize);
+
+float16_t arm_logsumexp_f16(const float16_t *in, uint32_t blockSize);
+
+/**
+ * @brief Dot product with log arithmetic
+ *
+ * Vectors are containing the log of the samples
+ *
+ * @param[in] pSrcA points to the first input vector
+ * @param[in] pSrcB points to the second input vector
+ * @param[in] blockSize number of samples in each vector
+ * @param[in] pTmpBuffer temporary buffer of length blockSize
+ * @return The log of the dot product .
+ *
+ */
+
+
+float16_t arm_logsumexp_dot_prod_f16(const float16_t * pSrcA,
+ const float16_t * pSrcB,
+ uint32_t blockSize,
+ float16_t *pTmpBuffer);
+
+/**
+ * @brief Kullback-Leibler
+ *
+ * @param[in] pSrcA Pointer to an array of input values for probability distribution A.
+ * @param[in] pSrcB Pointer to an array of input values for probability distribution B.
+ * @param[in] blockSize Number of samples in the input array.
+ * @return Kullback-Leibler Divergence D(A || B)
+ *
+ */
+float16_t arm_kullback_leibler_f16(const float16_t * pSrcA
+ ,const float16_t * pSrcB
+ ,uint32_t blockSize);
+
+/**
+ @brief Maximum value of a floating-point vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult maximum value returned here
+ @return none
+ */
+ void arm_max_no_idx_f16(
+ const float16_t *pSrc,
+ uint32_t blockSize,
+ float16_t *pResult);
+
+/**
+ @brief Minimum value of a floating-point vector.
+ @param[in] pSrc points to the input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult minimum value returned here
+ @return none
+ */
+ void arm_min_no_idx_f16(
+ const float16_t *pSrc,
+ uint32_t blockSize,
+ float16_t *pResult);
+
+/**
+ @brief Mean square error between two half precision float vectors.
+ @param[in] pSrcA points to the first input vector
+ @param[in] pSrcB points to the second input vector
+ @param[in] blockSize number of samples in input vector
+ @param[out] pResult mean square error
+ @return none
+*/
+
+void arm_mse_f16(
+ const float16_t * pSrcA,
+ const float16_t * pSrcB,
+ uint32_t blockSize,
+ float16_t * pResult);
+
+
+/**
+ * @brief Sum value of a floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[in] blockSize is the number of samples to process
+ * @param[out] pResult is output value.
+ */
+ void arm_accumulate_f16(
+ const float16_t * pSrc,
+ uint32_t blockSize,
+ float16_t * pResult);
+
+
+#endif /*defined(ARM_FLOAT16_SUPPORTED)*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _STATISTICS_FUNCTIONS_F16_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/support_functions.h b/Middlewares/ST/ARM/DSP/Include/dsp/support_functions.h
new file mode 100644
index 0000000..5358d28
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/support_functions.h
@@ -0,0 +1,540 @@
+/******************************************************************************
+ * @file support_functions.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.1
+ * @date 18 August 2022
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _SUPPORT_FUNCTIONS_H_
+#define _SUPPORT_FUNCTIONS_H_
+
+#include "arm_math_types.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+/**
+ * @defgroup groupSupport Support Functions
+ */
+
+
+/**
+ * @brief Converts the elements of the 64 bit floating-point vector to floating-point vector.
+ * @param[in] pSrc points to the floating-point 64 input vector
+ * @param[out] pDst points to the floating-point output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_f64_to_float(
+ const float64_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the 64 bit floating-point vector to Q31 vector.
+ * @param[in] pSrc points to the floating-point 64 input vector
+ * @param[out] pDst points to the Q31 output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_f64_to_q31(
+ const float64_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the 64 bit floating-point vector to Q15 vector.
+ * @param[in] pSrc points to the floating-point 64 input vector
+ * @param[out] pDst points to the Q15 output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_f64_to_q15(
+ const float64_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the 64 bit floating-point vector to Q7 vector.
+ * @param[in] pSrc points to the floating-point 64 input vector
+ * @param[out] pDst points to the Q7 output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_f64_to_q7(
+ const float64_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+
+/**
+ * @brief Converts the elements of the floating-point vector to 64 bit floating-point vector.
+ * @param[in] pSrc points to the floating-point input vector
+ * @param[out] pDst points to the 64 bit floating-point output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_float_to_f64(
+ const float32_t * pSrc,
+ float64_t * pDst,
+ uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the floating-point vector to Q31 vector.
+ * @param[in] pSrc points to the floating-point input vector
+ * @param[out] pDst points to the Q31 output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_float_to_q31(
+ const float32_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the floating-point vector to Q15 vector.
+ * @param[in] pSrc points to the floating-point input vector
+ * @param[out] pDst points to the Q15 output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_float_to_q15(
+ const float32_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the floating-point vector to Q7 vector.
+ * @param[in] pSrc points to the floating-point input vector
+ * @param[out] pDst points to the Q7 output vector
+ * @param[in] blockSize length of the input vector
+ */
+ void arm_float_to_q7(
+ const float32_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the Q31 vector to 64 bit floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+void arm_q31_to_f64(
+const q31_t * pSrc,
+ float64_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Converts the elements of the Q31 vector to floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q31_to_float(
+ const q31_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q31 vector to Q15 vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q31_to_q15(
+ const q31_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q31 vector to Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q31_to_q7(
+ const q31_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the Q15 vector to 64 bit floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+void arm_q15_to_f64(
+const q15_t * pSrc,
+ float64_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Converts the elements of the Q15 vector to floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q15_to_float(
+ const q15_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q15 vector to Q31 vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q15_to_q31(
+ const q15_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q15 vector to Q7 vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q15_to_q7(
+ const q15_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the Q7 vector to 64 bit floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+void arm_q7_to_f64(
+const q7_t * pSrc,
+ float64_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @brief Converts the elements of the Q7 vector to floating-point vector.
+ * @param[in] pSrc is input pointer
+ * @param[out] pDst is output pointer
+ * @param[in] blockSize is the number of samples to process
+ */
+ void arm_q7_to_float(
+ const q7_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q7 vector to Q31 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_q7_to_q31(
+ const q7_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Converts the elements of the Q7 vector to Q15 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_q7_to_q15(
+ const q7_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+
+
+
+ /**
+ * @brief Struct for specifying sorting algorithm
+ */
+ typedef enum
+ {
+ ARM_SORT_BITONIC = 0,
+ /**< Bitonic sort */
+ ARM_SORT_BUBBLE = 1,
+ /**< Bubble sort */
+ ARM_SORT_HEAP = 2,
+ /**< Heap sort */
+ ARM_SORT_INSERTION = 3,
+ /**< Insertion sort */
+ ARM_SORT_QUICK = 4,
+ /**< Quick sort */
+ ARM_SORT_SELECTION = 5
+ /**< Selection sort */
+ } arm_sort_alg;
+
+ /**
+ * @brief Struct for specifying sorting algorithm
+ */
+ typedef enum
+ {
+ ARM_SORT_DESCENDING = 0,
+ /**< Descending order (9 to 0) */
+ ARM_SORT_ASCENDING = 1
+ /**< Ascending order (0 to 9) */
+ } arm_sort_dir;
+
+ /**
+ * @brief Instance structure for the sorting algorithms.
+ */
+ typedef struct
+ {
+ arm_sort_alg alg; /**< Sorting algorithm selected */
+ arm_sort_dir dir; /**< Sorting order (direction) */
+ } arm_sort_instance_f32;
+
+ /**
+ * @param[in] S points to an instance of the sorting structure.
+ * @param[in] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data.
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_sort_f32(
+ const arm_sort_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+ /**
+ * @param[in,out] S points to an instance of the sorting structure.
+ * @param[in] alg Selected algorithm.
+ * @param[in] dir Sorting order.
+ */
+ void arm_sort_init_f32(
+ arm_sort_instance_f32 * S,
+ arm_sort_alg alg,
+ arm_sort_dir dir);
+
+ /**
+ * @brief Instance structure for the sorting algorithms.
+ */
+ typedef struct
+ {
+ arm_sort_dir dir; /**< Sorting order (direction) */
+ float32_t * buffer; /**< Working buffer */
+ } arm_merge_sort_instance_f32;
+
+ /**
+ * @param[in] S points to an instance of the sorting structure.
+ * @param[in,out] pSrc points to the block of input data.
+ * @param[out] pDst points to the block of output data
+ * @param[in] blockSize number of samples to process.
+ */
+ void arm_merge_sort_f32(
+ const arm_merge_sort_instance_f32 * S,
+ float32_t *pSrc,
+ float32_t *pDst,
+ uint32_t blockSize);
+
+ /**
+ * @param[in,out] S points to an instance of the sorting structure.
+ * @param[in] dir Sorting order.
+ * @param[in] buffer Working buffer.
+ */
+ void arm_merge_sort_init_f32(
+ arm_merge_sort_instance_f32 * S,
+ arm_sort_dir dir,
+ float32_t * buffer);
+
+
+
+ /**
+ * @brief Copies the elements of a floating-point vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_copy_f32(
+ const float32_t * pSrc,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+
+ /**
+ * @brief Copies the elements of a floating-point vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_copy_f64(
+ const float64_t * pSrc,
+ float64_t * pDst,
+ uint32_t blockSize);
+
+
+
+ /**
+ * @brief Copies the elements of a Q7 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_copy_q7(
+ const q7_t * pSrc,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Copies the elements of a Q15 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_copy_q15(
+ const q15_t * pSrc,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Copies the elements of a Q31 vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_copy_q31(
+ const q31_t * pSrc,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fills a constant value into a floating-point vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_fill_f32(
+ float32_t value,
+ float32_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fills a constant value into a floating-point vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_fill_f64(
+ float64_t value,
+ float64_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fills a constant value into a Q7 vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_fill_q7(
+ q7_t value,
+ q7_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fills a constant value into a Q15 vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_fill_q15(
+ q15_t value,
+ q15_t * pDst,
+ uint32_t blockSize);
+
+
+ /**
+ * @brief Fills a constant value into a Q31 vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+ void arm_fill_q31(
+ q31_t value,
+ q31_t * pDst,
+ uint32_t blockSize);
+
+
+
+
+
+
+
+/**
+ * @brief Weighted sum
+ *
+ *
+ * @param[in] *in Array of input values.
+ * @param[in] *weigths Weights
+ * @param[in] blockSize Number of samples in the input array.
+ * @return Weighted sum
+ *
+ */
+float32_t arm_weighted_sum_f32(const float32_t *in
+ , const float32_t *weigths
+ , uint32_t blockSize);
+
+
+/**
+ * @brief Barycenter
+ *
+ *
+ * @param[in] in List of vectors
+ * @param[in] weights Weights of the vectors
+ * @param[out] out Barycenter
+ * @param[in] nbVectors Number of vectors
+ * @param[in] vecDim Dimension of space (vector dimension)
+ * @return None
+ *
+ */
+void arm_barycenter_f32(const float32_t *in
+ , const float32_t *weights
+ , float32_t *out
+ , uint32_t nbVectors
+ , uint32_t vecDim);
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _SUPPORT_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/support_functions_f16.h b/Middlewares/ST/ARM/DSP/Include/dsp/support_functions_f16.h
new file mode 100644
index 0000000..bce2841
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/support_functions_f16.h
@@ -0,0 +1,202 @@
+/******************************************************************************
+ * @file support_functions_f16.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.1
+ * @date 18 August 2022
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _SUPPORT_FUNCTIONS_F16_H_
+#define _SUPPORT_FUNCTIONS_F16_H_
+
+#include "arm_math_types_f16.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if defined(ARM_FLOAT16_SUPPORTED)
+
+ /**
+ * @brief Copies the elements of a floating-point vector.
+ * @param[in] pSrc input pointer
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+void arm_copy_f16(const float16_t * pSrc, float16_t * pDst, uint32_t blockSize);
+
+ /**
+ * @brief Fills a constant value into a floating-point vector.
+ * @param[in] value input value to be filled
+ * @param[out] pDst output pointer
+ * @param[in] blockSize number of samples to process
+ */
+void arm_fill_f16(float16_t value, float16_t * pDst, uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the floating-point vector to Q31 vector.
+ * @param[in] pSrc points to the f16 input vector
+ * @param[out] pDst points to the q15 output vector
+ * @param[in] blockSize length of the input vector
+ */
+void arm_f16_to_q15(const float16_t * pSrc, q15_t * pDst, uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the floating-point vector to Q31 vector.
+ * @param[in] pSrc points to the q15 input vector
+ * @param[out] pDst points to the f16 output vector
+ * @param[in] blockSize length of the input vector
+ */
+void arm_q15_to_f16(const q15_t * pSrc, float16_t * pDst, uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the 64 bit floating-point vector to 16 bit floating-point vector.
+ * @param[in] pSrc points to the f64 input vector
+ * @param[out] pDst points to the f16 output vector
+ * @param[in] blockSize length of the input vector
+ */
+void arm_f64_to_f16(const float64_t * pSrc, float16_t * pDst, uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the 16 bit floating-point vector to 64 bit floating-point vector.
+ * @param[in] pSrc points to the f16 input vector
+ * @param[out] pDst points to the f64 output vector
+ * @param[in] blockSize length of the input vector
+ */
+void arm_f16_to_f64(const float16_t * pSrc, float64_t * pDst, uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the floating-point vector to Q31 vector.
+ * @param[in] pSrc points to the f32 input vector
+ * @param[out] pDst points to the f16 output vector
+ * @param[in] blockSize length of the input vector
+ */
+void arm_float_to_f16(const float32_t * pSrc, float16_t * pDst, uint32_t blockSize);
+
+/**
+ * @brief Converts the elements of the floating-point vector to Q31 vector.
+ * @param[in] pSrc points to the f16 input vector
+ * @param[out] pDst points to the f32 output vector
+ * @param[in] blockSize length of the input vector
+ */
+void arm_f16_to_float(const float16_t * pSrc, float32_t * pDst, uint32_t blockSize);
+
+/**
+ * @brief Weighted sum
+ *
+ *
+ * @param[in] *in Array of input values.
+ * @param[in] *weigths Weights
+ * @param[in] blockSize Number of samples in the input array.
+ * @return Weighted sum
+ *
+ */
+float16_t arm_weighted_sum_f16(const float16_t *in
+ , const float16_t *weigths
+ , uint32_t blockSize);
+
+/**
+ * @brief Barycenter
+ *
+ *
+ * @param[in] in List of vectors
+ * @param[in] weights Weights of the vectors
+ * @param[out] out Barycenter
+ * @param[in] nbVectors Number of vectors
+ * @param[in] vecDim Dimension of space (vector dimension)
+ * @return None
+ *
+ */
+void arm_barycenter_f16(const float16_t *in
+ , const float16_t *weights
+ , float16_t *out
+ , uint32_t nbVectors
+ , uint32_t vecDim);
+
+
+/**
+ @ingroup groupSupport
+ */
+
+/**
+ * @defgroup typecast Typecasting
+ */
+
+/**
+ @addtogroup typecast
+ @{
+ */
+
+/**
+ * @brief Interpret a f16 as an s16 value
+ * @param[in] x input value.
+ * @return return value.
+ *
+ * @par Description
+ * It is a typecast. No conversion of the float to int is done.
+ * The memcpy will be optimized out by the compiler.
+ * memcpy is used to prevent type punning issues.
+ * With gcc, -fno-builtins MUST not be used or the
+ * memcpy will not be optimized out.
+ */
+__STATIC_INLINE int16_t arm_typecast_s16_f16(float16_t x)
+{
+ int16_t res;
+ res=*(int16_t*)memcpy((char*)&res,(char*)&x,sizeof(float16_t));
+ return(res);
+}
+
+/**
+ * @brief Interpret an s16 as an f16 value
+ * @param[in] x input value.
+ * @return return value.
+ *
+ * @par Description
+ * It is a typecast. No conversion of the int to float is done.
+ * The memcpy will be optimized out by the compiler.
+ * memcpy is used to prevent type punning issues.
+ * With gcc, -fno-builtins MUST not be used or the
+ * memcpy will not be optimized out.
+ */
+__STATIC_INLINE float16_t arm_typecast_f16_s16(int16_t x)
+{
+ float16_t res;
+ res=*(float16_t*)memcpy((char*)&res,(char*)&x,sizeof(int16_t));
+ return(res);
+}
+
+
+/**
+ @} end of typecast group
+ */
+
+
+#endif /*defined(ARM_FLOAT16_SUPPORTED)*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _SUPPORT_FUNCTIONS_F16_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/svm_defines.h b/Middlewares/ST/ARM/DSP/Include/dsp/svm_defines.h
new file mode 100644
index 0000000..f93e953
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/svm_defines.h
@@ -0,0 +1,46 @@
+/******************************************************************************
+ * @file svm_defines.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ *
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _SVM_DEFINES_H_
+#define _SVM_DEFINES_H_
+
+/**
+ * @brief Struct for specifying SVM Kernel
+ */
+typedef enum
+{
+ ARM_ML_KERNEL_LINEAR = 0,
+ /**< Linear kernel */
+ ARM_ML_KERNEL_POLYNOMIAL = 1,
+ /**< Polynomial kernel */
+ ARM_ML_KERNEL_RBF = 2,
+ /**< Radial Basis Function kernel */
+ ARM_ML_KERNEL_SIGMOID = 3
+ /**< Sigmoid kernel */
+} arm_ml_kernel_type;
+
+#endif
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/svm_functions.h b/Middlewares/ST/ARM/DSP/Include/dsp/svm_functions.h
new file mode 100644
index 0000000..3acc621
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/svm_functions.h
@@ -0,0 +1,299 @@
+/******************************************************************************
+ * @file svm_functions.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _SVM_FUNCTIONS_H_
+#define _SVM_FUNCTIONS_H_
+
+#include "arm_math_types.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+#include "dsp/svm_defines.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#define STEP(x) (x) <= 0 ? 0 : 1
+
+/**
+ * @defgroup groupSVM SVM Functions
+ * This set of functions is implementing SVM classification on 2 classes.
+ * The training must be done from scikit-learn. The parameters can be easily
+ * generated from the scikit-learn object. Some examples are given in
+ * DSP/Testing/PatternGeneration/SVM.py
+ *
+ * If more than 2 classes are needed, the functions in this folder
+ * will have to be used, as building blocks, to do multi-class classification.
+ *
+ * No multi-class classification is provided in this SVM folder.
+ *
+ */
+
+/**
+ * @brief Integer exponentiation
+ * @param[in] x value
+ * @param[in] nb integer exponent >= 1
+ * @return x^nb
+ *
+ */
+__STATIC_INLINE float32_t arm_exponent_f32(float32_t x, int32_t nb)
+{
+ float32_t r = x;
+ nb --;
+ while(nb > 0)
+ {
+ r = r * x;
+ nb--;
+ }
+ return(r);
+}
+
+
+
+
+
+/**
+ * @brief Instance structure for linear SVM prediction function.
+ */
+typedef struct
+{
+ uint32_t nbOfSupportVectors; /**< Number of support vectors */
+ uint32_t vectorDimension; /**< Dimension of vector space */
+ float32_t intercept; /**< Intercept */
+ const float32_t *dualCoefficients; /**< Dual coefficients */
+ const float32_t *supportVectors; /**< Support vectors */
+ const int32_t *classes; /**< The two SVM classes */
+} arm_svm_linear_instance_f32;
+
+
+/**
+ * @brief Instance structure for polynomial SVM prediction function.
+ */
+typedef struct
+{
+ uint32_t nbOfSupportVectors; /**< Number of support vectors */
+ uint32_t vectorDimension; /**< Dimension of vector space */
+ float32_t intercept; /**< Intercept */
+ const float32_t *dualCoefficients; /**< Dual coefficients */
+ const float32_t *supportVectors; /**< Support vectors */
+ const int32_t *classes; /**< The two SVM classes */
+ int32_t degree; /**< Polynomial degree */
+ float32_t coef0; /**< Polynomial constant */
+ float32_t gamma; /**< Gamma factor */
+} arm_svm_polynomial_instance_f32;
+
+/**
+ * @brief Instance structure for rbf SVM prediction function.
+ */
+typedef struct
+{
+ uint32_t nbOfSupportVectors; /**< Number of support vectors */
+ uint32_t vectorDimension; /**< Dimension of vector space */
+ float32_t intercept; /**< Intercept */
+ const float32_t *dualCoefficients; /**< Dual coefficients */
+ const float32_t *supportVectors; /**< Support vectors */
+ const int32_t *classes; /**< The two SVM classes */
+ float32_t gamma; /**< Gamma factor */
+} arm_svm_rbf_instance_f32;
+
+/**
+ * @brief Instance structure for sigmoid SVM prediction function.
+ */
+typedef struct
+{
+ uint32_t nbOfSupportVectors; /**< Number of support vectors */
+ uint32_t vectorDimension; /**< Dimension of vector space */
+ float32_t intercept; /**< Intercept */
+ const float32_t *dualCoefficients; /**< Dual coefficients */
+ const float32_t *supportVectors; /**< Support vectors */
+ const int32_t *classes; /**< The two SVM classes */
+ float32_t coef0; /**< Independent constant */
+ float32_t gamma; /**< Gamma factor */
+} arm_svm_sigmoid_instance_f32;
+
+/**
+ * @brief SVM linear instance init function
+ * @param[in] S Parameters for SVM functions
+ * @param[in] nbOfSupportVectors Number of support vectors
+ * @param[in] vectorDimension Dimension of vector space
+ * @param[in] intercept Intercept
+ * @param[in] dualCoefficients Array of dual coefficients
+ * @param[in] supportVectors Array of support vectors
+ * @param[in] classes Array of 2 classes ID
+ * @return none.
+ *
+ */
+
+
+void arm_svm_linear_init_f32(arm_svm_linear_instance_f32 *S,
+ uint32_t nbOfSupportVectors,
+ uint32_t vectorDimension,
+ float32_t intercept,
+ const float32_t *dualCoefficients,
+ const float32_t *supportVectors,
+ const int32_t *classes);
+
+/**
+ * @brief SVM linear prediction
+ * @param[in] S Pointer to an instance of the linear SVM structure.
+ * @param[in] in Pointer to input vector
+ * @param[out] pResult Decision value
+ * @return none.
+ *
+ */
+
+void arm_svm_linear_predict_f32(const arm_svm_linear_instance_f32 *S,
+ const float32_t * in,
+ int32_t * pResult);
+
+
+/**
+ * @brief SVM polynomial instance init function
+ * @param[in] S points to an instance of the polynomial SVM structure.
+ * @param[in] nbOfSupportVectors Number of support vectors
+ * @param[in] vectorDimension Dimension of vector space
+ * @param[in] intercept Intercept
+ * @param[in] dualCoefficients Array of dual coefficients
+ * @param[in] supportVectors Array of support vectors
+ * @param[in] classes Array of 2 classes ID
+ * @param[in] degree Polynomial degree
+ * @param[in] coef0 coeff0 (scikit-learn terminology)
+ * @param[in] gamma gamma (scikit-learn terminology)
+ * @return none.
+ *
+ */
+
+
+void arm_svm_polynomial_init_f32(arm_svm_polynomial_instance_f32 *S,
+ uint32_t nbOfSupportVectors,
+ uint32_t vectorDimension,
+ float32_t intercept,
+ const float32_t *dualCoefficients,
+ const float32_t *supportVectors,
+ const int32_t *classes,
+ int32_t degree,
+ float32_t coef0,
+ float32_t gamma
+ );
+
+/**
+ * @brief SVM polynomial prediction
+ * @param[in] S Pointer to an instance of the polynomial SVM structure.
+ * @param[in] in Pointer to input vector
+ * @param[out] pResult Decision value
+ * @return none.
+ *
+ */
+void arm_svm_polynomial_predict_f32(const arm_svm_polynomial_instance_f32 *S,
+ const float32_t * in,
+ int32_t * pResult);
+
+
+/**
+ * @brief SVM radial basis function instance init function
+ * @param[in] S points to an instance of the polynomial SVM structure.
+ * @param[in] nbOfSupportVectors Number of support vectors
+ * @param[in] vectorDimension Dimension of vector space
+ * @param[in] intercept Intercept
+ * @param[in] dualCoefficients Array of dual coefficients
+ * @param[in] supportVectors Array of support vectors
+ * @param[in] classes Array of 2 classes ID
+ * @param[in] gamma gamma (scikit-learn terminology)
+ * @return none.
+ *
+ */
+
+void arm_svm_rbf_init_f32(arm_svm_rbf_instance_f32 *S,
+ uint32_t nbOfSupportVectors,
+ uint32_t vectorDimension,
+ float32_t intercept,
+ const float32_t *dualCoefficients,
+ const float32_t *supportVectors,
+ const int32_t *classes,
+ float32_t gamma
+ );
+
+/**
+ * @brief SVM rbf prediction
+ * @param[in] S Pointer to an instance of the rbf SVM structure.
+ * @param[in] in Pointer to input vector
+ * @param[out] pResult decision value
+ * @return none.
+ *
+ */
+void arm_svm_rbf_predict_f32(const arm_svm_rbf_instance_f32 *S,
+ const float32_t * in,
+ int32_t * pResult);
+
+/**
+ * @brief SVM sigmoid instance init function
+ * @param[in] S points to an instance of the rbf SVM structure.
+ * @param[in] nbOfSupportVectors Number of support vectors
+ * @param[in] vectorDimension Dimension of vector space
+ * @param[in] intercept Intercept
+ * @param[in] dualCoefficients Array of dual coefficients
+ * @param[in] supportVectors Array of support vectors
+ * @param[in] classes Array of 2 classes ID
+ * @param[in] coef0 coeff0 (scikit-learn terminology)
+ * @param[in] gamma gamma (scikit-learn terminology)
+ * @return none.
+ *
+ */
+
+void arm_svm_sigmoid_init_f32(arm_svm_sigmoid_instance_f32 *S,
+ uint32_t nbOfSupportVectors,
+ uint32_t vectorDimension,
+ float32_t intercept,
+ const float32_t *dualCoefficients,
+ const float32_t *supportVectors,
+ const int32_t *classes,
+ float32_t coef0,
+ float32_t gamma
+ );
+
+/**
+ * @brief SVM sigmoid prediction
+ * @param[in] S Pointer to an instance of the rbf SVM structure.
+ * @param[in] in Pointer to input vector
+ * @param[out] pResult Decision value
+ * @return none.
+ *
+ */
+void arm_svm_sigmoid_predict_f32(const arm_svm_sigmoid_instance_f32 *S,
+ const float32_t * in,
+ int32_t * pResult);
+
+
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _SVM_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/svm_functions_f16.h b/Middlewares/ST/ARM/DSP/Include/dsp/svm_functions_f16.h
new file mode 100644
index 0000000..7c9fbab
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/svm_functions_f16.h
@@ -0,0 +1,281 @@
+/******************************************************************************
+ * @file svm_functions_f16.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _SVM_FUNCTIONS_F16_H_
+#define _SVM_FUNCTIONS_F16_H_
+
+#include "arm_math_types_f16.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+#include "dsp/svm_defines.h"
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+#if defined(ARM_FLOAT16_SUPPORTED)
+
+#define STEP(x) (x) <= 0 ? 0 : 1
+
+/**
+ * @defgroup groupSVM SVM Functions
+ * This set of functions is implementing SVM classification on 2 classes.
+ * The training must be done from scikit-learn. The parameters can be easily
+ * generated from the scikit-learn object. Some examples are given in
+ * DSP/Testing/PatternGeneration/SVM.py
+ *
+ * If more than 2 classes are needed, the functions in this folder
+ * will have to be used, as building blocks, to do multi-class classification.
+ *
+ * No multi-class classification is provided in this SVM folder.
+ *
+ */
+
+
+
+/**
+ * @brief Instance structure for linear SVM prediction function.
+ */
+typedef struct
+{
+ uint32_t nbOfSupportVectors; /**< Number of support vectors */
+ uint32_t vectorDimension; /**< Dimension of vector space */
+ float16_t intercept; /**< Intercept */
+ const float16_t *dualCoefficients; /**< Dual coefficients */
+ const float16_t *supportVectors; /**< Support vectors */
+ const int32_t *classes; /**< The two SVM classes */
+} arm_svm_linear_instance_f16;
+
+
+/**
+ * @brief Instance structure for polynomial SVM prediction function.
+ */
+typedef struct
+{
+ uint32_t nbOfSupportVectors; /**< Number of support vectors */
+ uint32_t vectorDimension; /**< Dimension of vector space */
+ float16_t intercept; /**< Intercept */
+ const float16_t *dualCoefficients; /**< Dual coefficients */
+ const float16_t *supportVectors; /**< Support vectors */
+ const int32_t *classes; /**< The two SVM classes */
+ int32_t degree; /**< Polynomial degree */
+ float16_t coef0; /**< Polynomial constant */
+ float16_t gamma; /**< Gamma factor */
+} arm_svm_polynomial_instance_f16;
+
+/**
+ * @brief Instance structure for rbf SVM prediction function.
+ */
+typedef struct
+{
+ uint32_t nbOfSupportVectors; /**< Number of support vectors */
+ uint32_t vectorDimension; /**< Dimension of vector space */
+ float16_t intercept; /**< Intercept */
+ const float16_t *dualCoefficients; /**< Dual coefficients */
+ const float16_t *supportVectors; /**< Support vectors */
+ const int32_t *classes; /**< The two SVM classes */
+ float16_t gamma; /**< Gamma factor */
+} arm_svm_rbf_instance_f16;
+
+/**
+ * @brief Instance structure for sigmoid SVM prediction function.
+ */
+typedef struct
+{
+ uint32_t nbOfSupportVectors; /**< Number of support vectors */
+ uint32_t vectorDimension; /**< Dimension of vector space */
+ float16_t intercept; /**< Intercept */
+ const float16_t *dualCoefficients; /**< Dual coefficients */
+ const float16_t *supportVectors; /**< Support vectors */
+ const int32_t *classes; /**< The two SVM classes */
+ float16_t coef0; /**< Independent constant */
+ float16_t gamma; /**< Gamma factor */
+} arm_svm_sigmoid_instance_f16;
+
+/**
+ * @brief SVM linear instance init function
+ * @param[in] S Parameters for SVM functions
+ * @param[in] nbOfSupportVectors Number of support vectors
+ * @param[in] vectorDimension Dimension of vector space
+ * @param[in] intercept Intercept
+ * @param[in] dualCoefficients Array of dual coefficients
+ * @param[in] supportVectors Array of support vectors
+ * @param[in] classes Array of 2 classes ID
+ * @return none.
+ *
+ */
+
+
+void arm_svm_linear_init_f16(arm_svm_linear_instance_f16 *S,
+ uint32_t nbOfSupportVectors,
+ uint32_t vectorDimension,
+ float16_t intercept,
+ const float16_t *dualCoefficients,
+ const float16_t *supportVectors,
+ const int32_t *classes);
+
+/**
+ * @brief SVM linear prediction
+ * @param[in] S Pointer to an instance of the linear SVM structure.
+ * @param[in] in Pointer to input vector
+ * @param[out] pResult Decision value
+ * @return none.
+ *
+ */
+
+void arm_svm_linear_predict_f16(const arm_svm_linear_instance_f16 *S,
+ const float16_t * in,
+ int32_t * pResult);
+
+
+/**
+ * @brief SVM polynomial instance init function
+ * @param[in] S points to an instance of the polynomial SVM structure.
+ * @param[in] nbOfSupportVectors Number of support vectors
+ * @param[in] vectorDimension Dimension of vector space
+ * @param[in] intercept Intercept
+ * @param[in] dualCoefficients Array of dual coefficients
+ * @param[in] supportVectors Array of support vectors
+ * @param[in] classes Array of 2 classes ID
+ * @param[in] degree Polynomial degree
+ * @param[in] coef0 coeff0 (scikit-learn terminology)
+ * @param[in] gamma gamma (scikit-learn terminology)
+ * @return none.
+ *
+ */
+
+
+void arm_svm_polynomial_init_f16(arm_svm_polynomial_instance_f16 *S,
+ uint32_t nbOfSupportVectors,
+ uint32_t vectorDimension,
+ float16_t intercept,
+ const float16_t *dualCoefficients,
+ const float16_t *supportVectors,
+ const int32_t *classes,
+ int32_t degree,
+ float16_t coef0,
+ float16_t gamma
+ );
+
+/**
+ * @brief SVM polynomial prediction
+ * @param[in] S Pointer to an instance of the polynomial SVM structure.
+ * @param[in] in Pointer to input vector
+ * @param[out] pResult Decision value
+ * @return none.
+ *
+ */
+void arm_svm_polynomial_predict_f16(const arm_svm_polynomial_instance_f16 *S,
+ const float16_t * in,
+ int32_t * pResult);
+
+
+/**
+ * @brief SVM radial basis function instance init function
+ * @param[in] S points to an instance of the polynomial SVM structure.
+ * @param[in] nbOfSupportVectors Number of support vectors
+ * @param[in] vectorDimension Dimension of vector space
+ * @param[in] intercept Intercept
+ * @param[in] dualCoefficients Array of dual coefficients
+ * @param[in] supportVectors Array of support vectors
+ * @param[in] classes Array of 2 classes ID
+ * @param[in] gamma gamma (scikit-learn terminology)
+ * @return none.
+ *
+ */
+
+void arm_svm_rbf_init_f16(arm_svm_rbf_instance_f16 *S,
+ uint32_t nbOfSupportVectors,
+ uint32_t vectorDimension,
+ float16_t intercept,
+ const float16_t *dualCoefficients,
+ const float16_t *supportVectors,
+ const int32_t *classes,
+ float16_t gamma
+ );
+
+/**
+ * @brief SVM rbf prediction
+ * @param[in] S Pointer to an instance of the rbf SVM structure.
+ * @param[in] in Pointer to input vector
+ * @param[out] pResult decision value
+ * @return none.
+ *
+ */
+void arm_svm_rbf_predict_f16(const arm_svm_rbf_instance_f16 *S,
+ const float16_t * in,
+ int32_t * pResult);
+
+/**
+ * @brief SVM sigmoid instance init function
+ * @param[in] S points to an instance of the rbf SVM structure.
+ * @param[in] nbOfSupportVectors Number of support vectors
+ * @param[in] vectorDimension Dimension of vector space
+ * @param[in] intercept Intercept
+ * @param[in] dualCoefficients Array of dual coefficients
+ * @param[in] supportVectors Array of support vectors
+ * @param[in] classes Array of 2 classes ID
+ * @param[in] coef0 coeff0 (scikit-learn terminology)
+ * @param[in] gamma gamma (scikit-learn terminology)
+ * @return none.
+ *
+ */
+
+void arm_svm_sigmoid_init_f16(arm_svm_sigmoid_instance_f16 *S,
+ uint32_t nbOfSupportVectors,
+ uint32_t vectorDimension,
+ float16_t intercept,
+ const float16_t *dualCoefficients,
+ const float16_t *supportVectors,
+ const int32_t *classes,
+ float16_t coef0,
+ float16_t gamma
+ );
+
+/**
+ * @brief SVM sigmoid prediction
+ * @param[in] S Pointer to an instance of the rbf SVM structure.
+ * @param[in] in Pointer to input vector
+ * @param[out] pResult Decision value
+ * @return none.
+ *
+ */
+void arm_svm_sigmoid_predict_f16(const arm_svm_sigmoid_instance_f16 *S,
+ const float16_t * in,
+ int32_t * pResult);
+
+
+
+#endif /*defined(ARM_FLOAT16_SUPPORTED)*/
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _SVM_FUNCTIONS_F16_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/transform_functions.h b/Middlewares/ST/ARM/DSP/Include/dsp/transform_functions.h
new file mode 100644
index 0000000..6270e10
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/transform_functions.h
@@ -0,0 +1,735 @@
+/******************************************************************************
+ * @file transform_functions.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _TRANSFORM_FUNCTIONS_H_
+#define _TRANSFORM_FUNCTIONS_H_
+
+#include "arm_math_types.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#include "dsp/basic_math_functions.h"
+#include "dsp/complex_math_functions.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+/**
+ * @defgroup groupTransforms Transform Functions
+ */
+
+
+ /**
+ * @brief Instance structure for the Q15 CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ const q15_t *pTwiddle; /**< points to the Sin twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ } arm_cfft_radix2_instance_q15;
+
+/* Deprecated */
+ arm_status arm_cfft_radix2_init_q15(
+ arm_cfft_radix2_instance_q15 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix2_q15(
+ const arm_cfft_radix2_instance_q15 * S,
+ q15_t * pSrc);
+
+
+ /**
+ * @brief Instance structure for the Q15 CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ const q15_t *pTwiddle; /**< points to the twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ } arm_cfft_radix4_instance_q15;
+
+/* Deprecated */
+ arm_status arm_cfft_radix4_init_q15(
+ arm_cfft_radix4_instance_q15 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix4_q15(
+ const arm_cfft_radix4_instance_q15 * S,
+ q15_t * pSrc);
+
+ /**
+ * @brief Instance structure for the Radix-2 Q31 CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ const q31_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ } arm_cfft_radix2_instance_q31;
+
+/* Deprecated */
+ arm_status arm_cfft_radix2_init_q31(
+ arm_cfft_radix2_instance_q31 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix2_q31(
+ const arm_cfft_radix2_instance_q31 * S,
+ q31_t * pSrc);
+
+ /**
+ * @brief Instance structure for the Q31 CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ const q31_t *pTwiddle; /**< points to the twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ } arm_cfft_radix4_instance_q31;
+
+/* Deprecated */
+ void arm_cfft_radix4_q31(
+ const arm_cfft_radix4_instance_q31 * S,
+ q31_t * pSrc);
+
+/* Deprecated */
+ arm_status arm_cfft_radix4_init_q31(
+ arm_cfft_radix4_instance_q31 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+ /**
+ * @brief Instance structure for the floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ const float32_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ float32_t onebyfftLen; /**< value of 1/fftLen. */
+ } arm_cfft_radix2_instance_f32;
+
+
+/* Deprecated */
+ arm_status arm_cfft_radix2_init_f32(
+ arm_cfft_radix2_instance_f32 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix2_f32(
+ const arm_cfft_radix2_instance_f32 * S,
+ float32_t * pSrc);
+
+ /**
+ * @brief Instance structure for the floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ const float32_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ float32_t onebyfftLen; /**< value of 1/fftLen. */
+ } arm_cfft_radix4_instance_f32;
+
+
+
+/* Deprecated */
+ arm_status arm_cfft_radix4_init_f32(
+ arm_cfft_radix4_instance_f32 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix4_f32(
+ const arm_cfft_radix4_instance_f32 * S,
+ float32_t * pSrc);
+
+ /**
+ * @brief Instance structure for the fixed-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ const q15_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t bitRevLength; /**< bit reversal table length. */
+#if defined(ARM_MATH_MVEI) && !defined(ARM_MATH_AUTOVECTORIZE)
+ const uint32_t *rearranged_twiddle_tab_stride1_arr; /**< Per stage reordered twiddle pointer (offset 1) */ \
+ const uint32_t *rearranged_twiddle_tab_stride2_arr; /**< Per stage reordered twiddle pointer (offset 2) */ \
+ const uint32_t *rearranged_twiddle_tab_stride3_arr; /**< Per stage reordered twiddle pointer (offset 3) */ \
+ const q15_t *rearranged_twiddle_stride1; /**< reordered twiddle offset 1 storage */ \
+ const q15_t *rearranged_twiddle_stride2; /**< reordered twiddle offset 2 storage */ \
+ const q15_t *rearranged_twiddle_stride3;
+#endif
+ } arm_cfft_instance_q15;
+
+arm_status arm_cfft_init_q15(
+ arm_cfft_instance_q15 * S,
+ uint16_t fftLen);
+
+void arm_cfft_q15(
+ const arm_cfft_instance_q15 * S,
+ q15_t * p1,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+ /**
+ * @brief Instance structure for the fixed-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ const q31_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t bitRevLength; /**< bit reversal table length. */
+#if defined(ARM_MATH_MVEI) && !defined(ARM_MATH_AUTOVECTORIZE)
+ const uint32_t *rearranged_twiddle_tab_stride1_arr; /**< Per stage reordered twiddle pointer (offset 1) */ \
+ const uint32_t *rearranged_twiddle_tab_stride2_arr; /**< Per stage reordered twiddle pointer (offset 2) */ \
+ const uint32_t *rearranged_twiddle_tab_stride3_arr; /**< Per stage reordered twiddle pointer (offset 3) */ \
+ const q31_t *rearranged_twiddle_stride1; /**< reordered twiddle offset 1 storage */ \
+ const q31_t *rearranged_twiddle_stride2; /**< reordered twiddle offset 2 storage */ \
+ const q31_t *rearranged_twiddle_stride3;
+#endif
+ } arm_cfft_instance_q31;
+
+arm_status arm_cfft_init_q31(
+ arm_cfft_instance_q31 * S,
+ uint16_t fftLen);
+
+void arm_cfft_q31(
+ const arm_cfft_instance_q31 * S,
+ q31_t * p1,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+ /**
+ * @brief Instance structure for the floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ const float32_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t bitRevLength; /**< bit reversal table length. */
+#if defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE)
+ const uint32_t *rearranged_twiddle_tab_stride1_arr; /**< Per stage reordered twiddle pointer (offset 1) */ \
+ const uint32_t *rearranged_twiddle_tab_stride2_arr; /**< Per stage reordered twiddle pointer (offset 2) */ \
+ const uint32_t *rearranged_twiddle_tab_stride3_arr; /**< Per stage reordered twiddle pointer (offset 3) */ \
+ const float32_t *rearranged_twiddle_stride1; /**< reordered twiddle offset 1 storage */ \
+ const float32_t *rearranged_twiddle_stride2; /**< reordered twiddle offset 2 storage */ \
+ const float32_t *rearranged_twiddle_stride3;
+#endif
+ } arm_cfft_instance_f32;
+
+
+
+ arm_status arm_cfft_init_f32(
+ arm_cfft_instance_f32 * S,
+ uint16_t fftLen);
+
+ void arm_cfft_f32(
+ const arm_cfft_instance_f32 * S,
+ float32_t * p1,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+
+ /**
+ * @brief Instance structure for the Double Precision Floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ const float64_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t bitRevLength; /**< bit reversal table length. */
+ } arm_cfft_instance_f64;
+
+ arm_status arm_cfft_init_f64(
+ arm_cfft_instance_f64 * S,
+ uint16_t fftLen);
+
+ void arm_cfft_f64(
+ const arm_cfft_instance_f64 * S,
+ float64_t * p1,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+ /**
+ * @brief Instance structure for the Q15 RFFT/RIFFT function.
+ */
+ typedef struct
+ {
+ uint32_t fftLenReal; /**< length of the real FFT. */
+ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */
+ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */
+ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ const q15_t *pTwiddleAReal; /**< points to the real twiddle factor table. */
+ const q15_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */
+#if defined(ARM_MATH_MVEI) && !defined(ARM_MATH_AUTOVECTORIZE)
+ arm_cfft_instance_q15 cfftInst;
+#else
+ const arm_cfft_instance_q15 *pCfft; /**< points to the complex FFT instance. */
+#endif
+ } arm_rfft_instance_q15;
+
+ arm_status arm_rfft_init_q15(
+ arm_rfft_instance_q15 * S,
+ uint32_t fftLenReal,
+ uint32_t ifftFlagR,
+ uint32_t bitReverseFlag);
+
+ void arm_rfft_q15(
+ const arm_rfft_instance_q15 * S,
+ q15_t * pSrc,
+ q15_t * pDst);
+
+ /**
+ * @brief Instance structure for the Q31 RFFT/RIFFT function.
+ */
+ typedef struct
+ {
+ uint32_t fftLenReal; /**< length of the real FFT. */
+ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */
+ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */
+ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ const q31_t *pTwiddleAReal; /**< points to the real twiddle factor table. */
+ const q31_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */
+#if defined(ARM_MATH_MVEI) && !defined(ARM_MATH_AUTOVECTORIZE)
+ arm_cfft_instance_q31 cfftInst;
+#else
+ const arm_cfft_instance_q31 *pCfft; /**< points to the complex FFT instance. */
+#endif
+ } arm_rfft_instance_q31;
+
+ arm_status arm_rfft_init_q31(
+ arm_rfft_instance_q31 * S,
+ uint32_t fftLenReal,
+ uint32_t ifftFlagR,
+ uint32_t bitReverseFlag);
+
+ void arm_rfft_q31(
+ const arm_rfft_instance_q31 * S,
+ q31_t * pSrc,
+ q31_t * pDst);
+
+ /**
+ * @brief Instance structure for the floating-point RFFT/RIFFT function.
+ */
+ typedef struct
+ {
+ uint32_t fftLenReal; /**< length of the real FFT. */
+ uint16_t fftLenBy2; /**< length of the complex FFT. */
+ uint8_t ifftFlagR; /**< flag that selects forward (ifftFlagR=0) or inverse (ifftFlagR=1) transform. */
+ uint8_t bitReverseFlagR; /**< flag that enables (bitReverseFlagR=1) or disables (bitReverseFlagR=0) bit reversal of output. */
+ uint32_t twidCoefRModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ const float32_t *pTwiddleAReal; /**< points to the real twiddle factor table. */
+ const float32_t *pTwiddleBReal; /**< points to the imag twiddle factor table. */
+ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */
+ } arm_rfft_instance_f32;
+
+ arm_status arm_rfft_init_f32(
+ arm_rfft_instance_f32 * S,
+ arm_cfft_radix4_instance_f32 * S_CFFT,
+ uint32_t fftLenReal,
+ uint32_t ifftFlagR,
+ uint32_t bitReverseFlag);
+
+ void arm_rfft_f32(
+ const arm_rfft_instance_f32 * S,
+ float32_t * pSrc,
+ float32_t * pDst);
+
+ /**
+ * @brief Instance structure for the Double Precision Floating-point RFFT/RIFFT function.
+ */
+typedef struct
+ {
+ arm_cfft_instance_f64 Sint; /**< Internal CFFT structure. */
+ uint16_t fftLenRFFT; /**< length of the real sequence */
+ const float64_t * pTwiddleRFFT; /**< Twiddle factors real stage */
+ } arm_rfft_fast_instance_f64 ;
+
+arm_status arm_rfft_fast_init_f64 (
+ arm_rfft_fast_instance_f64 * S,
+ uint16_t fftLen);
+
+
+void arm_rfft_fast_f64(
+ arm_rfft_fast_instance_f64 * S,
+ float64_t * p, float64_t * pOut,
+ uint8_t ifftFlag);
+
+
+ /**
+ * @brief Instance structure for the floating-point RFFT/RIFFT function.
+ */
+typedef struct
+ {
+ arm_cfft_instance_f32 Sint; /**< Internal CFFT structure. */
+ uint16_t fftLenRFFT; /**< length of the real sequence */
+ const float32_t * pTwiddleRFFT; /**< Twiddle factors real stage */
+ } arm_rfft_fast_instance_f32 ;
+
+arm_status arm_rfft_fast_init_f32 (
+ arm_rfft_fast_instance_f32 * S,
+ uint16_t fftLen);
+
+
+ void arm_rfft_fast_f32(
+ const arm_rfft_fast_instance_f32 * S,
+ float32_t * p, float32_t * pOut,
+ uint8_t ifftFlag);
+
+ /**
+ * @brief Instance structure for the floating-point DCT4/IDCT4 function.
+ */
+ typedef struct
+ {
+ uint16_t N; /**< length of the DCT4. */
+ uint16_t Nby2; /**< half of the length of the DCT4. */
+ float32_t normalize; /**< normalizing factor. */
+ const float32_t *pTwiddle; /**< points to the twiddle factor table. */
+ const float32_t *pCosFactor; /**< points to the cosFactor table. */
+ arm_rfft_instance_f32 *pRfft; /**< points to the real FFT instance. */
+ arm_cfft_radix4_instance_f32 *pCfft; /**< points to the complex FFT instance. */
+ } arm_dct4_instance_f32;
+
+
+ /**
+ * @brief Initialization function for the floating-point DCT4/IDCT4.
+ * @param[in,out] S points to an instance of floating-point DCT4/IDCT4 structure.
+ * @param[in] S_RFFT points to an instance of floating-point RFFT/RIFFT structure.
+ * @param[in] S_CFFT points to an instance of floating-point CFFT/CIFFT structure.
+ * @param[in] N length of the DCT4.
+ * @param[in] Nby2 half of the length of the DCT4.
+ * @param[in] normalize normalizing factor.
+ * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if fftLenReal is not a supported transform length.
+ */
+ arm_status arm_dct4_init_f32(
+ arm_dct4_instance_f32 * S,
+ arm_rfft_instance_f32 * S_RFFT,
+ arm_cfft_radix4_instance_f32 * S_CFFT,
+ uint16_t N,
+ uint16_t Nby2,
+ float32_t normalize);
+
+
+ /**
+ * @brief Processing function for the floating-point DCT4/IDCT4.
+ * @param[in] S points to an instance of the floating-point DCT4/IDCT4 structure.
+ * @param[in] pState points to state buffer.
+ * @param[in,out] pInlineBuffer points to the in-place input and output buffer.
+ */
+ void arm_dct4_f32(
+ const arm_dct4_instance_f32 * S,
+ float32_t * pState,
+ float32_t * pInlineBuffer);
+
+
+ /**
+ * @brief Instance structure for the Q31 DCT4/IDCT4 function.
+ */
+ typedef struct
+ {
+ uint16_t N; /**< length of the DCT4. */
+ uint16_t Nby2; /**< half of the length of the DCT4. */
+ q31_t normalize; /**< normalizing factor. */
+ const q31_t *pTwiddle; /**< points to the twiddle factor table. */
+ const q31_t *pCosFactor; /**< points to the cosFactor table. */
+ arm_rfft_instance_q31 *pRfft; /**< points to the real FFT instance. */
+ arm_cfft_radix4_instance_q31 *pCfft; /**< points to the complex FFT instance. */
+ } arm_dct4_instance_q31;
+
+
+ /**
+ * @brief Initialization function for the Q31 DCT4/IDCT4.
+ * @param[in,out] S points to an instance of Q31 DCT4/IDCT4 structure.
+ * @param[in] S_RFFT points to an instance of Q31 RFFT/RIFFT structure
+ * @param[in] S_CFFT points to an instance of Q31 CFFT/CIFFT structure
+ * @param[in] N length of the DCT4.
+ * @param[in] Nby2 half of the length of the DCT4.
+ * @param[in] normalize normalizing factor.
+ * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length.
+ */
+ arm_status arm_dct4_init_q31(
+ arm_dct4_instance_q31 * S,
+ arm_rfft_instance_q31 * S_RFFT,
+ arm_cfft_radix4_instance_q31 * S_CFFT,
+ uint16_t N,
+ uint16_t Nby2,
+ q31_t normalize);
+
+
+ /**
+ * @brief Processing function for the Q31 DCT4/IDCT4.
+ * @param[in] S points to an instance of the Q31 DCT4 structure.
+ * @param[in] pState points to state buffer.
+ * @param[in,out] pInlineBuffer points to the in-place input and output buffer.
+ */
+ void arm_dct4_q31(
+ const arm_dct4_instance_q31 * S,
+ q31_t * pState,
+ q31_t * pInlineBuffer);
+
+
+ /**
+ * @brief Instance structure for the Q15 DCT4/IDCT4 function.
+ */
+ typedef struct
+ {
+ uint16_t N; /**< length of the DCT4. */
+ uint16_t Nby2; /**< half of the length of the DCT4. */
+ q15_t normalize; /**< normalizing factor. */
+ const q15_t *pTwiddle; /**< points to the twiddle factor table. */
+ const q15_t *pCosFactor; /**< points to the cosFactor table. */
+ arm_rfft_instance_q15 *pRfft; /**< points to the real FFT instance. */
+ arm_cfft_radix4_instance_q15 *pCfft; /**< points to the complex FFT instance. */
+ } arm_dct4_instance_q15;
+
+
+ /**
+ * @brief Initialization function for the Q15 DCT4/IDCT4.
+ * @param[in,out] S points to an instance of Q15 DCT4/IDCT4 structure.
+ * @param[in] S_RFFT points to an instance of Q15 RFFT/RIFFT structure.
+ * @param[in] S_CFFT points to an instance of Q15 CFFT/CIFFT structure.
+ * @param[in] N length of the DCT4.
+ * @param[in] Nby2 half of the length of the DCT4.
+ * @param[in] normalize normalizing factor.
+ * @return arm_status function returns ARM_MATH_SUCCESS if initialization is successful or ARM_MATH_ARGUMENT_ERROR if N is not a supported transform length.
+ */
+ arm_status arm_dct4_init_q15(
+ arm_dct4_instance_q15 * S,
+ arm_rfft_instance_q15 * S_RFFT,
+ arm_cfft_radix4_instance_q15 * S_CFFT,
+ uint16_t N,
+ uint16_t Nby2,
+ q15_t normalize);
+
+
+ /**
+ * @brief Processing function for the Q15 DCT4/IDCT4.
+ * @param[in] S points to an instance of the Q15 DCT4 structure.
+ * @param[in] pState points to state buffer.
+ * @param[in,out] pInlineBuffer points to the in-place input and output buffer.
+ */
+ void arm_dct4_q15(
+ const arm_dct4_instance_q15 * S,
+ q15_t * pState,
+ q15_t * pInlineBuffer);
+
+ /**
+ * @brief Instance structure for the Floating-point MFCC function.
+ */
+typedef struct
+ {
+ const float32_t *dctCoefs; /**< Internal DCT coefficients */
+ const float32_t *filterCoefs; /**< Internal Mel filter coefficients */
+ const float32_t *windowCoefs; /**< Windowing coefficients */
+ const uint32_t *filterPos; /**< Internal Mel filter positions in spectrum */
+ const uint32_t *filterLengths; /**< Internal Mel filter lengths */
+ uint32_t fftLen; /**< FFT length */
+ uint32_t nbMelFilters; /**< Number of Mel filters */
+ uint32_t nbDctOutputs; /**< Number of DCT outputs */
+#if defined(ARM_MFCC_CFFT_BASED)
+ /* Implementation of the MFCC is using a CFFT */
+ arm_cfft_instance_f32 cfft; /**< Internal CFFT instance */
+#else
+ /* Implementation of the MFCC is using a RFFT (default) */
+ arm_rfft_fast_instance_f32 rfft;
+#endif
+ } arm_mfcc_instance_f32 ;
+
+arm_status arm_mfcc_init_f32(
+ arm_mfcc_instance_f32 * S,
+ uint32_t fftLen,
+ uint32_t nbMelFilters,
+ uint32_t nbDctOutputs,
+ const float32_t *dctCoefs,
+ const uint32_t *filterPos,
+ const uint32_t *filterLengths,
+ const float32_t *filterCoefs,
+ const float32_t *windowCoefs
+ );
+
+
+/**
+ @brief MFCC F32
+ @param[in] S points to the mfcc instance structure
+ @param[in] pSrc points to the input samples
+ @param[out] pDst points to the output MFCC values
+ @param[inout] pTmp points to a temporary buffer of complex
+ @return none
+ */
+ void arm_mfcc_f32(
+ const arm_mfcc_instance_f32 * S,
+ float32_t *pSrc,
+ float32_t *pDst,
+ float32_t *pTmp
+ );
+
+typedef struct
+ {
+ const q31_t *dctCoefs; /**< Internal DCT coefficients */
+ const q31_t *filterCoefs; /**< Internal Mel filter coefficients */
+ const q31_t *windowCoefs; /**< Windowing coefficients */
+ const uint32_t *filterPos; /**< Internal Mel filter positions in spectrum */
+ const uint32_t *filterLengths; /**< Internal Mel filter lengths */
+ uint32_t fftLen; /**< FFT length */
+ uint32_t nbMelFilters; /**< Number of Mel filters */
+ uint32_t nbDctOutputs; /**< Number of DCT outputs */
+#if defined(ARM_MFCC_CFFT_BASED)
+ /* Implementation of the MFCC is using a CFFT */
+ arm_cfft_instance_q31 cfft; /**< Internal CFFT instance */
+#else
+ /* Implementation of the MFCC is using a RFFT (default) */
+ arm_rfft_instance_q31 rfft;
+#endif
+ } arm_mfcc_instance_q31 ;
+
+arm_status arm_mfcc_init_q31(
+ arm_mfcc_instance_q31 * S,
+ uint32_t fftLen,
+ uint32_t nbMelFilters,
+ uint32_t nbDctOutputs,
+ const q31_t *dctCoefs,
+ const uint32_t *filterPos,
+ const uint32_t *filterLengths,
+ const q31_t *filterCoefs,
+ const q31_t *windowCoefs
+ );
+
+
+/**
+ @brief MFCC Q31
+ @param[in] S points to the mfcc instance structure
+ @param[in] pSrc points to the input samples
+ @param[out] pDst points to the output MFCC values
+ @param[inout] pTmp points to a temporary buffer of complex
+ @return none
+ */
+ arm_status arm_mfcc_q31(
+ const arm_mfcc_instance_q31 * S,
+ q31_t *pSrc,
+ q31_t *pDst,
+ q31_t *pTmp
+ );
+
+typedef struct
+ {
+ const q15_t *dctCoefs; /**< Internal DCT coefficients */
+ const q15_t *filterCoefs; /**< Internal Mel filter coefficients */
+ const q15_t *windowCoefs; /**< Windowing coefficients */
+ const uint32_t *filterPos; /**< Internal Mel filter positions in spectrum */
+ const uint32_t *filterLengths; /**< Internal Mel filter lengths */
+ uint32_t fftLen; /**< FFT length */
+ uint32_t nbMelFilters; /**< Number of Mel filters */
+ uint32_t nbDctOutputs; /**< Number of DCT outputs */
+#if defined(ARM_MFCC_CFFT_BASED)
+ /* Implementation of the MFCC is using a CFFT */
+ arm_cfft_instance_q15 cfft; /**< Internal CFFT instance */
+#else
+ /* Implementation of the MFCC is using a RFFT (default) */
+ arm_rfft_instance_q15 rfft;
+#endif
+ } arm_mfcc_instance_q15 ;
+
+arm_status arm_mfcc_init_q15(
+ arm_mfcc_instance_q15 * S,
+ uint32_t fftLen,
+ uint32_t nbMelFilters,
+ uint32_t nbDctOutputs,
+ const q15_t *dctCoefs,
+ const uint32_t *filterPos,
+ const uint32_t *filterLengths,
+ const q15_t *filterCoefs,
+ const q15_t *windowCoefs
+ );
+
+
+/**
+ @brief MFCC Q15
+ @param[in] S points to the mfcc instance structure
+ @param[in] pSrc points to the input samples
+ @param[out] pDst points to the output MFCC values in q8.7 format
+ @param[inout] pTmp points to a temporary buffer of complex
+ @return error status
+ */
+ arm_status arm_mfcc_q15(
+ const arm_mfcc_instance_q15 * S,
+ q15_t *pSrc,
+ q15_t *pDst,
+ q31_t *pTmp
+ );
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _TRANSFORM_FUNCTIONS_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/transform_functions_f16.h b/Middlewares/ST/ARM/DSP/Include/dsp/transform_functions_f16.h
new file mode 100644
index 0000000..4d8cc22
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/transform_functions_f16.h
@@ -0,0 +1,208 @@
+/******************************************************************************
+ * @file transform_functions_f16.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.10.0
+ * @date 08 July 2021
+ * Target Processor: Cortex-M and Cortex-A cores
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+#ifndef _TRANSFORM_FUNCTIONS_F16_H_
+#define _TRANSFORM_FUNCTIONS_F16_H_
+
+#include "arm_math_types_f16.h"
+#include "arm_math_memory.h"
+
+#include "dsp/none.h"
+#include "dsp/utils.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+
+#if defined(ARM_FLOAT16_SUPPORTED)
+
+
+ /**
+ * @brief Instance structure for the floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ const float16_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ float16_t onebyfftLen; /**< value of 1/fftLen. */
+ } arm_cfft_radix2_instance_f16;
+
+ /**
+ * @brief Instance structure for the floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ uint8_t ifftFlag; /**< flag that selects forward (ifftFlag=0) or inverse (ifftFlag=1) transform. */
+ uint8_t bitReverseFlag; /**< flag that enables (bitReverseFlag=1) or disables (bitReverseFlag=0) bit reversal of output. */
+ const float16_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t twidCoefModifier; /**< twiddle coefficient modifier that supports different size FFTs with the same twiddle factor table. */
+ uint16_t bitRevFactor; /**< bit reversal modifier that supports different size FFTs with the same bit reversal table. */
+ float16_t onebyfftLen; /**< value of 1/fftLen. */
+ } arm_cfft_radix4_instance_f16;
+
+ /**
+ * @brief Instance structure for the floating-point CFFT/CIFFT function.
+ */
+ typedef struct
+ {
+ uint16_t fftLen; /**< length of the FFT. */
+ const float16_t *pTwiddle; /**< points to the Twiddle factor table. */
+ const uint16_t *pBitRevTable; /**< points to the bit reversal table. */
+ uint16_t bitRevLength; /**< bit reversal table length. */
+#if defined(ARM_MATH_MVEF) && !defined(ARM_MATH_AUTOVECTORIZE)
+ const uint32_t *rearranged_twiddle_tab_stride1_arr; /**< Per stage reordered twiddle pointer (offset 1) */ \
+ const uint32_t *rearranged_twiddle_tab_stride2_arr; /**< Per stage reordered twiddle pointer (offset 2) */ \
+ const uint32_t *rearranged_twiddle_tab_stride3_arr; /**< Per stage reordered twiddle pointer (offset 3) */ \
+ const float16_t *rearranged_twiddle_stride1; /**< reordered twiddle offset 1 storage */ \
+ const float16_t *rearranged_twiddle_stride2; /**< reordered twiddle offset 2 storage */ \
+ const float16_t *rearranged_twiddle_stride3;
+#endif
+ } arm_cfft_instance_f16;
+
+
+ arm_status arm_cfft_init_f16(
+ arm_cfft_instance_f16 * S,
+ uint16_t fftLen);
+
+ void arm_cfft_f16(
+ const arm_cfft_instance_f16 * S,
+ float16_t * p1,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+ /**
+ * @brief Instance structure for the floating-point RFFT/RIFFT function.
+ */
+typedef struct
+ {
+ arm_cfft_instance_f16 Sint; /**< Internal CFFT structure. */
+ uint16_t fftLenRFFT; /**< length of the real sequence */
+ const float16_t * pTwiddleRFFT; /**< Twiddle factors real stage */
+ } arm_rfft_fast_instance_f16 ;
+
+arm_status arm_rfft_fast_init_f16 (
+ arm_rfft_fast_instance_f16 * S,
+ uint16_t fftLen);
+
+
+ void arm_rfft_fast_f16(
+ const arm_rfft_fast_instance_f16 * S,
+ float16_t * p, float16_t * pOut,
+ uint8_t ifftFlag);
+
+/* Deprecated */
+ arm_status arm_cfft_radix4_init_f16(
+ arm_cfft_radix4_instance_f16 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix4_f16(
+ const arm_cfft_radix4_instance_f16 * S,
+ float16_t * pSrc);
+
+
+/* Deprecated */
+ arm_status arm_cfft_radix2_init_f16(
+ arm_cfft_radix2_instance_f16 * S,
+ uint16_t fftLen,
+ uint8_t ifftFlag,
+ uint8_t bitReverseFlag);
+
+/* Deprecated */
+ void arm_cfft_radix2_f16(
+ const arm_cfft_radix2_instance_f16 * S,
+ float16_t * pSrc);
+
+ /**
+ * @brief Instance structure for the Floating-point MFCC function.
+ */
+typedef struct
+ {
+ const float16_t *dctCoefs; /**< Internal DCT coefficients */
+ const float16_t *filterCoefs; /**< Internal Mel filter coefficients */
+ const float16_t *windowCoefs; /**< Windowing coefficients */
+ const uint32_t *filterPos; /**< Internal Mel filter positions in spectrum */
+ const uint32_t *filterLengths; /**< Internal Mel filter lengths */
+ uint32_t fftLen; /**< FFT length */
+ uint32_t nbMelFilters; /**< Number of Mel filters */
+ uint32_t nbDctOutputs; /**< Number of DCT outputs */
+#if defined(ARM_MFCC_CFFT_BASED)
+ /* Implementation of the MFCC is using a CFFT */
+ arm_cfft_instance_f16 cfft; /**< Internal CFFT instance */
+#else
+ /* Implementation of the MFCC is using a RFFT (default) */
+ arm_rfft_fast_instance_f16 rfft;
+#endif
+ } arm_mfcc_instance_f16 ;
+
+arm_status arm_mfcc_init_f16(
+ arm_mfcc_instance_f16 * S,
+ uint32_t fftLen,
+ uint32_t nbMelFilters,
+ uint32_t nbDctOutputs,
+ const float16_t *dctCoefs,
+ const uint32_t *filterPos,
+ const uint32_t *filterLengths,
+ const float16_t *filterCoefs,
+ const float16_t *windowCoefs
+ );
+
+
+/**
+ @brief MFCC F16
+ @param[in] S points to the mfcc instance structure
+ @param[in] pSrc points to the input samples
+ @param[out] pDst points to the output MFCC values
+ @param[inout] pTmp points to a temporary buffer of complex
+ @return none
+ */
+ void arm_mfcc_f16(
+ const arm_mfcc_instance_f16 * S,
+ float16_t *pSrc,
+ float16_t *pDst,
+ float16_t *pTmp
+ );
+
+
+#endif /* defined(ARM_FLOAT16_SUPPORTED)*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ifndef _TRANSFORM_FUNCTIONS_F16_H_ */
diff --git a/Middlewares/ST/ARM/DSP/Include/dsp/utils.h b/Middlewares/ST/ARM/DSP/Include/dsp/utils.h
new file mode 100644
index 0000000..10f9cf2
--- /dev/null
+++ b/Middlewares/ST/ARM/DSP/Include/dsp/utils.h
@@ -0,0 +1,257 @@
+/******************************************************************************
+ * @file arm_math_utils.h
+ * @brief Public header file for CMSIS DSP Library
+ * @version V1.9.0
+ * @date 20. July 2020
+ ******************************************************************************/
+/*
+ * Copyright (c) 2010-2020 Arm Limited or its affiliates. All rights reserved.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the License); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an AS IS BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _ARM_MATH_UTILS_H_
+
+#define _ARM_MATH_UTILS_H_
+
+#include "arm_math_types.h"
+#include + BaseType_t xCoRoutineCreate( + crCOROUTINE_CODE pxCoRoutineCode, + UBaseType_t uxPriority, + UBaseType_t uxIndex + );+ * + * Create a new co-routine and add it to the list of co-routines that are + * ready to run. + * + * @param pxCoRoutineCode Pointer to the co-routine function. Co-routine + * functions require special syntax - see the co-routine section of the WEB + * documentation for more information. + * + * @param uxPriority The priority with respect to other co-routines at which + * the co-routine will run. + * + * @param uxIndex Used to distinguish between different co-routines that + * execute the same function. See the example below and the co-routine section + * of the WEB documentation for further information. + * + * @return pdPASS if the co-routine was successfully created and added to a ready + * list, otherwise an error code defined with ProjDefs.h. + * + * Example usage: +
+ // Co-routine to be created.
+ void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ // This may not be necessary for const variables.
+ static const char cLedToFlash[ 2 ] = { 5, 6 };
+ static const TickType_t uxFlashRates[ 2 ] = { 200, 400 };
+
+ // Must start every co-routine with a call to crSTART();
+ crSTART( xHandle );
+
+ for( ;; )
+ {
+ // This co-routine just delays for a fixed period, then toggles
+ // an LED. Two co-routines are created using this function, so
+ // the uxIndex parameter is used to tell the co-routine which
+ // LED to flash and how int32_t to delay. This assumes xQueue has
+ // already been created.
+ vParTestToggleLED( cLedToFlash[ uxIndex ] );
+ crDELAY( xHandle, uxFlashRates[ uxIndex ] );
+ }
+
+ // Must end every co-routine with a call to crEND();
+ crEND();
+ }
+
+ // Function that creates two co-routines.
+ void vOtherFunction( void )
+ {
+ uint8_t ucParameterToPass;
+ TaskHandle_t xHandle;
+
+ // Create two co-routines at priority 0. The first is given index 0
+ // so (from the code above) toggles LED 5 every 200 ticks. The second
+ // is given index 1 so toggles LED 6 every 400 ticks.
+ for( uxIndex = 0; uxIndex < 2; uxIndex++ )
+ {
+ xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex );
+ }
+ }
+
+ * \defgroup xCoRoutineCreate xCoRoutineCreate
+ * \ingroup Tasks
+ */
+BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex );
+
+
+/**
+ * croutine. h
+ *+ void vCoRoutineSchedule( void );+ * + * Run a co-routine. + * + * vCoRoutineSchedule() executes the highest priority co-routine that is able + * to run. The co-routine will execute until it either blocks, yields or is + * preempted by a task. Co-routines execute cooperatively so one + * co-routine cannot be preempted by another, but can be preempted by a task. + * + * If an application comprises of both tasks and co-routines then + * vCoRoutineSchedule should be called from the idle task (in an idle task + * hook). + * + * Example usage: +
+ // This idle task hook will schedule a co-routine each time it is called.
+ // The rest of the idle task will execute between co-routine calls.
+ void vApplicationIdleHook( void )
+ {
+ vCoRoutineSchedule();
+ }
+
+ // Alternatively, if you do not require any other part of the idle task to
+ // execute, the idle task hook can call vCoRoutineSchedule() within an
+ // infinite loop.
+ void vApplicationIdleHook( void )
+ {
+ for( ;; )
+ {
+ vCoRoutineSchedule();
+ }
+ }
+
+ * \defgroup vCoRoutineSchedule vCoRoutineSchedule
+ * \ingroup Tasks
+ */
+void vCoRoutineSchedule( void );
+
+/**
+ * croutine. h
+ * + crSTART( CoRoutineHandle_t xHandle );+ * + * This macro MUST always be called at the start of a co-routine function. + * + * Example usage: +
+ // Co-routine to be created.
+ void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static int32_t ulAVariable;
+
+ // Must start every co-routine with a call to crSTART();
+ crSTART( xHandle );
+
+ for( ;; )
+ {
+ // Co-routine functionality goes here.
+ }
+
+ // Must end every co-routine with a call to crEND();
+ crEND();
+ }
+ * \defgroup crSTART crSTART
+ * \ingroup Tasks
+ */
+#define crSTART( pxCRCB ) switch( ( ( CRCB_t * )( pxCRCB ) )->uxState ) { case 0:
+
+/**
+ * croutine. h
+ * + crEND();+ * + * This macro MUST always be called at the end of a co-routine function. + * + * Example usage: +
+ // Co-routine to be created.
+ void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static int32_t ulAVariable;
+
+ // Must start every co-routine with a call to crSTART();
+ crSTART( xHandle );
+
+ for( ;; )
+ {
+ // Co-routine functionality goes here.
+ }
+
+ // Must end every co-routine with a call to crEND();
+ crEND();
+ }
+ * \defgroup crSTART crSTART
+ * \ingroup Tasks
+ */
+#define crEND() }
+
+/*
+ * These macros are intended for internal use by the co-routine implementation
+ * only. The macros should not be used directly by application writers.
+ */
+#define crSET_STATE0( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = (__LINE__ * 2); return; case (__LINE__ * 2):
+#define crSET_STATE1( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = ((__LINE__ * 2)+1); return; case ((__LINE__ * 2)+1):
+
+/**
+ * croutine. h
+ *+ crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay );+ * + * Delay a co-routine for a fixed period of time. + * + * crDELAY can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * @param xHandle The handle of the co-routine to delay. This is the xHandle + * parameter of the co-routine function. + * + * @param xTickToDelay The number of ticks that the co-routine should delay + * for. The actual amount of time this equates to is defined by + * configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant portTICK_PERIOD_MS + * can be used to convert ticks to milliseconds. + * + * Example usage: +
+ // Co-routine to be created.
+ void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ // This may not be necessary for const variables.
+ // We are to delay for 200ms.
+ static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS;
+
+ // Must start every co-routine with a call to crSTART();
+ crSTART( xHandle );
+
+ for( ;; )
+ {
+ // Delay for 200ms.
+ crDELAY( xHandle, xDelayTime );
+
+ // Do something here.
+ }
+
+ // Must end every co-routine with a call to crEND();
+ crEND();
+ }
+ * \defgroup crDELAY crDELAY
+ * \ingroup Tasks
+ */
+#define crDELAY( xHandle, xTicksToDelay ) \
+ if( ( xTicksToDelay ) > 0 ) \
+ { \
+ vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL ); \
+ } \
+ crSET_STATE0( ( xHandle ) );
+
+/**
+ * + crQUEUE_SEND( + CoRoutineHandle_t xHandle, + QueueHandle_t pxQueue, + void *pvItemToQueue, + TickType_t xTicksToWait, + BaseType_t *pxResult + )+ * + * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine + * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. + * + * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas + * xQueueSend() and xQueueReceive() can only be used from tasks. + * + * crQUEUE_SEND can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xHandle The handle of the calling co-routine. This is the xHandle + * parameter of the co-routine function. + * + * @param pxQueue The handle of the queue on which the data will be posted. + * The handle is obtained as the return value when the queue is created using + * the xQueueCreate() API function. + * + * @param pvItemToQueue A pointer to the data being posted onto the queue. + * The number of bytes of each queued item is specified when the queue is + * created. This number of bytes is copied from pvItemToQueue into the queue + * itself. + * + * @param xTickToDelay The number of ticks that the co-routine should block + * to wait for space to become available on the queue, should space not be + * available immediately. The actual amount of time this equates to is defined + * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant + * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see example + * below). + * + * @param pxResult The variable pointed to by pxResult will be set to pdPASS if + * data was successfully posted onto the queue, otherwise it will be set to an + * error defined within ProjDefs.h. + * + * Example usage: +
+ // Co-routine function that blocks for a fixed period then posts a number onto
+ // a queue.
+ static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static BaseType_t xNumberToPost = 0;
+ static BaseType_t xResult;
+
+ // Co-routines must begin with a call to crSTART().
+ crSTART( xHandle );
+
+ for( ;; )
+ {
+ // This assumes the queue has already been created.
+ crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult );
+
+ if( xResult != pdPASS )
+ {
+ // The message was not posted!
+ }
+
+ // Increment the number to be posted onto the queue.
+ xNumberToPost++;
+
+ // Delay for 100 ticks.
+ crDELAY( xHandle, 100 );
+ }
+
+ // Co-routines must end with a call to crEND().
+ crEND();
+ }
+ * \defgroup crQUEUE_SEND crQUEUE_SEND
+ * \ingroup Tasks
+ */
+#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult ) \
+{ \
+ *( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) ); \
+ if( *( pxResult ) == errQUEUE_BLOCKED ) \
+ { \
+ crSET_STATE0( ( xHandle ) ); \
+ *pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 ); \
+ } \
+ if( *pxResult == errQUEUE_YIELD ) \
+ { \
+ crSET_STATE1( ( xHandle ) ); \
+ *pxResult = pdPASS; \
+ } \
+}
+
+/**
+ * croutine. h
+ * + crQUEUE_RECEIVE( + CoRoutineHandle_t xHandle, + QueueHandle_t pxQueue, + void *pvBuffer, + TickType_t xTicksToWait, + BaseType_t *pxResult + )+ * + * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine + * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks. + * + * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas + * xQueueSend() and xQueueReceive() can only be used from tasks. + * + * crQUEUE_RECEIVE can only be called from the co-routine function itself - not + * from within a function called by the co-routine function. This is because + * co-routines do not maintain their own stack. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xHandle The handle of the calling co-routine. This is the xHandle + * parameter of the co-routine function. + * + * @param pxQueue The handle of the queue from which the data will be received. + * The handle is obtained as the return value when the queue is created using + * the xQueueCreate() API function. + * + * @param pvBuffer The buffer into which the received item is to be copied. + * The number of bytes of each queued item is specified when the queue is + * created. This number of bytes is copied into pvBuffer. + * + * @param xTickToDelay The number of ticks that the co-routine should block + * to wait for data to become available from the queue, should data not be + * available immediately. The actual amount of time this equates to is defined + * by configTICK_RATE_HZ (set in FreeRTOSConfig.h). The constant + * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see the + * crQUEUE_SEND example). + * + * @param pxResult The variable pointed to by pxResult will be set to pdPASS if + * data was successfully retrieved from the queue, otherwise it will be set to + * an error code as defined within ProjDefs.h. + * + * Example usage: +
+ // A co-routine receives the number of an LED to flash from a queue. It
+ // blocks on the queue until the number is received.
+ static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static BaseType_t xResult;
+ static UBaseType_t uxLEDToFlash;
+
+ // All co-routines must start with a call to crSTART().
+ crSTART( xHandle );
+
+ for( ;; )
+ {
+ // Wait for data to become available on the queue.
+ crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
+
+ if( xResult == pdPASS )
+ {
+ // We received the LED to flash - flash it!
+ vParTestToggleLED( uxLEDToFlash );
+ }
+ }
+
+ crEND();
+ }
+ * \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE
+ * \ingroup Tasks
+ */
+#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult ) \
+{ \
+ *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) ); \
+ if( *( pxResult ) == errQUEUE_BLOCKED ) \
+ { \
+ crSET_STATE0( ( xHandle ) ); \
+ *( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 ); \
+ } \
+ if( *( pxResult ) == errQUEUE_YIELD ) \
+ { \
+ crSET_STATE1( ( xHandle ) ); \
+ *( pxResult ) = pdPASS; \
+ } \
+}
+
+/**
+ * croutine. h
+ * + crQUEUE_SEND_FROM_ISR( + QueueHandle_t pxQueue, + void *pvItemToQueue, + BaseType_t xCoRoutinePreviouslyWoken + )+ * + * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the + * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() + * functions used by tasks. + * + * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to + * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and + * xQueueReceiveFromISR() can only be used to pass data between a task and and + * ISR. + * + * crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue + * that is being used from within a co-routine. + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto + * the same queue multiple times from a single interrupt. The first call + * should always pass in pdFALSE. Subsequent calls should pass in + * the value returned from the previous call. + * + * @return pdTRUE if a co-routine was woken by posting onto the queue. This is + * used by the ISR to determine if a context switch may be required following + * the ISR. + * + * Example usage: +
+ // A co-routine that blocks on a queue waiting for characters to be received.
+ static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ char cRxedChar;
+ BaseType_t xResult;
+
+ // All co-routines must start with a call to crSTART().
+ crSTART( xHandle );
+
+ for( ;; )
+ {
+ // Wait for data to become available on the queue. This assumes the
+ // queue xCommsRxQueue has already been created!
+ crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
+
+ // Was a character received?
+ if( xResult == pdPASS )
+ {
+ // Process the character here.
+ }
+ }
+
+ // All co-routines must end with a call to crEND().
+ crEND();
+ }
+
+ // An ISR that uses a queue to send characters received on a serial port to
+ // a co-routine.
+ void vUART_ISR( void )
+ {
+ char cRxedChar;
+ BaseType_t xCRWokenByPost = pdFALSE;
+
+ // We loop around reading characters until there are none left in the UART.
+ while( UART_RX_REG_NOT_EMPTY() )
+ {
+ // Obtain the character from the UART.
+ cRxedChar = UART_RX_REG;
+
+ // Post the character onto a queue. xCRWokenByPost will be pdFALSE
+ // the first time around the loop. If the post causes a co-routine
+ // to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE.
+ // In this manner we can ensure that if more than one co-routine is
+ // blocked on the queue only one is woken by this ISR no matter how
+ // many characters are posted to the queue.
+ xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost );
+ }
+ }
+ * \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR
+ * \ingroup Tasks
+ */
+#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) )
+
+
+/**
+ * croutine. h
+ * + crQUEUE_SEND_FROM_ISR( + QueueHandle_t pxQueue, + void *pvBuffer, + BaseType_t * pxCoRoutineWoken + )+ * + * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the + * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR() + * functions used by tasks. + * + * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to + * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and + * xQueueReceiveFromISR() can only be used to pass data between a task and and + * ISR. + * + * crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data + * from a queue that is being used from within a co-routine (a co-routine + * posted to the queue). + * + * See the co-routine section of the WEB documentation for information on + * passing data between tasks and co-routines and between ISR's and + * co-routines. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvBuffer A pointer to a buffer into which the received item will be + * placed. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from the queue into + * pvBuffer. + * + * @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become + * available on the queue. If crQUEUE_RECEIVE_FROM_ISR causes such a + * co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise + * *pxCoRoutineWoken will remain unchanged. + * + * @return pdTRUE an item was successfully received from the queue, otherwise + * pdFALSE. + * + * Example usage: +
+ // A co-routine that posts a character to a queue then blocks for a fixed
+ // period. The character is incremented each time.
+ static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // cChar holds its value while this co-routine is blocked and must therefore
+ // be declared static.
+ static char cCharToTx = 'a';
+ BaseType_t xResult;
+
+ // All co-routines must start with a call to crSTART().
+ crSTART( xHandle );
+
+ for( ;; )
+ {
+ // Send the next character to the queue.
+ crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult );
+
+ if( xResult == pdPASS )
+ {
+ // The character was successfully posted to the queue.
+ }
+ else
+ {
+ // Could not post the character to the queue.
+ }
+
+ // Enable the UART Tx interrupt to cause an interrupt in this
+ // hypothetical UART. The interrupt will obtain the character
+ // from the queue and send it.
+ ENABLE_RX_INTERRUPT();
+
+ // Increment to the next character then block for a fixed period.
+ // cCharToTx will maintain its value across the delay as it is
+ // declared static.
+ cCharToTx++;
+ if( cCharToTx > 'x' )
+ {
+ cCharToTx = 'a';
+ }
+ crDELAY( 100 );
+ }
+
+ // All co-routines must end with a call to crEND().
+ crEND();
+ }
+
+ // An ISR that uses a queue to receive characters to send on a UART.
+ void vUART_ISR( void )
+ {
+ char cCharToTx;
+ BaseType_t xCRWokenByPost = pdFALSE;
+
+ while( UART_TX_REG_EMPTY() )
+ {
+ // Are there any characters in the queue waiting to be sent?
+ // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
+ // is woken by the post - ensuring that only a single co-routine is
+ // woken no matter how many times we go around this loop.
+ if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) )
+ {
+ SEND_CHARACTER( cCharToTx );
+ }
+ }
+ }
+ * \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR
+ * \ingroup Tasks
+ */
+#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) )
+
+/*
+ * This function is intended for internal use by the co-routine macros only.
+ * The macro nature of the co-routine implementation requires that the
+ * prototype appears here. The function should not be used by application
+ * writers.
+ *
+ * Removes the current co-routine from its ready list and places it in the
+ * appropriate delayed list.
+ */
+void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList );
+
+/*
+ * This function is intended for internal use by the queue implementation only.
+ * The function should not be used by application writers.
+ *
+ * Removes the highest priority co-routine from the event list and places it in
+ * the pending ready list.
+ */
+BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CO_ROUTINE_H */
diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/deprecated_definitions.h b/Middlewares/Third_Party/FreeRTOS/Source/include/deprecated_definitions.h
new file mode 100644
index 0000000..21657b9
--- /dev/null
+++ b/Middlewares/Third_Party/FreeRTOS/Source/include/deprecated_definitions.h
@@ -0,0 +1,279 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ * the Software, and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * http://www.FreeRTOS.org
+ * http://aws.amazon.com/freertos
+ *
+ * 1 tab == 4 spaces!
+ */
+
+#ifndef DEPRECATED_DEFINITIONS_H
+#define DEPRECATED_DEFINITIONS_H
+
+
+/* Each FreeRTOS port has a unique portmacro.h header file. Originally a
+pre-processor definition was used to ensure the pre-processor found the correct
+portmacro.h file for the port being used. That scheme was deprecated in favour
+of setting the compiler's include path such that it found the correct
+portmacro.h file - removing the need for the constant and allowing the
+portmacro.h file to be located anywhere in relation to the port being used. The
+definitions below remain in the code for backward compatibility only. New
+projects should not use them. */
+
+#ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT
+ #include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h"
+ typedef void ( __interrupt __far *pxISR )();
+#endif
+
+#ifdef OPEN_WATCOM_FLASH_LITE_186_PORT
+ #include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h"
+ typedef void ( __interrupt __far *pxISR )();
+#endif
+
+#ifdef GCC_MEGA_AVR
+ #include "../portable/GCC/ATMega323/portmacro.h"
+#endif
+
+#ifdef IAR_MEGA_AVR
+ #include "../portable/IAR/ATMega323/portmacro.h"
+#endif
+
+#ifdef MPLAB_PIC24_PORT
+ #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h"
+#endif
+
+#ifdef MPLAB_DSPIC_PORT
+ #include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h"
+#endif
+
+#ifdef MPLAB_PIC18F_PORT
+ #include "../../Source/portable/MPLAB/PIC18F/portmacro.h"
+#endif
+
+#ifdef MPLAB_PIC32MX_PORT
+ #include "../../Source/portable/MPLAB/PIC32MX/portmacro.h"
+#endif
+
+#ifdef _FEDPICC
+ #include "libFreeRTOS/Include/portmacro.h"
+#endif
+
+#ifdef SDCC_CYGNAL
+ #include "../../Source/portable/SDCC/Cygnal/portmacro.h"
+#endif
+
+#ifdef GCC_ARM7
+ #include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h"
+#endif
+
+#ifdef GCC_ARM7_ECLIPSE
+ #include "portmacro.h"
+#endif
+
+#ifdef ROWLEY_LPC23xx
+ #include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h"
+#endif
+
+#ifdef IAR_MSP430
+ #include "..\..\Source\portable\IAR\MSP430\portmacro.h"
+#endif
+
+#ifdef GCC_MSP430
+ #include "../../Source/portable/GCC/MSP430F449/portmacro.h"
+#endif
+
+#ifdef ROWLEY_MSP430
+ #include "../../Source/portable/Rowley/MSP430F449/portmacro.h"
+#endif
+
+#ifdef ARM7_LPC21xx_KEIL_RVDS
+ #include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h"
+#endif
+
+#ifdef SAM7_GCC
+ #include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h"
+#endif
+
+#ifdef SAM7_IAR
+ #include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h"
+#endif
+
+#ifdef SAM9XE_IAR
+ #include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h"
+#endif
+
+#ifdef LPC2000_IAR
+ #include "..\..\Source\portable\IAR\LPC2000\portmacro.h"
+#endif
+
+#ifdef STR71X_IAR
+ #include "..\..\Source\portable\IAR\STR71x\portmacro.h"
+#endif
+
+#ifdef STR75X_IAR
+ #include "..\..\Source\portable\IAR\STR75x\portmacro.h"
+#endif
+
+#ifdef STR75X_GCC
+ #include "..\..\Source\portable\GCC\STR75x\portmacro.h"
+#endif
+
+#ifdef STR91X_IAR
+ #include "..\..\Source\portable\IAR\STR91x\portmacro.h"
+#endif
+
+#ifdef GCC_H8S
+ #include "../../Source/portable/GCC/H8S2329/portmacro.h"
+#endif
+
+#ifdef GCC_AT91FR40008
+ #include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h"
+#endif
+
+#ifdef RVDS_ARMCM3_LM3S102
+ #include "../../Source/portable/RVDS/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef GCC_ARMCM3_LM3S102
+ #include "../../Source/portable/GCC/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef GCC_ARMCM3
+ #include "../../Source/portable/GCC/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef IAR_ARM_CM3
+ #include "../../Source/portable/IAR/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef IAR_ARMCM3_LM
+ #include "../../Source/portable/IAR/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef HCS12_CODE_WARRIOR
+ #include "../../Source/portable/CodeWarrior/HCS12/portmacro.h"
+#endif
+
+#ifdef MICROBLAZE_GCC
+ #include "../../Source/portable/GCC/MicroBlaze/portmacro.h"
+#endif
+
+#ifdef TERN_EE
+ #include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h"
+#endif
+
+#ifdef GCC_HCS12
+ #include "../../Source/portable/GCC/HCS12/portmacro.h"
+#endif
+
+#ifdef GCC_MCF5235
+ #include "../../Source/portable/GCC/MCF5235/portmacro.h"
+#endif
+
+#ifdef COLDFIRE_V2_GCC
+ #include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h"
+#endif
+
+#ifdef COLDFIRE_V2_CODEWARRIOR
+ #include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h"
+#endif
+
+#ifdef GCC_PPC405
+ #include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h"
+#endif
+
+#ifdef GCC_PPC440
+ #include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h"
+#endif
+
+#ifdef _16FX_SOFTUNE
+ #include "..\..\Source\portable\Softune\MB96340\portmacro.h"
+#endif
+
+#ifdef BCC_INDUSTRIAL_PC_PORT
+ /* A short file name has to be used in place of the normal
+ FreeRTOSConfig.h when using the Borland compiler. */
+ #include "frconfig.h"
+ #include "..\portable\BCC\16BitDOS\PC\prtmacro.h"
+ typedef void ( __interrupt __far *pxISR )();
+#endif
+
+#ifdef BCC_FLASH_LITE_186_PORT
+ /* A short file name has to be used in place of the normal
+ FreeRTOSConfig.h when using the Borland compiler. */
+ #include "frconfig.h"
+ #include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h"
+ typedef void ( __interrupt __far *pxISR )();
+#endif
+
+#ifdef __GNUC__
+ #ifdef __AVR32_AVR32A__
+ #include "portmacro.h"
+ #endif
+#endif
+
+#ifdef __ICCAVR32__
+ #ifdef __CORE__
+ #if __CORE__ == __AVR32A__
+ #include "portmacro.h"
+ #endif
+ #endif
+#endif
+
+#ifdef __91467D
+ #include "portmacro.h"
+#endif
+
+#ifdef __96340
+ #include "portmacro.h"
+#endif
+
+
+#ifdef __IAR_V850ES_Fx3__
+ #include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_V850ES_Jx3__
+ #include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_V850ES_Jx3_L__
+ #include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_V850ES_Jx2__
+ #include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_V850ES_Hx2__
+ #include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_78K0R_Kx3__
+ #include "../../Source/portable/IAR/78K0R/portmacro.h"
+#endif
+
+#ifdef __IAR_78K0R_Kx3L__
+ #include "../../Source/portable/IAR/78K0R/portmacro.h"
+#endif
+
+#endif /* DEPRECATED_DEFINITIONS_H */
+
diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h b/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h
new file mode 100644
index 0000000..a87fdf3
--- /dev/null
+++ b/Middlewares/Third_Party/FreeRTOS/Source/include/event_groups.h
@@ -0,0 +1,757 @@
+/*
+ * FreeRTOS Kernel V10.3.1
+ * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+ * the Software, and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+ * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+ * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+ * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * http://www.FreeRTOS.org
+ * http://aws.amazon.com/freertos
+ *
+ * 1 tab == 4 spaces!
+ */
+
+#ifndef EVENT_GROUPS_H
+#define EVENT_GROUPS_H
+
+#ifndef INC_FREERTOS_H
+ #error "include FreeRTOS.h" must appear in source files before "include event_groups.h"
+#endif
+
+/* FreeRTOS includes. */
+#include "timers.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * An event group is a collection of bits to which an application can assign a
+ * meaning. For example, an application may create an event group to convey
+ * the status of various CAN bus related events in which bit 0 might mean "A CAN
+ * message has been received and is ready for processing", bit 1 might mean "The
+ * application has queued a message that is ready for sending onto the CAN
+ * network", and bit 2 might mean "It is time to send a SYNC message onto the
+ * CAN network" etc. A task can then test the bit values to see which events
+ * are active, and optionally enter the Blocked state to wait for a specified
+ * bit or a group of specified bits to be active. To continue the CAN bus
+ * example, a CAN controlling task can enter the Blocked state (and therefore
+ * not consume any processing time) until either bit 0, bit 1 or bit 2 are
+ * active, at which time the bit that was actually active would inform the task
+ * which action it had to take (process a received message, send a message, or
+ * send a SYNC).
+ *
+ * The event groups implementation contains intelligence to avoid race
+ * conditions that would otherwise occur were an application to use a simple
+ * variable for the same purpose. This is particularly important with respect
+ * to when a bit within an event group is to be cleared, and when bits have to
+ * be set and then tested atomically - as is the case where event groups are
+ * used to create a synchronisation point between multiple tasks (a
+ * 'rendezvous').
+ *
+ * \defgroup EventGroup
+ */
+
+
+
+/**
+ * event_groups.h
+ *
+ * Type by which event groups are referenced. For example, a call to
+ * xEventGroupCreate() returns an EventGroupHandle_t variable that can then
+ * be used as a parameter to other event group functions.
+ *
+ * \defgroup EventGroupHandle_t EventGroupHandle_t
+ * \ingroup EventGroup
+ */
+struct EventGroupDef_t;
+typedef struct EventGroupDef_t * EventGroupHandle_t;
+
+/*
+ * The type that holds event bits always matches TickType_t - therefore the
+ * number of bits it holds is set by configUSE_16_BIT_TICKS (16 bits if set to 1,
+ * 32 bits if set to 0.
+ *
+ * \defgroup EventBits_t EventBits_t
+ * \ingroup EventGroup
+ */
+typedef TickType_t EventBits_t;
+
+/**
+ * event_groups.h
+ *+ EventGroupHandle_t xEventGroupCreate( void ); ++ * + * Create a new event group. + * + * Internally, within the FreeRTOS implementation, event groups use a [small] + * block of memory, in which the event group's structure is stored. If an event + * groups is created using xEventGropuCreate() then the required memory is + * automatically dynamically allocated inside the xEventGroupCreate() function. + * (see http://www.freertos.org/a00111.html). If an event group is created + * using xEventGropuCreateStatic() then the application writer must instead + * provide the memory that will get used by the event group. + * xEventGroupCreateStatic() therefore allows an event group to be created + * without using any dynamic memory allocation. + * + * Although event groups are not related to ticks, for internal implementation + * reasons the number of bits available for use in an event group is dependent + * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If + * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit + * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has + * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store + * event bits within an event group. + * + * @return If the event group was created then a handle to the event group is + * returned. If there was insufficient FreeRTOS heap available to create the + * event group then NULL is returned. See http://www.freertos.org/a00111.html + * + * Example usage: +
+ // Declare a variable to hold the created event group.
+ EventGroupHandle_t xCreatedEventGroup;
+
+ // Attempt to create the event group.
+ xCreatedEventGroup = xEventGroupCreate();
+
+ // Was the event group created successfully?
+ if( xCreatedEventGroup == NULL )
+ {
+ // The event group was not created because there was insufficient
+ // FreeRTOS heap available.
+ }
+ else
+ {
+ // The event group was created.
+ }
+
+ * \defgroup xEventGroupCreate xEventGroupCreate
+ * \ingroup EventGroup
+ */
+#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+ EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION;
+#endif
+
+/**
+ * event_groups.h
+ *+ EventGroupHandle_t xEventGroupCreateStatic( EventGroupHandle_t * pxEventGroupBuffer ); ++ * + * Create a new event group. + * + * Internally, within the FreeRTOS implementation, event groups use a [small] + * block of memory, in which the event group's structure is stored. If an event + * groups is created using xEventGropuCreate() then the required memory is + * automatically dynamically allocated inside the xEventGroupCreate() function. + * (see http://www.freertos.org/a00111.html). If an event group is created + * using xEventGropuCreateStatic() then the application writer must instead + * provide the memory that will get used by the event group. + * xEventGroupCreateStatic() therefore allows an event group to be created + * without using any dynamic memory allocation. + * + * Although event groups are not related to ticks, for internal implementation + * reasons the number of bits available for use in an event group is dependent + * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h. If + * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit + * 0 to bit 7). If configUSE_16_BIT_TICKS is set to 0 then each event group has + * 24 usable bits (bit 0 to bit 23). The EventBits_t type is used to store + * event bits within an event group. + * + * @param pxEventGroupBuffer pxEventGroupBuffer must point to a variable of type + * StaticEventGroup_t, which will be then be used to hold the event group's data + * structures, removing the need for the memory to be allocated dynamically. + * + * @return If the event group was created then a handle to the event group is + * returned. If pxEventGroupBuffer was NULL then NULL is returned. + * + * Example usage: +
+ // StaticEventGroup_t is a publicly accessible structure that has the same + // size and alignment requirements as the real event group structure. It is + // provided as a mechanism for applications to know the size of the event + // group (which is dependent on the architecture and configuration file + // settings) without breaking the strict data hiding policy by exposing the + // real event group internals. This StaticEventGroup_t variable is passed + // into the xSemaphoreCreateEventGroupStatic() function and is used to store + // the event group's data structures + StaticEventGroup_t xEventGroupBuffer; + + // Create the event group without dynamically allocating any memory. + xEventGroup = xEventGroupCreateStatic( &xEventGroupBuffer ); ++ */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) PRIVILEGED_FUNCTION; +#endif + +/** + * event_groups.h + *
+ EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToWaitFor, + const BaseType_t xClearOnExit, + const BaseType_t xWaitForAllBits, + const TickType_t xTicksToWait ); ++ * + * [Potentially] block to wait for one or more bits to be set within a + * previously created event group. + * + * This function cannot be called from an interrupt. + * + * @param xEventGroup The event group in which the bits are being tested. The + * event group must have previously been created using a call to + * xEventGroupCreate(). + * + * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test + * inside the event group. For example, to wait for bit 0 and/or bit 2 set + * uxBitsToWaitFor to 0x05. To wait for bits 0 and/or bit 1 and/or bit 2 set + * uxBitsToWaitFor to 0x07. Etc. + * + * @param xClearOnExit If xClearOnExit is set to pdTRUE then any bits within + * uxBitsToWaitFor that are set within the event group will be cleared before + * xEventGroupWaitBits() returns if the wait condition was met (if the function + * returns for a reason other than a timeout). If xClearOnExit is set to + * pdFALSE then the bits set in the event group are not altered when the call to + * xEventGroupWaitBits() returns. + * + * @param xWaitForAllBits If xWaitForAllBits is set to pdTRUE then + * xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor + * are set or the specified block time expires. If xWaitForAllBits is set to + * pdFALSE then xEventGroupWaitBits() will return when any one of the bits set + * in uxBitsToWaitFor is set or the specified block time expires. The block + * time is specified by the xTicksToWait parameter. + * + * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait + * for one/all (depending on the xWaitForAllBits value) of the bits specified by + * uxBitsToWaitFor to become set. + * + * @return The value of the event group at the time either the bits being waited + * for became set, or the block time expired. Test the return value to know + * which bits were set. If xEventGroupWaitBits() returned because its timeout + * expired then not all the bits being waited for will be set. If + * xEventGroupWaitBits() returned because the bits it was waiting for were set + * then the returned value is the event group value before any bits were + * automatically cleared in the case that xClearOnExit parameter was set to + * pdTRUE. + * + * Example usage: +
+ #define BIT_0 ( 1 << 0 )
+ #define BIT_4 ( 1 << 4 )
+
+ void aFunction( EventGroupHandle_t xEventGroup )
+ {
+ EventBits_t uxBits;
+ const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
+
+ // Wait a maximum of 100ms for either bit 0 or bit 4 to be set within
+ // the event group. Clear the bits before exiting.
+ uxBits = xEventGroupWaitBits(
+ xEventGroup, // The event group being tested.
+ BIT_0 | BIT_4, // The bits within the event group to wait for.
+ pdTRUE, // BIT_0 and BIT_4 should be cleared before returning.
+ pdFALSE, // Don't wait for both bits, either bit will do.
+ xTicksToWait ); // Wait a maximum of 100ms for either bit to be set.
+
+ if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+ {
+ // xEventGroupWaitBits() returned because both bits were set.
+ }
+ else if( ( uxBits & BIT_0 ) != 0 )
+ {
+ // xEventGroupWaitBits() returned because just BIT_0 was set.
+ }
+ else if( ( uxBits & BIT_4 ) != 0 )
+ {
+ // xEventGroupWaitBits() returned because just BIT_4 was set.
+ }
+ else
+ {
+ // xEventGroupWaitBits() returned because xTicksToWait ticks passed
+ // without either BIT_0 or BIT_4 becoming set.
+ }
+ }
+
+ * \defgroup xEventGroupWaitBits xEventGroupWaitBits
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/**
+ * event_groups.h
+ *+ EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ); ++ * + * Clear bits within an event group. This function cannot be called from an + * interrupt. + * + * @param xEventGroup The event group in which the bits are to be cleared. + * + * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear + * in the event group. For example, to clear bit 3 only, set uxBitsToClear to + * 0x08. To clear bit 3 and bit 0 set uxBitsToClear to 0x09. + * + * @return The value of the event group before the specified bits were cleared. + * + * Example usage: +
+ #define BIT_0 ( 1 << 0 )
+ #define BIT_4 ( 1 << 4 )
+
+ void aFunction( EventGroupHandle_t xEventGroup )
+ {
+ EventBits_t uxBits;
+
+ // Clear bit 0 and bit 4 in xEventGroup.
+ uxBits = xEventGroupClearBits(
+ xEventGroup, // The event group being updated.
+ BIT_0 | BIT_4 );// The bits being cleared.
+
+ if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+ {
+ // Both bit 0 and bit 4 were set before xEventGroupClearBits() was
+ // called. Both will now be clear (not set).
+ }
+ else if( ( uxBits & BIT_0 ) != 0 )
+ {
+ // Bit 0 was set before xEventGroupClearBits() was called. It will
+ // now be clear.
+ }
+ else if( ( uxBits & BIT_4 ) != 0 )
+ {
+ // Bit 4 was set before xEventGroupClearBits() was called. It will
+ // now be clear.
+ }
+ else
+ {
+ // Neither bit 0 nor bit 4 were set in the first place.
+ }
+ }
+
+ * \defgroup xEventGroupClearBits xEventGroupClearBits
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION;
+
+/**
+ * event_groups.h
+ *+ BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ); ++ * + * A version of xEventGroupClearBits() that can be called from an interrupt. + * + * Setting bits in an event group is not a deterministic operation because there + * are an unknown number of tasks that may be waiting for the bit or bits being + * set. FreeRTOS does not allow nondeterministic operations to be performed + * while interrupts are disabled, so protects event groups that are accessed + * from tasks by suspending the scheduler rather than disabling interrupts. As + * a result event groups cannot be accessed directly from an interrupt service + * routine. Therefore xEventGroupClearBitsFromISR() sends a message to the + * timer task to have the clear operation performed in the context of the timer + * task. + * + * @param xEventGroup The event group in which the bits are to be cleared. + * + * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear. + * For example, to clear bit 3 only, set uxBitsToClear to 0x08. To clear bit 3 + * and bit 0 set uxBitsToClear to 0x09. + * + * @return If the request to execute the function was posted successfully then + * pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned + * if the timer service queue was full. + * + * Example usage: +
+ #define BIT_0 ( 1 << 0 )
+ #define BIT_4 ( 1 << 4 )
+
+ // An event group which it is assumed has already been created by a call to
+ // xEventGroupCreate().
+ EventGroupHandle_t xEventGroup;
+
+ void anInterruptHandler( void )
+ {
+ // Clear bit 0 and bit 4 in xEventGroup.
+ xResult = xEventGroupClearBitsFromISR(
+ xEventGroup, // The event group being updated.
+ BIT_0 | BIT_4 ); // The bits being set.
+
+ if( xResult == pdPASS )
+ {
+ // The message was posted successfully.
+ }
+ }
+
+ * \defgroup xEventGroupClearBitsFromISR xEventGroupClearBitsFromISR
+ * \ingroup EventGroup
+ */
+#if( configUSE_TRACE_FACILITY == 1 )
+ BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION;
+#else
+ #define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL )
+#endif
+
+/**
+ * event_groups.h
+ *+ EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ); ++ * + * Set bits within an event group. + * This function cannot be called from an interrupt. xEventGroupSetBitsFromISR() + * is a version that can be called from an interrupt. + * + * Setting bits in an event group will automatically unblock tasks that are + * blocked waiting for the bits. + * + * @param xEventGroup The event group in which the bits are to be set. + * + * @param uxBitsToSet A bitwise value that indicates the bit or bits to set. + * For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 + * and bit 0 set uxBitsToSet to 0x09. + * + * @return The value of the event group at the time the call to + * xEventGroupSetBits() returns. There are two reasons why the returned value + * might have the bits specified by the uxBitsToSet parameter cleared. First, + * if setting a bit results in a task that was waiting for the bit leaving the + * blocked state then it is possible the bit will be cleared automatically + * (see the xClearBitOnExit parameter of xEventGroupWaitBits()). Second, any + * unblocked (or otherwise Ready state) task that has a priority above that of + * the task that called xEventGroupSetBits() will execute and may change the + * event group value before the call to xEventGroupSetBits() returns. + * + * Example usage: +
+ #define BIT_0 ( 1 << 0 )
+ #define BIT_4 ( 1 << 4 )
+
+ void aFunction( EventGroupHandle_t xEventGroup )
+ {
+ EventBits_t uxBits;
+
+ // Set bit 0 and bit 4 in xEventGroup.
+ uxBits = xEventGroupSetBits(
+ xEventGroup, // The event group being updated.
+ BIT_0 | BIT_4 );// The bits being set.
+
+ if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+ {
+ // Both bit 0 and bit 4 remained set when the function returned.
+ }
+ else if( ( uxBits & BIT_0 ) != 0 )
+ {
+ // Bit 0 remained set when the function returned, but bit 4 was
+ // cleared. It might be that bit 4 was cleared automatically as a
+ // task that was waiting for bit 4 was removed from the Blocked
+ // state.
+ }
+ else if( ( uxBits & BIT_4 ) != 0 )
+ {
+ // Bit 4 remained set when the function returned, but bit 0 was
+ // cleared. It might be that bit 0 was cleared automatically as a
+ // task that was waiting for bit 0 was removed from the Blocked
+ // state.
+ }
+ else
+ {
+ // Neither bit 0 nor bit 4 remained set. It might be that a task
+ // was waiting for both of the bits to be set, and the bits were
+ // cleared as the task left the Blocked state.
+ }
+ }
+
+ * \defgroup xEventGroupSetBits xEventGroupSetBits
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) PRIVILEGED_FUNCTION;
+
+/**
+ * event_groups.h
+ *+ BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ); ++ * + * A version of xEventGroupSetBits() that can be called from an interrupt. + * + * Setting bits in an event group is not a deterministic operation because there + * are an unknown number of tasks that may be waiting for the bit or bits being + * set. FreeRTOS does not allow nondeterministic operations to be performed in + * interrupts or from critical sections. Therefore xEventGroupSetBitsFromISR() + * sends a message to the timer task to have the set operation performed in the + * context of the timer task - where a scheduler lock is used in place of a + * critical section. + * + * @param xEventGroup The event group in which the bits are to be set. + * + * @param uxBitsToSet A bitwise value that indicates the bit or bits to set. + * For example, to set bit 3 only, set uxBitsToSet to 0x08. To set bit 3 + * and bit 0 set uxBitsToSet to 0x09. + * + * @param pxHigherPriorityTaskWoken As mentioned above, calling this function + * will result in a message being sent to the timer daemon task. If the + * priority of the timer daemon task is higher than the priority of the + * currently running task (the task the interrupt interrupted) then + * *pxHigherPriorityTaskWoken will be set to pdTRUE by + * xEventGroupSetBitsFromISR(), indicating that a context switch should be + * requested before the interrupt exits. For that reason + * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the + * example code below. + * + * @return If the request to execute the function was posted successfully then + * pdPASS is returned, otherwise pdFALSE is returned. pdFALSE will be returned + * if the timer service queue was full. + * + * Example usage: +
+ #define BIT_0 ( 1 << 0 )
+ #define BIT_4 ( 1 << 4 )
+
+ // An event group which it is assumed has already been created by a call to
+ // xEventGroupCreate().
+ EventGroupHandle_t xEventGroup;
+
+ void anInterruptHandler( void )
+ {
+ BaseType_t xHigherPriorityTaskWoken, xResult;
+
+ // xHigherPriorityTaskWoken must be initialised to pdFALSE.
+ xHigherPriorityTaskWoken = pdFALSE;
+
+ // Set bit 0 and bit 4 in xEventGroup.
+ xResult = xEventGroupSetBitsFromISR(
+ xEventGroup, // The event group being updated.
+ BIT_0 | BIT_4 // The bits being set.
+ &xHigherPriorityTaskWoken );
+
+ // Was the message posted successfully?
+ if( xResult == pdPASS )
+ {
+ // If xHigherPriorityTaskWoken is now set to pdTRUE then a context
+ // switch should be requested. The macro used is port specific and
+ // will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() -
+ // refer to the documentation page for the port being used.
+ portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
+ }
+ }
+
+ * \defgroup xEventGroupSetBitsFromISR xEventGroupSetBitsFromISR
+ * \ingroup EventGroup
+ */
+#if( configUSE_TRACE_FACILITY == 1 )
+ BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+#else
+ #define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken )
+#endif
+
+/**
+ * event_groups.h
+ *+ EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, + const EventBits_t uxBitsToSet, + const EventBits_t uxBitsToWaitFor, + TickType_t xTicksToWait ); ++ * + * Atomically set bits within an event group, then wait for a combination of + * bits to be set within the same event group. This functionality is typically + * used to synchronise multiple tasks, where each task has to wait for the other + * tasks to reach a synchronisation point before proceeding. + * + * This function cannot be used from an interrupt. + * + * The function will return before its block time expires if the bits specified + * by the uxBitsToWait parameter are set, or become set within that time. In + * this case all the bits specified by uxBitsToWait will be automatically + * cleared before the function returns. + * + * @param xEventGroup The event group in which the bits are being tested. The + * event group must have previously been created using a call to + * xEventGroupCreate(). + * + * @param uxBitsToSet The bits to set in the event group before determining + * if, and possibly waiting for, all the bits specified by the uxBitsToWait + * parameter are set. + * + * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test + * inside the event group. For example, to wait for bit 0 and bit 2 set + * uxBitsToWaitFor to 0x05. To wait for bits 0 and bit 1 and bit 2 set + * uxBitsToWaitFor to 0x07. Etc. + * + * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait + * for all of the bits specified by uxBitsToWaitFor to become set. + * + * @return The value of the event group at the time either the bits being waited + * for became set, or the block time expired. Test the return value to know + * which bits were set. If xEventGroupSync() returned because its timeout + * expired then not all the bits being waited for will be set. If + * xEventGroupSync() returned because all the bits it was waiting for were + * set then the returned value is the event group value before any bits were + * automatically cleared. + * + * Example usage: +
+ // Bits used by the three tasks.
+ #define TASK_0_BIT ( 1 << 0 )
+ #define TASK_1_BIT ( 1 << 1 )
+ #define TASK_2_BIT ( 1 << 2 )
+
+ #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT )
+
+ // Use an event group to synchronise three tasks. It is assumed this event
+ // group has already been created elsewhere.
+ EventGroupHandle_t xEventBits;
+
+ void vTask0( void *pvParameters )
+ {
+ EventBits_t uxReturn;
+ TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
+
+ for( ;; )
+ {
+ // Perform task functionality here.
+
+ // Set bit 0 in the event flag to note this task has reached the
+ // sync point. The other two tasks will set the other two bits defined
+ // by ALL_SYNC_BITS. All three tasks have reached the synchronisation
+ // point when all the ALL_SYNC_BITS are set. Wait a maximum of 100ms
+ // for this to happen.
+ uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait );
+
+ if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS )
+ {
+ // All three tasks reached the synchronisation point before the call
+ // to xEventGroupSync() timed out.
+ }
+ }
+ }
+
+ void vTask1( void *pvParameters )
+ {
+ for( ;; )
+ {
+ // Perform task functionality here.
+
+ // Set bit 1 in the event flag to note this task has reached the
+ // synchronisation point. The other two tasks will set the other two
+ // bits defined by ALL_SYNC_BITS. All three tasks have reached the
+ // synchronisation point when all the ALL_SYNC_BITS are set. Wait
+ // indefinitely for this to happen.
+ xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY );
+
+ // xEventGroupSync() was called with an indefinite block time, so
+ // this task will only reach here if the syncrhonisation was made by all
+ // three tasks, so there is no need to test the return value.
+ }
+ }
+
+ void vTask2( void *pvParameters )
+ {
+ for( ;; )
+ {
+ // Perform task functionality here.
+
+ // Set bit 2 in the event flag to note this task has reached the
+ // synchronisation point. The other two tasks will set the other two
+ // bits defined by ALL_SYNC_BITS. All three tasks have reached the
+ // synchronisation point when all the ALL_SYNC_BITS are set. Wait
+ // indefinitely for this to happen.
+ xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
+
+ // xEventGroupSync() was called with an indefinite block time, so
+ // this task will only reach here if the syncrhonisation was made by all
+ // three tasks, so there is no need to test the return value.
+ }
+ }
+
+
+ * \defgroup xEventGroupSync xEventGroupSync
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+
+/**
+ * event_groups.h
+ *+ EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup ); ++ * + * Returns the current value of the bits in an event group. This function + * cannot be used from an interrupt. + * + * @param xEventGroup The event group being queried. + * + * @return The event group bits at the time xEventGroupGetBits() was called. + * + * \defgroup xEventGroupGetBits xEventGroupGetBits + * \ingroup EventGroup + */ +#define xEventGroupGetBits( xEventGroup ) xEventGroupClearBits( xEventGroup, 0 ) + +/** + * event_groups.h + *
+ EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ); ++ * + * A version of xEventGroupGetBits() that can be called from an ISR. + * + * @param xEventGroup The event group being queried. + * + * @return The event group bits at the time xEventGroupGetBitsFromISR() was called. + * + * \defgroup xEventGroupGetBitsFromISR xEventGroupGetBitsFromISR + * \ingroup EventGroup + */ +EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; + +/** + * event_groups.h + *
+ void xEventGroupDelete( EventGroupHandle_t xEventGroup ); ++ * + * Delete an event group that was previously created by a call to + * xEventGroupCreate(). Tasks that are blocked on the event group will be + * unblocked and obtain 0 as the event group's value. + * + * @param xEventGroup The event group being deleted. + */ +void vEventGroupDelete( EventGroupHandle_t xEventGroup ) PRIVILEGED_FUNCTION; + +/* For internal use only. */ +void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet ) PRIVILEGED_FUNCTION; +void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION; + + +#if (configUSE_TRACE_FACILITY == 1) + UBaseType_t uxEventGroupGetNumber( void* xEventGroup ) PRIVILEGED_FUNCTION; + void vEventGroupSetNumber( void* xEventGroup, UBaseType_t uxEventGroupNumber ) PRIVILEGED_FUNCTION; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* EVENT_GROUPS_H */ + + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/list.h b/Middlewares/Third_Party/FreeRTOS/Source/include/list.h new file mode 100644 index 0000000..a3e3024 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/list.h @@ -0,0 +1,412 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * This is the list implementation used by the scheduler. While it is tailored + * heavily for the schedulers needs, it is also available for use by + * application code. + * + * list_ts can only store pointers to list_item_ts. Each ListItem_t contains a + * numeric value (xItemValue). Most of the time the lists are sorted in + * descending item value order. + * + * Lists are created already containing one list item. The value of this + * item is the maximum possible that can be stored, it is therefore always at + * the end of the list and acts as a marker. The list member pxHead always + * points to this marker - even though it is at the tail of the list. This + * is because the tail contains a wrap back pointer to the true head of + * the list. + * + * In addition to it's value, each list item contains a pointer to the next + * item in the list (pxNext), a pointer to the list it is in (pxContainer) + * and a pointer to back to the object that contains it. These later two + * pointers are included for efficiency of list manipulation. There is + * effectively a two way link between the object containing the list item and + * the list item itself. + * + * + * \page ListIntroduction List Implementation + * \ingroup FreeRTOSIntro + */ + +#ifndef INC_FREERTOS_H + #error FreeRTOS.h must be included before list.h +#endif + +#ifndef LIST_H +#define LIST_H + +/* + * The list structure members are modified from within interrupts, and therefore + * by rights should be declared volatile. However, they are only modified in a + * functionally atomic way (within critical sections of with the scheduler + * suspended) and are either passed by reference into a function or indexed via + * a volatile variable. Therefore, in all use cases tested so far, the volatile + * qualifier can be omitted in order to provide a moderate performance + * improvement without adversely affecting functional behaviour. The assembly + * instructions generated by the IAR, ARM and GCC compilers when the respective + * compiler's options were set for maximum optimisation has been inspected and + * deemed to be as intended. That said, as compiler technology advances, and + * especially if aggressive cross module optimisation is used (a use case that + * has not been exercised to any great extend) then it is feasible that the + * volatile qualifier will be needed for correct optimisation. It is expected + * that a compiler removing essential code because, without the volatile + * qualifier on the list structure members and with aggressive cross module + * optimisation, the compiler deemed the code unnecessary will result in + * complete and obvious failure of the scheduler. If this is ever experienced + * then the volatile qualifier can be inserted in the relevant places within the + * list structures by simply defining configLIST_VOLATILE to volatile in + * FreeRTOSConfig.h (as per the example at the bottom of this comment block). + * If configLIST_VOLATILE is not defined then the preprocessor directives below + * will simply #define configLIST_VOLATILE away completely. + * + * To use volatile list structure members then add the following line to + * FreeRTOSConfig.h (without the quotes): + * "#define configLIST_VOLATILE volatile" + */ +#ifndef configLIST_VOLATILE + #define configLIST_VOLATILE +#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Macros that can be used to place known values within the list structures, +then check that the known values do not get corrupted during the execution of +the application. These may catch the list data structures being overwritten in +memory. They will not catch data errors caused by incorrect configuration or +use of FreeRTOS.*/ +#if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 ) + /* Define the macros to do nothing. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) + #define listTEST_LIST_INTEGRITY( pxList ) +#else + /* Define macros that add new members into the list structures. */ + #define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue1; + #define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE TickType_t xListItemIntegrityValue2; + #define listFIRST_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue1; + #define listSECOND_LIST_INTEGRITY_CHECK_VALUE TickType_t xListIntegrityValue2; + + /* Define macros that set the new structure members to known values. */ + #define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ) ( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ) ( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE + #define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ) ( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE + + /* Define macros that will assert if one of the structure members does not + contain its expected value. */ + #define listTEST_LIST_ITEM_INTEGRITY( pxItem ) configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) + #define listTEST_LIST_INTEGRITY( pxList ) configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) ) +#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */ + + +/* + * Definition of the only type of object that a list can contain. + */ +struct xLIST; +struct xLIST_ITEM +{ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; /*< The value being listed. In most cases this is used to sort the list in descending order. */ + struct xLIST_ITEM * configLIST_VOLATILE pxNext; /*< Pointer to the next ListItem_t in the list. */ + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; /*< Pointer to the previous ListItem_t in the list. */ + void * pvOwner; /*< Pointer to the object (normally a TCB) that contains the list item. There is therefore a two way link between the object containing the list item and the list item itself. */ + struct xLIST * configLIST_VOLATILE pxContainer; /*< Pointer to the list in which this list item is placed (if any). */ + listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ +}; +typedef struct xLIST_ITEM ListItem_t; /* For some reason lint wants this as two separate definitions. */ + +struct xMINI_LIST_ITEM +{ + listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + configLIST_VOLATILE TickType_t xItemValue; + struct xLIST_ITEM * configLIST_VOLATILE pxNext; + struct xLIST_ITEM * configLIST_VOLATILE pxPrevious; +}; +typedef struct xMINI_LIST_ITEM MiniListItem_t; + +/* + * Definition of the type of queue used by the scheduler. + */ +typedef struct xLIST +{ + listFIRST_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + volatile UBaseType_t uxNumberOfItems; + ListItem_t * configLIST_VOLATILE pxIndex; /*< Used to walk through the list. Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */ + MiniListItem_t xListEnd; /*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */ + listSECOND_LIST_INTEGRITY_CHECK_VALUE /*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ +} List_t; + +/* + * Access macro to set the owner of a list item. The owner of a list item + * is the object (usually a TCB) that contains the list item. + * + * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER + * \ingroup LinkedList + */ +#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner ) ( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) ) + +/* + * Access macro to get the owner of a list item. The owner of a list item + * is the object (usually a TCB) that contains the list item. + * + * \page listGET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER + * \ingroup LinkedList + */ +#define listGET_LIST_ITEM_OWNER( pxListItem ) ( ( pxListItem )->pvOwner ) + +/* + * Access macro to set the value of the list item. In most cases the value is + * used to sort the list in descending order. + * + * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listSET_LIST_ITEM_VALUE( pxListItem, xValue ) ( ( pxListItem )->xItemValue = ( xValue ) ) + +/* + * Access macro to retrieve the value of the list item. The value can + * represent anything - for example the priority of a task, or the time at + * which a task should be unblocked. + * + * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listGET_LIST_ITEM_VALUE( pxListItem ) ( ( pxListItem )->xItemValue ) + +/* + * Access macro to retrieve the value of the list item at the head of a given + * list. + * + * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE + * \ingroup LinkedList + */ +#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext->xItemValue ) + +/* + * Return the list item at the head of the list. + * + * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY + * \ingroup LinkedList + */ +#define listGET_HEAD_ENTRY( pxList ) ( ( ( pxList )->xListEnd ).pxNext ) + +/* + * Return the next list item. + * + * \page listGET_NEXT listGET_NEXT + * \ingroup LinkedList + */ +#define listGET_NEXT( pxListItem ) ( ( pxListItem )->pxNext ) + +/* + * Return the list item that marks the end of the list + * + * \page listGET_END_MARKER listGET_END_MARKER + * \ingroup LinkedList + */ +#define listGET_END_MARKER( pxList ) ( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) ) + +/* + * Access macro to determine if a list contains any items. The macro will + * only have the value true if the list is empty. + * + * \page listLIST_IS_EMPTY listLIST_IS_EMPTY + * \ingroup LinkedList + */ +#define listLIST_IS_EMPTY( pxList ) ( ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) ? pdTRUE : pdFALSE ) + +/* + * Access macro to return the number of items in the list. + */ +#define listCURRENT_LIST_LENGTH( pxList ) ( ( pxList )->uxNumberOfItems ) + +/* + * Access function to obtain the owner of the next entry in a list. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list + * and returns that entry's pxOwner parameter. Using multiple calls to this + * function it is therefore possible to move through every item contained in + * a list. + * + * The pxOwner parameter of a list item is a pointer to the object that owns + * the list item. In the scheduler this is normally a task control block. + * The pxOwner parameter effectively creates a two way link between the list + * item and its owner. + * + * @param pxTCB pxTCB is set to the address of the owner of the next list item. + * @param pxList The list from which the next item owner is to be returned. + * + * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY + * \ingroup LinkedList + */ +#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList ) \ +{ \ +List_t * const pxConstList = ( pxList ); \ + /* Increment the index to the next item and return the item, ensuring */ \ + /* we don't return the marker used at the end of the list. */ \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) ) \ + { \ + ( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext; \ + } \ + ( pxTCB ) = ( pxConstList )->pxIndex->pvOwner; \ +} + + +/* + * Access function to obtain the owner of the first entry in a list. Lists + * are normally sorted in ascending item value order. + * + * This function returns the pxOwner member of the first item in the list. + * The pxOwner parameter of a list item is a pointer to the object that owns + * the list item. In the scheduler this is normally a task control block. + * The pxOwner parameter effectively creates a two way link between the list + * item and its owner. + * + * @param pxList The list from which the owner of the head item is to be + * returned. + * + * \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY + * \ingroup LinkedList + */ +#define listGET_OWNER_OF_HEAD_ENTRY( pxList ) ( (&( ( pxList )->xListEnd ))->pxNext->pvOwner ) + +/* + * Check to see if a list item is within a list. The list item maintains a + * "container" pointer that points to the list it is in. All this macro does + * is check to see if the container and the list match. + * + * @param pxList The list we want to know if the list item is within. + * @param pxListItem The list item we want to know if is in the list. + * @return pdTRUE if the list item is in the list, otherwise pdFALSE. + */ +#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( ( pxListItem )->pxContainer == ( pxList ) ) ? ( pdTRUE ) : ( pdFALSE ) ) + +/* + * Return the list a list item is contained within (referenced from). + * + * @param pxListItem The list item being queried. + * @return A pointer to the List_t object that references the pxListItem + */ +#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pxContainer ) + +/* + * This provides a crude means of knowing if a list has been initialised, as + * pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise() + * function. + */ +#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY ) + +/* + * Must be called before a list is used! This initialises all the members + * of the list structure and inserts the xListEnd item into the list as a + * marker to the back of the list. + * + * @param pxList Pointer to the list being initialised. + * + * \page vListInitialise vListInitialise + * \ingroup LinkedList + */ +void vListInitialise( List_t * const pxList ) PRIVILEGED_FUNCTION; + +/* + * Must be called before a list item is used. This sets the list container to + * null so the item does not think that it is already contained in a list. + * + * @param pxItem Pointer to the list item being initialised. + * + * \page vListInitialiseItem vListInitialiseItem + * \ingroup LinkedList + */ +void vListInitialiseItem( ListItem_t * const pxItem ) PRIVILEGED_FUNCTION; + +/* + * Insert a list item into a list. The item will be inserted into the list in + * a position determined by its item value (descending item value order). + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The item that is to be placed in the list. + * + * \page vListInsert vListInsert + * \ingroup LinkedList + */ +void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; + +/* + * Insert a list item into a list. The item will be inserted in a position + * such that it will be the last item within the list returned by multiple + * calls to listGET_OWNER_OF_NEXT_ENTRY. + * + * The list member pxIndex is used to walk through a list. Calling + * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list. + * Placing an item in a list using vListInsertEnd effectively places the item + * in the list position pointed to by pxIndex. This means that every other + * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before + * the pxIndex parameter again points to the item being inserted. + * + * @param pxList The list into which the item is to be inserted. + * + * @param pxNewListItem The list item to be inserted into the list. + * + * \page vListInsertEnd vListInsertEnd + * \ingroup LinkedList + */ +void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem ) PRIVILEGED_FUNCTION; + +/* + * Remove an item from a list. The list item has a pointer to the list that + * it is in, so only the list item need be passed into the function. + * + * @param uxListRemove The item to be removed. The item will remove itself from + * the list pointed to by it's pxContainer parameter. + * + * @return The number of items that remain in the list after the list item has + * been removed. + * + * \page uxListRemove uxListRemove + * \ingroup LinkedList + */ +UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) PRIVILEGED_FUNCTION; + +#ifdef __cplusplus +} +#endif + +#endif + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h b/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h new file mode 100644 index 0000000..0c3edb9 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/message_buffer.h @@ -0,0 +1,803 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +/* + * Message buffers build functionality on top of FreeRTOS stream buffers. + * Whereas stream buffers are used to send a continuous stream of data from one + * task or interrupt to another, message buffers are used to send variable + * length discrete messages from one task or interrupt to another. Their + * implementation is light weight, making them particularly suited for interrupt + * to task and core to core communication scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * timeout to 0. + * + * Message buffers hold variable length messages. To enable that, when a + * message is written to the message buffer an additional sizeof( size_t ) bytes + * are also written to store the message's length (that happens internally, with + * the API function). sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so writing a 10 byte message to a message buffer on a 32-bit + * architecture will actually reduce the available space in the message buffer + * by 14 bytes (10 byte are used by the message, and 4 bytes to hold the length + * of the message). + */ + +#ifndef FREERTOS_MESSAGE_BUFFER_H +#define FREERTOS_MESSAGE_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include message_buffer.h" +#endif + +/* Message buffers are built onto of stream buffers. */ +#include "stream_buffer.h" + +#if defined( __cplusplus ) +extern "C" { +#endif + +/** + * Type by which message buffers are referenced. For example, a call to + * xMessageBufferCreate() returns an MessageBufferHandle_t variable that can + * then be used as a parameter to xMessageBufferSend(), xMessageBufferReceive(), + * etc. + */ +typedef void * MessageBufferHandle_t; + +/*-----------------------------------------------------------*/ + +/** + * message_buffer.h + * +
+MessageBufferHandle_t xMessageBufferCreate( size_t xBufferSizeBytes ); ++ * + * Creates a new message buffer using dynamically allocated memory. See + * xMessageBufferCreateStatic() for a version that uses statically allocated + * memory (memory that is allocated at compile time). + * + * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in + * FreeRTOSConfig.h for xMessageBufferCreate() to be available. + * + * @param xBufferSizeBytes The total number of bytes (not messages) the message + * buffer will be able to hold at any one time. When a message is written to + * the message buffer an additional sizeof( size_t ) bytes are also written to + * store the message's length. sizeof( size_t ) is typically 4 bytes on a + * 32-bit architecture, so on most 32-bit architectures a 10 byte message will + * take up 14 bytes of message buffer space. + * + * @return If NULL is returned, then the message buffer cannot be created + * because there is insufficient heap memory available for FreeRTOS to allocate + * the message buffer data structures and storage area. A non-NULL value being + * returned indicates that the message buffer has been created successfully - + * the returned value should be stored as the handle to the created message + * buffer. + * + * Example use: +
+
+void vAFunction( void )
+{
+MessageBufferHandle_t xMessageBuffer;
+const size_t xMessageBufferSizeBytes = 100;
+
+ // Create a message buffer that can hold 100 bytes. The memory used to hold
+ // both the message buffer structure and the messages themselves is allocated
+ // dynamically. Each message added to the buffer consumes an additional 4
+ // bytes which are used to hold the lengh of the message.
+ xMessageBuffer = xMessageBufferCreate( xMessageBufferSizeBytes );
+
+ if( xMessageBuffer == NULL )
+ {
+ // There was not enough heap memory space available to create the
+ // message buffer.
+ }
+ else
+ {
+ // The message buffer was created successfully and can now be used.
+ }
+
+
+ * \defgroup xMessageBufferCreate xMessageBufferCreate
+ * \ingroup MessageBufferManagement
+ */
+#define xMessageBufferCreate( xBufferSizeBytes ) ( MessageBufferHandle_t ) xStreamBufferGenericCreate( xBufferSizeBytes, ( size_t ) 0, pdTRUE )
+
+/**
+ * message_buffer.h
+ *
++MessageBufferHandle_t xMessageBufferCreateStatic( size_t xBufferSizeBytes, + uint8_t *pucMessageBufferStorageArea, + StaticMessageBuffer_t *pxStaticMessageBuffer ); ++ * Creates a new message buffer using statically allocated memory. See + * xMessageBufferCreate() for a version that uses dynamically allocated memory. + * + * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the + * pucMessageBufferStorageArea parameter. When a message is written to the + * message buffer an additional sizeof( size_t ) bytes are also written to store + * the message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so on most 32-bit architecture a 10 byte message will take up + * 14 bytes of message buffer space. The maximum number of bytes that can be + * stored in the message buffer is actually (xBufferSizeBytes - 1). + * + * @param pucMessageBufferStorageArea Must point to a uint8_t array that is at + * least xBufferSizeBytes + 1 big. This is the array to which messages are + * copied when they are written to the message buffer. + * + * @param pxStaticMessageBuffer Must point to a variable of type + * StaticMessageBuffer_t, which will be used to hold the message buffer's data + * structure. + * + * @return If the message buffer is created successfully then a handle to the + * created message buffer is returned. If either pucMessageBufferStorageArea or + * pxStaticmessageBuffer are NULL then NULL is returned. + * + * Example use: +
+
+// Used to dimension the array used to hold the messages. The available space
+// will actually be one less than this, so 999.
+#define STORAGE_SIZE_BYTES 1000
+
+// Defines the memory that will actually hold the messages within the message
+// buffer.
+static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ];
+
+// The variable used to hold the message buffer structure.
+StaticMessageBuffer_t xMessageBufferStruct;
+
+void MyFunction( void )
+{
+MessageBufferHandle_t xMessageBuffer;
+
+ xMessageBuffer = xMessageBufferCreateStatic( sizeof( ucBufferStorage ),
+ ucBufferStorage,
+ &xMessageBufferStruct );
+
+ // As neither the pucMessageBufferStorageArea or pxStaticMessageBuffer
+ // parameters were NULL, xMessageBuffer will not be NULL, and can be used to
+ // reference the created message buffer in other message buffer API calls.
+
+ // Other code that uses the message buffer can go here.
+}
+
+
+ * \defgroup xMessageBufferCreateStatic xMessageBufferCreateStatic
+ * \ingroup MessageBufferManagement
+ */
+#define xMessageBufferCreateStatic( xBufferSizeBytes, pucMessageBufferStorageArea, pxStaticMessageBuffer ) ( MessageBufferHandle_t ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, 0, pdTRUE, pucMessageBufferStorageArea, pxStaticMessageBuffer )
+
+/**
+ * message_buffer.h
+ *
++size_t xMessageBufferSend( MessageBufferHandle_t xMessageBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ); ++ * + * Sends a discrete message to the message buffer. The message can be any + * length that fits within the buffer's free space, and is copied into the + * buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferSend() to write to a message buffer from a task. Use + * xMessageBufferSendFromISR() to write to a message buffer from an interrupt + * service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer to which a message is + * being sent. + * + * @param pvTxData A pointer to the message that is to be copied into the + * message buffer. + * + * @param xDataLengthBytes The length of the message. That is, the number of + * bytes to copy from pvTxData into the message buffer. When a message is + * written to the message buffer an additional sizeof( size_t ) bytes are also + * written to store the message's length. sizeof( size_t ) is typically 4 bytes + * on a 32-bit architecture, so on most 32-bit architecture setting + * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 + * bytes (20 bytes of message data and 4 bytes to hold the message length). + * + * @param xTicksToWait The maximum amount of time the calling task should remain + * in the Blocked state to wait for enough space to become available in the + * message buffer, should the message buffer have insufficient space when + * xMessageBufferSend() is called. The calling task will never block if + * xTicksToWait is zero. The block time is specified in tick periods, so the + * absolute time it represents is dependent on the tick frequency. The macro + * pdMS_TO_TICKS() can be used to convert a time specified in milliseconds into + * a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will cause + * the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any + * CPU time when they are in the Blocked state. + * + * @return The number of bytes written to the message buffer. If the call to + * xMessageBufferSend() times out before there was enough space to write the + * message into the message buffer then zero is returned. If the call did not + * time out then xDataLengthBytes is returned. + * + * Example use: ++void vAFunction( MessageBufferHandle_t xMessageBuffer ) +{ +size_t xBytesSent; +uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; +char *pcStringToSend = "String to send"; +const TickType_t x100ms = pdMS_TO_TICKS( 100 ); + + // Send an array to the message buffer, blocking for a maximum of 100ms to + // wait for enough space to be available in the message buffer. + xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); + + if( xBytesSent != sizeof( ucArrayToSend ) ) + { + // The call to xMessageBufferSend() times out before there was enough + // space in the buffer for the data to be written. + } + + // Send the string to the message buffer. Return immediately if there is + // not enough space in the buffer. + xBytesSent = xMessageBufferSend( xMessageBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); + + if( xBytesSent != strlen( pcStringToSend ) ) + { + // The string could not be added to the message buffer because there was + // not enough free space in the buffer. + } +} ++ * \defgroup xMessageBufferSend xMessageBufferSend + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSend( xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) xStreamBufferSend( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, xTicksToWait ) + +/** + * message_buffer.h + * ++size_t xMessageBufferSendFromISR( MessageBufferHandle_t xMessageBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + BaseType_t *pxHigherPriorityTaskWoken ); ++ * + * Interrupt safe version of the API function that sends a discrete message to + * the message buffer. The message can be any length that fits within the + * buffer's free space, and is copied into the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferSend() to write to a message buffer from a task. Use + * xMessageBufferSendFromISR() to write to a message buffer from an interrupt + * service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer to which a message is + * being sent. + * + * @param pvTxData A pointer to the message that is to be copied into the + * message buffer. + * + * @param xDataLengthBytes The length of the message. That is, the number of + * bytes to copy from pvTxData into the message buffer. When a message is + * written to the message buffer an additional sizeof( size_t ) bytes are also + * written to store the message's length. sizeof( size_t ) is typically 4 bytes + * on a 32-bit architecture, so on most 32-bit architecture setting + * xDataLengthBytes to 20 will reduce the free space in the message buffer by 24 + * bytes (20 bytes of message data and 4 bytes to hold the message length). + * + * @param pxHigherPriorityTaskWoken It is possible that a message buffer will + * have a task blocked on it waiting for data. Calling + * xMessageBufferSendFromISR() can make data available, and so cause a task that + * was waiting for data to leave the Blocked state. If calling + * xMessageBufferSendFromISR() causes a task to leave the Blocked state, and the + * unblocked task has a priority higher than the currently executing task (the + * task that was interrupted), then, internally, xMessageBufferSendFromISR() + * will set *pxHigherPriorityTaskWoken to pdTRUE. If + * xMessageBufferSendFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. This will + * ensure that the interrupt returns directly to the highest priority Ready + * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it + * is passed into the function. See the code example below for an example. + * + * @return The number of bytes actually written to the message buffer. If the + * message buffer didn't have enough free space for the message to be stored + * then 0 is returned, otherwise xDataLengthBytes is returned. + * + * Example use: ++// A message buffer that has already been created. +MessageBufferHandle_t xMessageBuffer; + +void vAnInterruptServiceRoutine( void ) +{ +size_t xBytesSent; +char *pcStringToSend = "String to send"; +BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + + // Attempt to send the string to the message buffer. + xBytesSent = xMessageBufferSendFromISR( xMessageBuffer, + ( void * ) pcStringToSend, + strlen( pcStringToSend ), + &xHigherPriorityTaskWoken ); + + if( xBytesSent != strlen( pcStringToSend ) ) + { + // The string could not be added to the message buffer because there was + // not enough free space in the buffer. + } + + // If xHigherPriorityTaskWoken was set to pdTRUE inside + // xMessageBufferSendFromISR() then a task that has a priority above the + // priority of the currently executing task was unblocked and a context + // switch should be performed to ensure the ISR returns to the unblocked + // task. In most FreeRTOS ports this is done by simply passing + // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + // variables value, and perform the context switch if necessary. Check the + // documentation for the port in use for port specific instructions. + portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); +} ++ * \defgroup xMessageBufferSendFromISR xMessageBufferSendFromISR + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSendFromISR( xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferSendFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvTxData, xDataLengthBytes, pxHigherPriorityTaskWoken ) + +/** + * message_buffer.h + * ++size_t xMessageBufferReceive( MessageBufferHandle_t xMessageBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ); ++ * + * Receives a discrete message from a message buffer. Messages can be of + * variable length and are copied out of the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferReceive() to read from a message buffer from a task. Use + * xMessageBufferReceiveFromISR() to read from a message buffer from an + * interrupt service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer from which a message + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received message is + * to be copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData + * parameter. This sets the maximum length of the message that can be received. + * If xBufferLengthBytes is too small to hold the next message then the message + * will be left in the message buffer and 0 will be returned. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for a message, should the message buffer be empty. + * xMessageBufferReceive() will return immediately if xTicksToWait is zero and + * the message buffer is empty. The block time is specified in tick periods, so + * the absolute time it represents is dependent on the tick frequency. The + * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds + * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will + * cause the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. Tasks do not use any + * CPU time when they are in the Blocked state. + * + * @return The length, in bytes, of the message read from the message buffer, if + * any. If xMessageBufferReceive() times out before a message became available + * then zero is returned. If the length of the message is greater than + * xBufferLengthBytes then the message will be left in the message buffer and + * zero is returned. + * + * Example use: ++void vAFunction( MessageBuffer_t xMessageBuffer ) +{ +uint8_t ucRxData[ 20 ]; +size_t xReceivedBytes; +const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); + + // Receive the next message from the message buffer. Wait in the Blocked + // state (so not using any CPU processing time) for a maximum of 100ms for + // a message to become available. + xReceivedBytes = xMessageBufferReceive( xMessageBuffer, + ( void * ) ucRxData, + sizeof( ucRxData ), + xBlockTime ); + + if( xReceivedBytes > 0 ) + { + // A ucRxData contains a message that is xReceivedBytes long. Process + // the message here.... + } +} ++ * \defgroup xMessageBufferReceive xMessageBufferReceive + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReceive( xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) xStreamBufferReceive( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, xTicksToWait ) + + +/** + * message_buffer.h + * ++size_t xMessageBufferReceiveFromISR( MessageBufferHandle_t xMessageBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + BaseType_t *pxHigherPriorityTaskWoken ); ++ * + * An interrupt safe version of the API function that receives a discrete + * message from a message buffer. Messages can be of variable length and are + * copied out of the buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xMessageBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xMessageBufferRead()) inside a critical section and set the receive + * block time to 0. + * + * Use xMessageBufferReceive() to read from a message buffer from a task. Use + * xMessageBufferReceiveFromISR() to read from a message buffer from an + * interrupt service routine (ISR). + * + * @param xMessageBuffer The handle of the message buffer from which a message + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received message is + * to be copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the pvRxData + * parameter. This sets the maximum length of the message that can be received. + * If xBufferLengthBytes is too small to hold the next message then the message + * will be left in the message buffer and 0 will be returned. + * + * @param pxHigherPriorityTaskWoken It is possible that a message buffer will + * have a task blocked on it waiting for space to become available. Calling + * xMessageBufferReceiveFromISR() can make space available, and so cause a task + * that is waiting for space to leave the Blocked state. If calling + * xMessageBufferReceiveFromISR() causes a task to leave the Blocked state, and + * the unblocked task has a priority higher than the currently executing task + * (the task that was interrupted), then, internally, + * xMessageBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. + * If xMessageBufferReceiveFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. That will + * ensure the interrupt returns directly to the highest priority Ready state + * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is + * passed into the function. See the code example below for an example. + * + * @return The length, in bytes, of the message read from the message buffer, if + * any. + * + * Example use: ++// A message buffer that has already been created. +MessageBuffer_t xMessageBuffer; + +void vAnInterruptServiceRoutine( void ) +{ +uint8_t ucRxData[ 20 ]; +size_t xReceivedBytes; +BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + + // Receive the next message from the message buffer. + xReceivedBytes = xMessageBufferReceiveFromISR( xMessageBuffer, + ( void * ) ucRxData, + sizeof( ucRxData ), + &xHigherPriorityTaskWoken ); + + if( xReceivedBytes > 0 ) + { + // A ucRxData contains a message that is xReceivedBytes long. Process + // the message here.... + } + + // If xHigherPriorityTaskWoken was set to pdTRUE inside + // xMessageBufferReceiveFromISR() then a task that has a priority above the + // priority of the currently executing task was unblocked and a context + // switch should be performed to ensure the ISR returns to the unblocked + // task. In most FreeRTOS ports this is done by simply passing + // xHigherPriorityTaskWoken into portYIELD_FROM_ISR(), which will test the + // variables value, and perform the context switch if necessary. Check the + // documentation for the port in use for port specific instructions. + portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); +} ++ * \defgroup xMessageBufferReceiveFromISR xMessageBufferReceiveFromISR + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReceiveFromISR( xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) xStreamBufferReceiveFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pvRxData, xBufferLengthBytes, pxHigherPriorityTaskWoken ) + +/** + * message_buffer.h + * ++void vMessageBufferDelete( MessageBufferHandle_t xMessageBuffer ); ++ * + * Deletes a message buffer that was previously created using a call to + * xMessageBufferCreate() or xMessageBufferCreateStatic(). If the message + * buffer was created using dynamic memory (that is, by xMessageBufferCreate()), + * then the allocated memory is freed. + * + * A message buffer handle must not be used after the message buffer has been + * deleted. + * + * @param xMessageBuffer The handle of the message buffer to be deleted. + * + */ +#define vMessageBufferDelete( xMessageBuffer ) vStreamBufferDelete( ( StreamBufferHandle_t ) xMessageBuffer ) + +/** + * message_buffer.h ++BaseType_t xMessageBufferIsFull( MessageBufferHandle_t xMessageBuffer ) ); ++ * + * Tests to see if a message buffer is full. A message buffer is full if it + * cannot accept any more messages, of any size, until space is made available + * by a message being removed from the message buffer. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return If the message buffer referenced by xMessageBuffer is full then + * pdTRUE is returned. Otherwise pdFALSE is returned. + */ +#define xMessageBufferIsFull( xMessageBuffer ) xStreamBufferIsFull( ( StreamBufferHandle_t ) xMessageBuffer ) + +/** + * message_buffer.h ++BaseType_t xMessageBufferIsEmpty( MessageBufferHandle_t xMessageBuffer ) ); ++ * + * Tests to see if a message buffer is empty (does not contain any messages). + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return If the message buffer referenced by xMessageBuffer is empty then + * pdTRUE is returned. Otherwise pdFALSE is returned. + * + */ +#define xMessageBufferIsEmpty( xMessageBuffer ) xStreamBufferIsEmpty( ( StreamBufferHandle_t ) xMessageBuffer ) + +/** + * message_buffer.h ++BaseType_t xMessageBufferReset( MessageBufferHandle_t xMessageBuffer ); ++ * + * Resets a message buffer to its initial empty state, discarding any message it + * contained. + * + * A message buffer can only be reset if there are no tasks blocked on it. + * + * @param xMessageBuffer The handle of the message buffer being reset. + * + * @return If the message buffer was reset then pdPASS is returned. If the + * message buffer could not be reset because either there was a task blocked on + * the message queue to wait for space to become available, or to wait for a + * a message to be available, then pdFAIL is returned. + * + * \defgroup xMessageBufferReset xMessageBufferReset + * \ingroup MessageBufferManagement + */ +#define xMessageBufferReset( xMessageBuffer ) xStreamBufferReset( ( StreamBufferHandle_t ) xMessageBuffer ) + + +/** + * message_buffer.h ++size_t xMessageBufferSpaceAvailable( MessageBufferHandle_t xMessageBuffer ) ); ++ * Returns the number of bytes of free space in the message buffer. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return The number of bytes that can be written to the message buffer before + * the message buffer would be full. When a message is written to the message + * buffer an additional sizeof( size_t ) bytes are also written to store the + * message's length. sizeof( size_t ) is typically 4 bytes on a 32-bit + * architecture, so if xMessageBufferSpacesAvailable() returns 10, then the size + * of the largest message that can be written to the message buffer is 6 bytes. + * + * \defgroup xMessageBufferSpaceAvailable xMessageBufferSpaceAvailable + * \ingroup MessageBufferManagement + */ +#define xMessageBufferSpaceAvailable( xMessageBuffer ) xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) +#define xMessageBufferSpacesAvailable( xMessageBuffer ) xStreamBufferSpacesAvailable( ( StreamBufferHandle_t ) xMessageBuffer ) /* Corrects typo in original macro name. */ + +/** + * message_buffer.h ++ size_t xMessageBufferNextLengthBytes( MessageBufferHandle_t xMessageBuffer ) ); ++ * Returns the length (in bytes) of the next message in a message buffer. + * Useful if xMessageBufferReceive() returned 0 because the size of the buffer + * passed into xMessageBufferReceive() was too small to hold the next message. + * + * @param xMessageBuffer The handle of the message buffer being queried. + * + * @return The length (in bytes) of the next message in the message buffer, or 0 + * if the message buffer is empty. + * + * \defgroup xMessageBufferNextLengthBytes xMessageBufferNextLengthBytes + * \ingroup MessageBufferManagement + */ +#define xMessageBufferNextLengthBytes( xMessageBuffer ) xStreamBufferNextMessageLengthBytes( ( StreamBufferHandle_t ) xMessageBuffer ) PRIVILEGED_FUNCTION; + +/** + * message_buffer.h + * ++BaseType_t xMessageBufferSendCompletedFromISR( MessageBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ); ++ * + * For advanced users only. + * + * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is sent to a message buffer or stream buffer. If there was a task that + * was blocked on the message or stream buffer waiting for data to arrive then + * the sbSEND_COMPLETED() macro sends a notification to the task to remove it + * from the Blocked state. xMessageBufferSendCompletedFromISR() does the same + * thing. It is provided to enable application writers to implement their own + * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xStreamBuffer The handle of the stream buffer to which data was + * written. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xMessageBufferSendCompletedFromISR(). If calling + * xMessageBufferSendCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xMessageBufferSendCompletedFromISR xMessageBufferSendCompletedFromISR + * \ingroup StreamBufferManagement + */ +#define xMessageBufferSendCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) xStreamBufferSendCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) + +/** + * message_buffer.h + * ++BaseType_t xMessageBufferReceiveCompletedFromISR( MessageBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ); ++ * + * For advanced users only. + * + * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is read out of a message buffer or stream buffer. If there was a task + * that was blocked on the message or stream buffer waiting for data to arrive + * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to + * remove it from the Blocked state. xMessageBufferReceiveCompletedFromISR() + * does the same thing. It is provided to enable application writers to + * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT + * ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xStreamBuffer The handle of the stream buffer from which data was + * read. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xMessageBufferReceiveCompletedFromISR(). If calling + * xMessageBufferReceiveCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xMessageBufferReceiveCompletedFromISR xMessageBufferReceiveCompletedFromISR + * \ingroup StreamBufferManagement + */ +#define xMessageBufferReceiveCompletedFromISR( xMessageBuffer, pxHigherPriorityTaskWoken ) xStreamBufferReceiveCompletedFromISR( ( StreamBufferHandle_t ) xMessageBuffer, pxHigherPriorityTaskWoken ) + +#if defined( __cplusplus ) +} /* extern "C" */ +#endif + +#endif /* !defined( FREERTOS_MESSAGE_BUFFER_H ) */ diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h b/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h new file mode 100644 index 0000000..a21b7a6 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_prototypes.h @@ -0,0 +1,160 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * When the MPU is used the standard (non MPU) API functions are mapped to + * equivalents that start "MPU_", the prototypes for which are defined in this + * header files. This will cause the application code to call the MPU_ version + * which wraps the non-MPU version with privilege promoting then demoting code, + * so the kernel code always runs will full privileges. + */ + + +#ifndef MPU_PROTOTYPES_H +#define MPU_PROTOTYPES_H + +/* MPU versions of tasks.h API functions. */ +BaseType_t MPU_xTaskCreate( TaskFunction_t pxTaskCode, const char * const pcName, const uint16_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskCreateStatic( TaskFunction_t pxTaskCode, const char * const pcName, const uint32_t ulStackDepth, void * const pvParameters, UBaseType_t uxPriority, StackType_t * const puxStackBuffer, StaticTask_t * const pxTaskBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskDelete( TaskHandle_t xTaskToDelete ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskDelay( const TickType_t xTicksToDelay ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskAbortDelay( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskPriorityGet( const TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +eTaskState MPU_eTaskGetState( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSuspend( TaskHandle_t xTaskToSuspend ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskResume( TaskHandle_t xTaskToResume ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskStartScheduler( void ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSuspendAll( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskResumeAll( void ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTaskGetTickCount( void ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetNumberOfTasks( void ) FREERTOS_SYSTEM_CALL; +char * MPU_pcTaskGetName( TaskHandle_t xTaskToQuery ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetHandle( const char *pcNameToQuery ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +configSTACK_DEPTH_TYPE MPU_uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) FREERTOS_SYSTEM_CALL; +TaskHookFunction_t MPU_xTaskGetApplicationTaskTag( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) FREERTOS_SYSTEM_CALL; +void * MPU_pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetIdleTaskHandle( void ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) FREERTOS_SYSTEM_CALL; +uint32_t MPU_ulTaskGetIdleRunTimeCounter( void ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskList( char * pcWriteBuffer ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskGetRunTimeStats( char *pcWriteBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +uint32_t MPU_ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskNotifyStateClear( TaskHandle_t xTask ) FREERTOS_SYSTEM_CALL; +uint32_t MPU_ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskIncrementTick( void ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTaskGetCurrentTaskHandle( void ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) FREERTOS_SYSTEM_CALL; +void MPU_vTaskMissedYield( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskGetSchedulerState( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of queue.h API functions. */ +BaseType_t MPU_xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueMessagesWaiting( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueSpacesAvailable( const QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueDelete( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateMutex( const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xQueueGetMutexHolder( QueueHandle_t xSemaphore ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueGiveMutexRecursive( QueueHandle_t pxMutex ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcName ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueUnregisterQueue( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +const char * MPU_pcQueueGetName( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; +QueueHandle_t MPU_xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) FREERTOS_SYSTEM_CALL; +QueueSetHandle_t MPU_xQueueCreateSet( const UBaseType_t uxEventQueueLength ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) FREERTOS_SYSTEM_CALL; +QueueSetMemberHandle_t MPU_xQueueSelectFromSet( QueueSetHandle_t xQueueSet, const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) FREERTOS_SYSTEM_CALL; +void MPU_vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxQueueGetQueueNumber( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; +uint8_t MPU_ucQueueGetQueueType( QueueHandle_t xQueue ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of timers.h API functions. */ +TimerHandle_t MPU_xTimerCreate( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction ) FREERTOS_SYSTEM_CALL; +TimerHandle_t MPU_xTimerCreateStatic( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, StaticTimer_t *pxTimerBuffer ) FREERTOS_SYSTEM_CALL; +void * MPU_pvTimerGetTimerID( const TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +void MPU_vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerIsTimerActive( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TaskHandle_t MPU_xTimerGetTimerDaemonTaskHandle( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +const char * MPU_pcTimerGetName( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +void MPU_vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxTimerGetReloadMode( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTimerGetPeriod( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +TickType_t MPU_xTimerGetExpiryTime( TimerHandle_t xTimer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerCreateTimerTask( void ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of event_group.h API functions. */ +EventGroupHandle_t MPU_xEventGroupCreate( void ) FREERTOS_SYSTEM_CALL; +EventGroupHandle_t MPU_xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) FREERTOS_SYSTEM_CALL; +EventBits_t MPU_xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +void MPU_vEventGroupDelete( EventGroupHandle_t xEventGroup ) FREERTOS_SYSTEM_CALL; +UBaseType_t MPU_uxEventGroupGetNumber( void* xEventGroup ) FREERTOS_SYSTEM_CALL; + +/* MPU versions of message/stream_buffer.h API functions. */ +size_t MPU_xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, const void *pvTxData, size_t xDataLengthBytes, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, void *pvRxData, size_t xBufferLengthBytes, TickType_t xTicksToWait ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +void MPU_vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +size_t MPU_xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) FREERTOS_SYSTEM_CALL; +BaseType_t MPU_xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ) FREERTOS_SYSTEM_CALL; +StreamBufferHandle_t MPU_xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) FREERTOS_SYSTEM_CALL; +StreamBufferHandle_t MPU_xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer, uint8_t * const pucStreamBufferStorageArea, StaticStreamBuffer_t * const pxStaticStreamBuffer ) FREERTOS_SYSTEM_CALL; + + + +#endif /* MPU_PROTOTYPES_H */ + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h b/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h new file mode 100644 index 0000000..5f63d4f --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/mpu_wrappers.h @@ -0,0 +1,189 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef MPU_WRAPPERS_H +#define MPU_WRAPPERS_H + +/* This file redefines API functions to be called through a wrapper macro, but +only for ports that are using the MPU. */ +#ifdef portUSING_MPU_WRAPPERS + + /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is + included from queue.c or task.c to prevent it from having an effect within + those files. */ + #ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + + /* + * Map standard (non MPU) API functions to equivalents that start + * "MPU_". This will cause the application code to call the MPU_ + * version, which wraps the non-MPU version with privilege promoting + * then demoting code, so the kernel code always runs will full + * privileges. + */ + + /* Map standard tasks.h API functions to the MPU equivalents. */ + #define xTaskCreate MPU_xTaskCreate + #define xTaskCreateStatic MPU_xTaskCreateStatic + #define xTaskCreateRestricted MPU_xTaskCreateRestricted + #define vTaskAllocateMPURegions MPU_vTaskAllocateMPURegions + #define vTaskDelete MPU_vTaskDelete + #define vTaskDelay MPU_vTaskDelay + #define vTaskDelayUntil MPU_vTaskDelayUntil + #define xTaskAbortDelay MPU_xTaskAbortDelay + #define uxTaskPriorityGet MPU_uxTaskPriorityGet + #define eTaskGetState MPU_eTaskGetState + #define vTaskGetInfo MPU_vTaskGetInfo + #define vTaskPrioritySet MPU_vTaskPrioritySet + #define vTaskSuspend MPU_vTaskSuspend + #define vTaskResume MPU_vTaskResume + #define vTaskSuspendAll MPU_vTaskSuspendAll + #define xTaskResumeAll MPU_xTaskResumeAll + #define xTaskGetTickCount MPU_xTaskGetTickCount + #define uxTaskGetNumberOfTasks MPU_uxTaskGetNumberOfTasks + #define pcTaskGetName MPU_pcTaskGetName + #define xTaskGetHandle MPU_xTaskGetHandle + #define uxTaskGetStackHighWaterMark MPU_uxTaskGetStackHighWaterMark + #define uxTaskGetStackHighWaterMark2 MPU_uxTaskGetStackHighWaterMark2 + #define vTaskSetApplicationTaskTag MPU_vTaskSetApplicationTaskTag + #define xTaskGetApplicationTaskTag MPU_xTaskGetApplicationTaskTag + #define vTaskSetThreadLocalStoragePointer MPU_vTaskSetThreadLocalStoragePointer + #define pvTaskGetThreadLocalStoragePointer MPU_pvTaskGetThreadLocalStoragePointer + #define xTaskCallApplicationTaskHook MPU_xTaskCallApplicationTaskHook + #define xTaskGetIdleTaskHandle MPU_xTaskGetIdleTaskHandle + #define uxTaskGetSystemState MPU_uxTaskGetSystemState + #define vTaskList MPU_vTaskList + #define vTaskGetRunTimeStats MPU_vTaskGetRunTimeStats + #define ulTaskGetIdleRunTimeCounter MPU_ulTaskGetIdleRunTimeCounter + #define xTaskGenericNotify MPU_xTaskGenericNotify + #define xTaskNotifyWait MPU_xTaskNotifyWait + #define ulTaskNotifyTake MPU_ulTaskNotifyTake + #define xTaskNotifyStateClear MPU_xTaskNotifyStateClear + #define ulTaskNotifyValueClear MPU_ulTaskNotifyValueClear + #define xTaskCatchUpTicks MPU_xTaskCatchUpTicks + + #define xTaskGetCurrentTaskHandle MPU_xTaskGetCurrentTaskHandle + #define vTaskSetTimeOutState MPU_vTaskSetTimeOutState + #define xTaskCheckForTimeOut MPU_xTaskCheckForTimeOut + #define xTaskGetSchedulerState MPU_xTaskGetSchedulerState + + /* Map standard queue.h API functions to the MPU equivalents. */ + #define xQueueGenericSend MPU_xQueueGenericSend + #define xQueueReceive MPU_xQueueReceive + #define xQueuePeek MPU_xQueuePeek + #define xQueueSemaphoreTake MPU_xQueueSemaphoreTake + #define uxQueueMessagesWaiting MPU_uxQueueMessagesWaiting + #define uxQueueSpacesAvailable MPU_uxQueueSpacesAvailable + #define vQueueDelete MPU_vQueueDelete + #define xQueueCreateMutex MPU_xQueueCreateMutex + #define xQueueCreateMutexStatic MPU_xQueueCreateMutexStatic + #define xQueueCreateCountingSemaphore MPU_xQueueCreateCountingSemaphore + #define xQueueCreateCountingSemaphoreStatic MPU_xQueueCreateCountingSemaphoreStatic + #define xQueueGetMutexHolder MPU_xQueueGetMutexHolder + #define xQueueTakeMutexRecursive MPU_xQueueTakeMutexRecursive + #define xQueueGiveMutexRecursive MPU_xQueueGiveMutexRecursive + #define xQueueGenericCreate MPU_xQueueGenericCreate + #define xQueueGenericCreateStatic MPU_xQueueGenericCreateStatic + #define xQueueCreateSet MPU_xQueueCreateSet + #define xQueueAddToSet MPU_xQueueAddToSet + #define xQueueRemoveFromSet MPU_xQueueRemoveFromSet + #define xQueueSelectFromSet MPU_xQueueSelectFromSet + #define xQueueGenericReset MPU_xQueueGenericReset + + #if( configQUEUE_REGISTRY_SIZE > 0 ) + #define vQueueAddToRegistry MPU_vQueueAddToRegistry + #define vQueueUnregisterQueue MPU_vQueueUnregisterQueue + #define pcQueueGetName MPU_pcQueueGetName + #endif + + /* Map standard timer.h API functions to the MPU equivalents. */ + #define xTimerCreate MPU_xTimerCreate + #define xTimerCreateStatic MPU_xTimerCreateStatic + #define pvTimerGetTimerID MPU_pvTimerGetTimerID + #define vTimerSetTimerID MPU_vTimerSetTimerID + #define xTimerIsTimerActive MPU_xTimerIsTimerActive + #define xTimerGetTimerDaemonTaskHandle MPU_xTimerGetTimerDaemonTaskHandle + #define xTimerPendFunctionCall MPU_xTimerPendFunctionCall + #define pcTimerGetName MPU_pcTimerGetName + #define vTimerSetReloadMode MPU_vTimerSetReloadMode + #define uxTimerGetReloadMode MPU_uxTimerGetReloadMode + #define xTimerGetPeriod MPU_xTimerGetPeriod + #define xTimerGetExpiryTime MPU_xTimerGetExpiryTime + #define xTimerGenericCommand MPU_xTimerGenericCommand + + /* Map standard event_group.h API functions to the MPU equivalents. */ + #define xEventGroupCreate MPU_xEventGroupCreate + #define xEventGroupCreateStatic MPU_xEventGroupCreateStatic + #define xEventGroupWaitBits MPU_xEventGroupWaitBits + #define xEventGroupClearBits MPU_xEventGroupClearBits + #define xEventGroupSetBits MPU_xEventGroupSetBits + #define xEventGroupSync MPU_xEventGroupSync + #define vEventGroupDelete MPU_vEventGroupDelete + + /* Map standard message/stream_buffer.h API functions to the MPU + equivalents. */ + #define xStreamBufferSend MPU_xStreamBufferSend + #define xStreamBufferReceive MPU_xStreamBufferReceive + #define xStreamBufferNextMessageLengthBytes MPU_xStreamBufferNextMessageLengthBytes + #define vStreamBufferDelete MPU_vStreamBufferDelete + #define xStreamBufferIsFull MPU_xStreamBufferIsFull + #define xStreamBufferIsEmpty MPU_xStreamBufferIsEmpty + #define xStreamBufferReset MPU_xStreamBufferReset + #define xStreamBufferSpacesAvailable MPU_xStreamBufferSpacesAvailable + #define xStreamBufferBytesAvailable MPU_xStreamBufferBytesAvailable + #define xStreamBufferSetTriggerLevel MPU_xStreamBufferSetTriggerLevel + #define xStreamBufferGenericCreate MPU_xStreamBufferGenericCreate + #define xStreamBufferGenericCreateStatic MPU_xStreamBufferGenericCreateStatic + + + /* Remove the privileged function macro, but keep the PRIVILEGED_DATA + macro so applications can place data in privileged access sections + (useful when using statically allocated objects). */ + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) + #define FREERTOS_SYSTEM_CALL + + #else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + + /* Ensure API functions go in the privileged execution section. */ + #define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions"))) + #define PRIVILEGED_DATA __attribute__((section("privileged_data"))) + #define FREERTOS_SYSTEM_CALL __attribute__((section( "freertos_system_calls"))) + + #endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */ + +#else /* portUSING_MPU_WRAPPERS */ + + #define PRIVILEGED_FUNCTION + #define PRIVILEGED_DATA + #define FREERTOS_SYSTEM_CALL + #define portUSING_MPU_WRAPPERS 0 + +#endif /* portUSING_MPU_WRAPPERS */ + + +#endif /* MPU_WRAPPERS_H */ + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h b/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h new file mode 100644 index 0000000..a2099c3 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/portable.h @@ -0,0 +1,199 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/*----------------------------------------------------------- + * Portable layer API. Each function must be defined for each port. + *----------------------------------------------------------*/ + +#ifndef PORTABLE_H +#define PORTABLE_H + +/* Each FreeRTOS port has a unique portmacro.h header file. Originally a +pre-processor definition was used to ensure the pre-processor found the correct +portmacro.h file for the port being used. That scheme was deprecated in favour +of setting the compiler's include path such that it found the correct +portmacro.h file - removing the need for the constant and allowing the +portmacro.h file to be located anywhere in relation to the port being used. +Purely for reasons of backward compatibility the old method is still valid, but +to make it clear that new projects should not use it, support for the port +specific constants has been moved into the deprecated_definitions.h header +file. */ +#include "deprecated_definitions.h" + +/* If portENTER_CRITICAL is not defined then including deprecated_definitions.h +did not result in a portmacro.h header file being included - and it should be +included here. In this case the path to the correct portmacro.h header file +must be set in the compiler's include path. */ +#ifndef portENTER_CRITICAL + #include "portmacro.h" +#endif + +#if portBYTE_ALIGNMENT == 32 + #define portBYTE_ALIGNMENT_MASK ( 0x001f ) +#endif + +#if portBYTE_ALIGNMENT == 16 + #define portBYTE_ALIGNMENT_MASK ( 0x000f ) +#endif + +#if portBYTE_ALIGNMENT == 8 + #define portBYTE_ALIGNMENT_MASK ( 0x0007 ) +#endif + +#if portBYTE_ALIGNMENT == 4 + #define portBYTE_ALIGNMENT_MASK ( 0x0003 ) +#endif + +#if portBYTE_ALIGNMENT == 2 + #define portBYTE_ALIGNMENT_MASK ( 0x0001 ) +#endif + +#if portBYTE_ALIGNMENT == 1 + #define portBYTE_ALIGNMENT_MASK ( 0x0000 ) +#endif + +#ifndef portBYTE_ALIGNMENT_MASK + #error "Invalid portBYTE_ALIGNMENT definition" +#endif + +#ifndef portNUM_CONFIGURABLE_REGIONS + #define portNUM_CONFIGURABLE_REGIONS 1 +#endif + +#ifndef portHAS_STACK_OVERFLOW_CHECKING + #define portHAS_STACK_OVERFLOW_CHECKING 0 +#endif + +#ifndef portARCH_NAME + #define portARCH_NAME NULL +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#include "mpu_wrappers.h" + +/* + * Setup the stack of a new task so it is ready to be placed under the + * scheduler control. The registers have to be placed on the stack in + * the order that the port expects to find them. + * + */ +#if( portUSING_MPU_WRAPPERS == 1 ) + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #else + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION; + #endif +#else + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, StackType_t *pxEndOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; + #else + StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION; + #endif +#endif + +/* Used by heap_5.c to define the start address and size of each memory region +that together comprise the total FreeRTOS heap space. */ +typedef struct HeapRegion +{ + uint8_t *pucStartAddress; + size_t xSizeInBytes; +} HeapRegion_t; + +/* Used to pass information about the heap out of vPortGetHeapStats(). */ +typedef struct xHeapStats +{ + size_t xAvailableHeapSpaceInBytes; /* The total heap size currently available - this is the sum of all the free blocks, not the largest block that can be allocated. */ + size_t xSizeOfLargestFreeBlockInBytes; /* The maximum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xSizeOfSmallestFreeBlockInBytes; /* The minimum size, in bytes, of all the free blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xNumberOfFreeBlocks; /* The number of free memory blocks within the heap at the time vPortGetHeapStats() is called. */ + size_t xMinimumEverFreeBytesRemaining; /* The minimum amount of total free memory (sum of all free blocks) there has been in the heap since the system booted. */ + size_t xNumberOfSuccessfulAllocations; /* The number of calls to pvPortMalloc() that have returned a valid memory block. */ + size_t xNumberOfSuccessfulFrees; /* The number of calls to vPortFree() that has successfully freed a block of memory. */ +} HeapStats_t; + +/* + * Used to define multiple heap regions for use by heap_5.c. This function + * must be called before any calls to pvPortMalloc() - not creating a task, + * queue, semaphore, mutex, software timer, event group, etc. will result in + * pvPortMalloc being called. + * + * pxHeapRegions passes in an array of HeapRegion_t structures - each of which + * defines a region of memory that can be used as the heap. The array is + * terminated by a HeapRegions_t structure that has a size of 0. The region + * with the lowest start address must appear first in the array. + */ +void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions ) PRIVILEGED_FUNCTION; + +/* + * Returns a HeapStats_t structure filled with information about the current + * heap state. + */ +void vPortGetHeapStats( HeapStats_t *pxHeapStats ); + +/* + * Map to the memory management routines required for the port. + */ +void *pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION; +void vPortFree( void *pv ) PRIVILEGED_FUNCTION; +void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION; +size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION; +size_t xPortGetMinimumEverFreeHeapSize( void ) PRIVILEGED_FUNCTION; + +/* + * Setup the hardware ready for the scheduler to take control. This generally + * sets up a tick interrupt and sets timers for the correct tick frequency. + */ +BaseType_t xPortStartScheduler( void ) PRIVILEGED_FUNCTION; + +/* + * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so + * the hardware is left in its original condition after the scheduler stops + * executing. + */ +void vPortEndScheduler( void ) PRIVILEGED_FUNCTION; + +/* + * The structures and methods of manipulating the MPU are contained within the + * port layer. + * + * Fills the xMPUSettings structure with the memory region information + * contained in xRegions. + */ +#if( portUSING_MPU_WRAPPERS == 1 ) + struct xMEMORY_REGION; + void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, StackType_t *pxBottomOfStack, uint32_t ulStackDepth ) PRIVILEGED_FUNCTION; +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* PORTABLE_H */ + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h b/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h new file mode 100644 index 0000000..0d95130 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/projdefs.h @@ -0,0 +1,124 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef PROJDEFS_H +#define PROJDEFS_H + +/* + * Defines the prototype to which task functions must conform. Defined in this + * file to ensure the type is known before portable.h is included. + */ +typedef void (*TaskFunction_t)( void * ); + +/* Converts a time in milliseconds to a time in ticks. This macro can be +overridden by a macro of the same name defined in FreeRTOSConfig.h in case the +definition here is not suitable for your application. */ +#ifndef pdMS_TO_TICKS + #define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) ) +#endif + +#define pdFALSE ( ( BaseType_t ) 0 ) +#define pdTRUE ( ( BaseType_t ) 1 ) + +#define pdPASS ( pdTRUE ) +#define pdFAIL ( pdFALSE ) +#define errQUEUE_EMPTY ( ( BaseType_t ) 0 ) +#define errQUEUE_FULL ( ( BaseType_t ) 0 ) + +/* FreeRTOS error definitions. */ +#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ( -1 ) +#define errQUEUE_BLOCKED ( -4 ) +#define errQUEUE_YIELD ( -5 ) + +/* Macros used for basic data corruption checks. */ +#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES + #define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0 +#endif + +#if( configUSE_16_BIT_TICKS == 1 ) + #define pdINTEGRITY_CHECK_VALUE 0x5a5a +#else + #define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL +#endif + +/* The following errno values are used by FreeRTOS+ components, not FreeRTOS +itself. */ +#define pdFREERTOS_ERRNO_NONE 0 /* No errors */ +#define pdFREERTOS_ERRNO_ENOENT 2 /* No such file or directory */ +#define pdFREERTOS_ERRNO_EINTR 4 /* Interrupted system call */ +#define pdFREERTOS_ERRNO_EIO 5 /* I/O error */ +#define pdFREERTOS_ERRNO_ENXIO 6 /* No such device or address */ +#define pdFREERTOS_ERRNO_EBADF 9 /* Bad file number */ +#define pdFREERTOS_ERRNO_EAGAIN 11 /* No more processes */ +#define pdFREERTOS_ERRNO_EWOULDBLOCK 11 /* Operation would block */ +#define pdFREERTOS_ERRNO_ENOMEM 12 /* Not enough memory */ +#define pdFREERTOS_ERRNO_EACCES 13 /* Permission denied */ +#define pdFREERTOS_ERRNO_EFAULT 14 /* Bad address */ +#define pdFREERTOS_ERRNO_EBUSY 16 /* Mount device busy */ +#define pdFREERTOS_ERRNO_EEXIST 17 /* File exists */ +#define pdFREERTOS_ERRNO_EXDEV 18 /* Cross-device link */ +#define pdFREERTOS_ERRNO_ENODEV 19 /* No such device */ +#define pdFREERTOS_ERRNO_ENOTDIR 20 /* Not a directory */ +#define pdFREERTOS_ERRNO_EISDIR 21 /* Is a directory */ +#define pdFREERTOS_ERRNO_EINVAL 22 /* Invalid argument */ +#define pdFREERTOS_ERRNO_ENOSPC 28 /* No space left on device */ +#define pdFREERTOS_ERRNO_ESPIPE 29 /* Illegal seek */ +#define pdFREERTOS_ERRNO_EROFS 30 /* Read only file system */ +#define pdFREERTOS_ERRNO_EUNATCH 42 /* Protocol driver not attached */ +#define pdFREERTOS_ERRNO_EBADE 50 /* Invalid exchange */ +#define pdFREERTOS_ERRNO_EFTYPE 79 /* Inappropriate file type or format */ +#define pdFREERTOS_ERRNO_ENMFILE 89 /* No more files */ +#define pdFREERTOS_ERRNO_ENOTEMPTY 90 /* Directory not empty */ +#define pdFREERTOS_ERRNO_ENAMETOOLONG 91 /* File or path name too long */ +#define pdFREERTOS_ERRNO_EOPNOTSUPP 95 /* Operation not supported on transport endpoint */ +#define pdFREERTOS_ERRNO_ENOBUFS 105 /* No buffer space available */ +#define pdFREERTOS_ERRNO_ENOPROTOOPT 109 /* Protocol not available */ +#define pdFREERTOS_ERRNO_EADDRINUSE 112 /* Address already in use */ +#define pdFREERTOS_ERRNO_ETIMEDOUT 116 /* Connection timed out */ +#define pdFREERTOS_ERRNO_EINPROGRESS 119 /* Connection already in progress */ +#define pdFREERTOS_ERRNO_EALREADY 120 /* Socket already connected */ +#define pdFREERTOS_ERRNO_EADDRNOTAVAIL 125 /* Address not available */ +#define pdFREERTOS_ERRNO_EISCONN 127 /* Socket is already connected */ +#define pdFREERTOS_ERRNO_ENOTCONN 128 /* Socket is not connected */ +#define pdFREERTOS_ERRNO_ENOMEDIUM 135 /* No medium inserted */ +#define pdFREERTOS_ERRNO_EILSEQ 138 /* An invalid UTF-16 sequence was encountered. */ +#define pdFREERTOS_ERRNO_ECANCELED 140 /* Operation canceled. */ + +/* The following endian values are used by FreeRTOS+ components, not FreeRTOS +itself. */ +#define pdFREERTOS_LITTLE_ENDIAN 0 +#define pdFREERTOS_BIG_ENDIAN 1 + +/* Re-defining endian values for generic naming. */ +#define pdLITTLE_ENDIAN pdFREERTOS_LITTLE_ENDIAN +#define pdBIG_ENDIAN pdFREERTOS_BIG_ENDIAN + + +#endif /* PROJDEFS_H */ + + + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h b/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h new file mode 100644 index 0000000..52ccca5 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/queue.h @@ -0,0 +1,1655 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +#ifndef QUEUE_H +#define QUEUE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include queue.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +#include "task.h" + +/** + * Type by which queues are referenced. For example, a call to xQueueCreate() + * returns an QueueHandle_t variable that can then be used as a parameter to + * xQueueSend(), xQueueReceive(), etc. + */ +struct QueueDefinition; /* Using old naming convention so as not to break kernel aware debuggers. */ +typedef struct QueueDefinition * QueueHandle_t; + +/** + * Type by which queue sets are referenced. For example, a call to + * xQueueCreateSet() returns an xQueueSet variable that can then be used as a + * parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc. + */ +typedef struct QueueDefinition * QueueSetHandle_t; + +/** + * Queue sets can contain both queues and semaphores, so the + * QueueSetMemberHandle_t is defined as a type to be used where a parameter or + * return value can be either an QueueHandle_t or an SemaphoreHandle_t. + */ +typedef struct QueueDefinition * QueueSetMemberHandle_t; + +/* For internal use only. */ +#define queueSEND_TO_BACK ( ( BaseType_t ) 0 ) +#define queueSEND_TO_FRONT ( ( BaseType_t ) 1 ) +#define queueOVERWRITE ( ( BaseType_t ) 2 ) + +/* For internal use only. These definitions *must* match those in queue.c. */ +#define queueQUEUE_TYPE_BASE ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_SET ( ( uint8_t ) 0U ) +#define queueQUEUE_TYPE_MUTEX ( ( uint8_t ) 1U ) +#define queueQUEUE_TYPE_COUNTING_SEMAPHORE ( ( uint8_t ) 2U ) +#define queueQUEUE_TYPE_BINARY_SEMAPHORE ( ( uint8_t ) 3U ) +#define queueQUEUE_TYPE_RECURSIVE_MUTEX ( ( uint8_t ) 4U ) + +/** + * queue. h + *+ QueueHandle_t xQueueCreate( + UBaseType_t uxQueueLength, + UBaseType_t uxItemSize + ); + *+ * + * Creates a new queue instance, and returns a handle by which the new queue + * can be referenced. + * + * Internally, within the FreeRTOS implementation, queues use two blocks of + * memory. The first block is used to hold the queue's data structures. The + * second block is used to hold items placed into the queue. If a queue is + * created using xQueueCreate() then both blocks of memory are automatically + * dynamically allocated inside the xQueueCreate() function. (see + * http://www.freertos.org/a00111.html). If a queue is created using + * xQueueCreateStatic() then the application writer must provide the memory that + * will get used by the queue. xQueueCreateStatic() therefore allows a queue to + * be created without using any dynamic memory allocation. + * + * http://www.FreeRTOS.org/Embedded-RTOS-Queues.html + * + * @param uxQueueLength The maximum number of items that the queue can contain. + * + * @param uxItemSize The number of bytes each item in the queue will require. + * Items are queued by copy, not by reference, so this is the number of bytes + * that will be copied for each posted item. Each item on the queue must be + * the same size. + * + * @return If the queue is successfully create then a handle to the newly + * created queue is returned. If the queue cannot be created then 0 is + * returned. + * + * Example usage: ++ struct AMessage + { + char ucMessageID; + char ucData[ 20 ]; + }; + + void vATask( void *pvParameters ) + { + QueueHandle_t xQueue1, xQueue2; + + // Create a queue capable of containing 10 uint32_t values. + xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + if( xQueue1 == 0 ) + { + // Queue was not created and must not be used. + } + + // Create a queue capable of containing 10 pointers to AMessage structures. + // These should be passed by pointer as they contain a lot of data. + xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + if( xQueue2 == 0 ) + { + // Queue was not created and must not be used. + } + + // ... Rest of task code. + } ++ * \defgroup xQueueCreate xQueueCreate + * \ingroup QueueManagement + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( ( uxQueueLength ), ( uxItemSize ), ( queueQUEUE_TYPE_BASE ) ) +#endif + +/** + * queue. h + *+ QueueHandle_t xQueueCreateStatic( + UBaseType_t uxQueueLength, + UBaseType_t uxItemSize, + uint8_t *pucQueueStorageBuffer, + StaticQueue_t *pxQueueBuffer + ); + *+ * + * Creates a new queue instance, and returns a handle by which the new queue + * can be referenced. + * + * Internally, within the FreeRTOS implementation, queues use two blocks of + * memory. The first block is used to hold the queue's data structures. The + * second block is used to hold items placed into the queue. If a queue is + * created using xQueueCreate() then both blocks of memory are automatically + * dynamically allocated inside the xQueueCreate() function. (see + * http://www.freertos.org/a00111.html). If a queue is created using + * xQueueCreateStatic() then the application writer must provide the memory that + * will get used by the queue. xQueueCreateStatic() therefore allows a queue to + * be created without using any dynamic memory allocation. + * + * http://www.FreeRTOS.org/Embedded-RTOS-Queues.html + * + * @param uxQueueLength The maximum number of items that the queue can contain. + * + * @param uxItemSize The number of bytes each item in the queue will require. + * Items are queued by copy, not by reference, so this is the number of bytes + * that will be copied for each posted item. Each item on the queue must be + * the same size. + * + * @param pucQueueStorageBuffer If uxItemSize is not zero then + * pucQueueStorageBuffer must point to a uint8_t array that is at least large + * enough to hold the maximum number of items that can be in the queue at any + * one time - which is ( uxQueueLength * uxItemsSize ) bytes. If uxItemSize is + * zero then pucQueueStorageBuffer can be NULL. + * + * @param pxQueueBuffer Must point to a variable of type StaticQueue_t, which + * will be used to hold the queue's data structure. + * + * @return If the queue is created then a handle to the created queue is + * returned. If pxQueueBuffer is NULL then NULL is returned. + * + * Example usage: ++ struct AMessage + { + char ucMessageID; + char ucData[ 20 ]; + }; + + #define QUEUE_LENGTH 10 + #define ITEM_SIZE sizeof( uint32_t ) + + // xQueueBuffer will hold the queue structure. + StaticQueue_t xQueueBuffer; + + // ucQueueStorage will hold the items posted to the queue. Must be at least + // [(queue length) * ( queue item size)] bytes long. + uint8_t ucQueueStorage[ QUEUE_LENGTH * ITEM_SIZE ]; + + void vATask( void *pvParameters ) + { + QueueHandle_t xQueue1; + + // Create a queue capable of containing 10 uint32_t values. + xQueue1 = xQueueCreate( QUEUE_LENGTH, // The number of items the queue can hold. + ITEM_SIZE // The size of each item in the queue + &( ucQueueStorage[ 0 ] ), // The buffer that will hold the items in the queue. + &xQueueBuffer ); // The buffer that will hold the queue structure. + + // The queue is guaranteed to be created successfully as no dynamic memory + // allocation is used. Therefore xQueue1 is now a handle to a valid queue. + + // ... Rest of task code. + } ++ * \defgroup xQueueCreateStatic xQueueCreateStatic + * \ingroup QueueManagement + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xQueueCreateStatic( uxQueueLength, uxItemSize, pucQueueStorage, pxQueueBuffer ) xQueueGenericCreateStatic( ( uxQueueLength ), ( uxItemSize ), ( pucQueueStorage ), ( pxQueueBuffer ), ( queueQUEUE_TYPE_BASE ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * queue. h + *+ BaseType_t xQueueSendToToFront( + QueueHandle_t xQueue, + const void *pvItemToQueue, + TickType_t xTicksToWait + ); + *+ * + * Post an item to the front of a queue. The item is queued by copy, not by + * reference. This function must not be called from an interrupt service + * routine. See xQueueSendFromISR () for an alternative which may be used + * in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the + * queue is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: ++ struct AMessage + { + char ucMessageID; + char ucData[ 20 ]; + } xMessage; + + uint32_t ulVar = 10UL; + + void vATask( void *pvParameters ) + { + QueueHandle_t xQueue1, xQueue2; + struct AMessage *pxMessage; + + // Create a queue capable of containing 10 uint32_t values. + xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + + // Create a queue capable of containing 10 pointers to AMessage structures. + // These should be passed by pointer as they contain a lot of data. + xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + + // ... + + if( xQueue1 != 0 ) + { + // Send an uint32_t. Wait for 10 ticks for space to become + // available if necessary. + if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) + { + // Failed to post the message, even after 10 ticks. + } + } + + if( xQueue2 != 0 ) + { + // Send a pointer to a struct AMessage object. Don't block if the + // queue is already full. + pxMessage = & xMessage; + xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); + } + + // ... Rest of task code. + } ++ * \defgroup xQueueSend xQueueSend + * \ingroup QueueManagement + */ +#define xQueueSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT ) + +/** + * queue. h + *+ BaseType_t xQueueSendToBack( + QueueHandle_t xQueue, + const void *pvItemToQueue, + TickType_t xTicksToWait + ); + *+ * + * This is a macro that calls xQueueGenericSend(). + * + * Post an item to the back of a queue. The item is queued by copy, not by + * reference. This function must not be called from an interrupt service + * routine. See xQueueSendFromISR () for an alternative which may be used + * in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the queue + * is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: ++ struct AMessage + { + char ucMessageID; + char ucData[ 20 ]; + } xMessage; + + uint32_t ulVar = 10UL; + + void vATask( void *pvParameters ) + { + QueueHandle_t xQueue1, xQueue2; + struct AMessage *pxMessage; + + // Create a queue capable of containing 10 uint32_t values. + xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + + // Create a queue capable of containing 10 pointers to AMessage structures. + // These should be passed by pointer as they contain a lot of data. + xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + + // ... + + if( xQueue1 != 0 ) + { + // Send an uint32_t. Wait for 10 ticks for space to become + // available if necessary. + if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) + { + // Failed to post the message, even after 10 ticks. + } + } + + if( xQueue2 != 0 ) + { + // Send a pointer to a struct AMessage object. Don't block if the + // queue is already full. + pxMessage = & xMessage; + xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); + } + + // ... Rest of task code. + } ++ * \defgroup xQueueSend xQueueSend + * \ingroup QueueManagement + */ +#define xQueueSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK ) + +/** + * queue. h + *+ BaseType_t xQueueSend( + QueueHandle_t xQueue, + const void * pvItemToQueue, + TickType_t xTicksToWait + ); + *+ * + * This is a macro that calls xQueueGenericSend(). It is included for + * backward compatibility with versions of FreeRTOS.org that did not + * include the xQueueSendToFront() and xQueueSendToBack() macros. It is + * equivalent to xQueueSendToBack(). + * + * Post an item on a queue. The item is queued by copy, not by reference. + * This function must not be called from an interrupt service routine. + * See xQueueSendFromISR () for an alternative which may be used in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the + * queue is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: ++ struct AMessage + { + char ucMessageID; + char ucData[ 20 ]; + } xMessage; + + uint32_t ulVar = 10UL; + + void vATask( void *pvParameters ) + { + QueueHandle_t xQueue1, xQueue2; + struct AMessage *pxMessage; + + // Create a queue capable of containing 10 uint32_t values. + xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + + // Create a queue capable of containing 10 pointers to AMessage structures. + // These should be passed by pointer as they contain a lot of data. + xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + + // ... + + if( xQueue1 != 0 ) + { + // Send an uint32_t. Wait for 10 ticks for space to become + // available if necessary. + if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS ) + { + // Failed to post the message, even after 10 ticks. + } + } + + if( xQueue2 != 0 ) + { + // Send a pointer to a struct AMessage object. Don't block if the + // queue is already full. + pxMessage = & xMessage; + xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 ); + } + + // ... Rest of task code. + } ++ * \defgroup xQueueSend xQueueSend + * \ingroup QueueManagement + */ +#define xQueueSend( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK ) + +/** + * queue. h + *+ BaseType_t xQueueOverwrite( + QueueHandle_t xQueue, + const void * pvItemToQueue + ); + *+ * + * Only for use with queues that have a length of one - so the queue is either + * empty or full. + * + * Post an item on a queue. If the queue is already full then overwrite the + * value held in the queue. The item is queued by copy, not by reference. + * + * This function must not be called from an interrupt service routine. + * See xQueueOverwriteFromISR () for an alternative which may be used in an ISR. + * + * @param xQueue The handle of the queue to which the data is being sent. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @return xQueueOverwrite() is a macro that calls xQueueGenericSend(), and + * therefore has the same return values as xQueueSendToFront(). However, pdPASS + * is the only value that can be returned because xQueueOverwrite() will write + * to the queue even when the queue is already full. + * + * Example usage: ++ + void vFunction( void *pvParameters ) + { + QueueHandle_t xQueue; + uint32_t ulVarToSend, ulValReceived; + + // Create a queue to hold one uint32_t value. It is strongly + // recommended *not* to use xQueueOverwrite() on queues that can + // contain more than one value, and doing so will trigger an assertion + // if configASSERT() is defined. + xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); + + // Write the value 10 to the queue using xQueueOverwrite(). + ulVarToSend = 10; + xQueueOverwrite( xQueue, &ulVarToSend ); + + // Peeking the queue should now return 10, but leave the value 10 in + // the queue. A block time of zero is used as it is known that the + // queue holds a value. + ulValReceived = 0; + xQueuePeek( xQueue, &ulValReceived, 0 ); + + if( ulValReceived != 10 ) + { + // Error unless the item was removed by a different task. + } + + // The queue is still full. Use xQueueOverwrite() to overwrite the + // value held in the queue with 100. + ulVarToSend = 100; + xQueueOverwrite( xQueue, &ulVarToSend ); + + // This time read from the queue, leaving the queue empty once more. + // A block time of 0 is used again. + xQueueReceive( xQueue, &ulValReceived, 0 ); + + // The value read should be the last value written, even though the + // queue was already full when the value was written. + if( ulValReceived != 100 ) + { + // Error! + } + + // ... +} ++ * \defgroup xQueueOverwrite xQueueOverwrite + * \ingroup QueueManagement + */ +#define xQueueOverwrite( xQueue, pvItemToQueue ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), 0, queueOVERWRITE ) + + +/** + * queue. h + *+ BaseType_t xQueueGenericSend( + QueueHandle_t xQueue, + const void * pvItemToQueue, + TickType_t xTicksToWait + BaseType_t xCopyPosition + ); + *+ * + * It is preferred that the macros xQueueSend(), xQueueSendToFront() and + * xQueueSendToBack() are used in place of calling this function directly. + * + * Post an item on a queue. The item is queued by copy, not by reference. + * This function must not be called from an interrupt service routine. + * See xQueueSendFromISR () for an alternative which may be used in an ISR. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for space to become available on the queue, should it already + * be full. The call will return immediately if this is set to 0 and the + * queue is full. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * + * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the + * item at the back of the queue, or queueSEND_TO_FRONT to place the item + * at the front of the queue (for high priority messages). + * + * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL. + * + * Example usage: ++ struct AMessage + { + char ucMessageID; + char ucData[ 20 ]; + } xMessage; + + uint32_t ulVar = 10UL; + + void vATask( void *pvParameters ) + { + QueueHandle_t xQueue1, xQueue2; + struct AMessage *pxMessage; + + // Create a queue capable of containing 10 uint32_t values. + xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) ); + + // Create a queue capable of containing 10 pointers to AMessage structures. + // These should be passed by pointer as they contain a lot of data. + xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) ); + + // ... + + if( xQueue1 != 0 ) + { + // Send an uint32_t. Wait for 10 ticks for space to become + // available if necessary. + if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS ) + { + // Failed to post the message, even after 10 ticks. + } + } + + if( xQueue2 != 0 ) + { + // Send a pointer to a struct AMessage object. Don't block if the + // queue is already full. + pxMessage = & xMessage; + xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK ); + } + + // ... Rest of task code. + } ++ * \defgroup xQueueSend xQueueSend + * \ingroup QueueManagement + */ +BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; + +/** + * queue. h + *+ BaseType_t xQueuePeek( + QueueHandle_t xQueue, + void * const pvBuffer, + TickType_t xTicksToWait + );+ * + * Receive an item from a queue without removing the item from the queue. + * The item is received by copy so a buffer of adequate size must be + * provided. The number of bytes copied into the buffer was defined when + * the queue was created. + * + * Successfully received items remain on the queue so will be returned again + * by the next call, or a call to xQueueReceive(). + * + * This macro must not be used in an interrupt service routine. See + * xQueuePeekFromISR() for an alternative that can be called from an interrupt + * service routine. + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for an item to receive should the queue be empty at the time + * of the call. The time is defined in tick periods so the constant + * portTICK_PERIOD_MS should be used to convert to real time if this is required. + * xQueuePeek() will return immediately if xTicksToWait is 0 and the queue + * is empty. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * Example usage: ++ struct AMessage + { + char ucMessageID; + char ucData[ 20 ]; + } xMessage; + + QueueHandle_t xQueue; + + // Task to create a queue and post a value. + void vATask( void *pvParameters ) + { + struct AMessage *pxMessage; + + // Create a queue capable of containing 10 pointers to AMessage structures. + // These should be passed by pointer as they contain a lot of data. + xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); + if( xQueue == 0 ) + { + // Failed to create the queue. + } + + // ... + + // Send a pointer to a struct AMessage object. Don't block if the + // queue is already full. + pxMessage = & xMessage; + xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); + + // ... Rest of task code. + } + + // Task to peek the data from the queue. + void vADifferentTask( void *pvParameters ) + { + struct AMessage *pxRxedMessage; + + if( xQueue != 0 ) + { + // Peek a message on the created queue. Block for 10 ticks if a + // message is not immediately available. + if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) + { + // pcRxedMessage now points to the struct AMessage variable posted + // by vATask, but the item still remains on the queue. + } + } + + // ... Rest of task code. + } ++ * \defgroup xQueuePeek xQueuePeek + * \ingroup QueueManagement + */ +BaseType_t xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * queue. h + *+ BaseType_t xQueuePeekFromISR( + QueueHandle_t xQueue, + void *pvBuffer, + );+ * + * A version of xQueuePeek() that can be called from an interrupt service + * routine (ISR). + * + * Receive an item from a queue without removing the item from the queue. + * The item is received by copy so a buffer of adequate size must be + * provided. The number of bytes copied into the buffer was defined when + * the queue was created. + * + * Successfully received items remain on the queue so will be returned again + * by the next call, or a call to xQueueReceive(). + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * \defgroup xQueuePeekFromISR xQueuePeekFromISR + * \ingroup QueueManagement + */ +BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION; + +/** + * queue. h + *+ BaseType_t xQueueReceive( + QueueHandle_t xQueue, + void *pvBuffer, + TickType_t xTicksToWait + );+ * + * Receive an item from a queue. The item is received by copy so a buffer of + * adequate size must be provided. The number of bytes copied into the buffer + * was defined when the queue was created. + * + * Successfully received items are removed from the queue. + * + * This function must not be used in an interrupt service routine. See + * xQueueReceiveFromISR for an alternative that can. + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @param xTicksToWait The maximum amount of time the task should block + * waiting for an item to receive should the queue be empty at the time + * of the call. xQueueReceive() will return immediately if xTicksToWait + * is zero and the queue is empty. The time is defined in tick periods so the + * constant portTICK_PERIOD_MS should be used to convert to real time if this is + * required. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * Example usage: ++ struct AMessage + { + char ucMessageID; + char ucData[ 20 ]; + } xMessage; + + QueueHandle_t xQueue; + + // Task to create a queue and post a value. + void vATask( void *pvParameters ) + { + struct AMessage *pxMessage; + + // Create a queue capable of containing 10 pointers to AMessage structures. + // These should be passed by pointer as they contain a lot of data. + xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) ); + if( xQueue == 0 ) + { + // Failed to create the queue. + } + + // ... + + // Send a pointer to a struct AMessage object. Don't block if the + // queue is already full. + pxMessage = & xMessage; + xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 ); + + // ... Rest of task code. + } + + // Task to receive from the queue. + void vADifferentTask( void *pvParameters ) + { + struct AMessage *pxRxedMessage; + + if( xQueue != 0 ) + { + // Receive a message on the created queue. Block for 10 ticks if a + // message is not immediately available. + if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) ) + { + // pcRxedMessage now points to the struct AMessage variable posted + // by vATask. + } + } + + // ... Rest of task code. + } ++ * \defgroup xQueueReceive xQueueReceive + * \ingroup QueueManagement + */ +BaseType_t xQueueReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * queue. h + *UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue );+ * + * Return the number of messages stored in a queue. + * + * @param xQueue A handle to the queue being queried. + * + * @return The number of messages available in the queue. + * + * \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting + * \ingroup QueueManagement + */ +UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** + * queue. h + *UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue );+ * + * Return the number of free spaces available in a queue. This is equal to the + * number of items that can be sent to the queue before the queue becomes full + * if no items are removed. + * + * @param xQueue A handle to the queue being queried. + * + * @return The number of spaces available in the queue. + * + * \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting + * \ingroup QueueManagement + */ +UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** + * queue. h + *void vQueueDelete( QueueHandle_t xQueue );+ * + * Delete a queue - freeing all the memory allocated for storing of items + * placed on the queue. + * + * @param xQueue A handle to the queue to be deleted. + * + * \defgroup vQueueDelete vQueueDelete + * \ingroup QueueManagement + */ +void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/** + * queue. h + *+ BaseType_t xQueueSendToFrontFromISR( + QueueHandle_t xQueue, + const void *pvItemToQueue, + BaseType_t *pxHigherPriorityTaskWoken + ); ++ * + * This is a macro that calls xQueueGenericSendFromISR(). + * + * Post an item to the front of a queue. It is safe to use this macro from + * within an interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueSendToFrontFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueSendToFromFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): ++ void vBufferISR( void ) + { + char cIn; + BaseType_t xHigherPrioritTaskWoken; + + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWoken = pdFALSE; + + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + + // Post the byte. + xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + + } while( portINPUT_BYTE( BUFFER_COUNT ) ); + + // Now the buffer is empty we can switch context if necessary. + if( xHigherPriorityTaskWoken ) + { + taskYIELD (); + } + } ++ * + * \defgroup xQueueSendFromISR xQueueSendFromISR + * \ingroup QueueManagement + */ +#define xQueueSendToFrontFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_FRONT ) + + +/** + * queue. h + *+ BaseType_t xQueueSendToBackFromISR( + QueueHandle_t xQueue, + const void *pvItemToQueue, + BaseType_t *pxHigherPriorityTaskWoken + ); ++ * + * This is a macro that calls xQueueGenericSendFromISR(). + * + * Post an item to the back of a queue. It is safe to use this macro from + * within an interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueSendToBackFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): ++ void vBufferISR( void ) + { + char cIn; + BaseType_t xHigherPriorityTaskWoken; + + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWoken = pdFALSE; + + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + + // Post the byte. + xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + + } while( portINPUT_BYTE( BUFFER_COUNT ) ); + + // Now the buffer is empty we can switch context if necessary. + if( xHigherPriorityTaskWoken ) + { + taskYIELD (); + } + } ++ * + * \defgroup xQueueSendFromISR xQueueSendFromISR + * \ingroup QueueManagement + */ +#define xQueueSendToBackFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) + +/** + * queue. h + *+ BaseType_t xQueueOverwriteFromISR( + QueueHandle_t xQueue, + const void * pvItemToQueue, + BaseType_t *pxHigherPriorityTaskWoken + ); + *+ * + * A version of xQueueOverwrite() that can be used in an interrupt service + * routine (ISR). + * + * Only for use with queues that can hold a single item - so the queue is either + * empty or full. + * + * Post an item on a queue. If the queue is already full then overwrite the + * value held in the queue. The item is queued by copy, not by reference. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueOverwriteFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueOverwriteFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return xQueueOverwriteFromISR() is a macro that calls + * xQueueGenericSendFromISR(), and therefore has the same return values as + * xQueueSendToFrontFromISR(). However, pdPASS is the only value that can be + * returned because xQueueOverwriteFromISR() will write to the queue even when + * the queue is already full. + * + * Example usage: ++ + QueueHandle_t xQueue; + + void vFunction( void *pvParameters ) + { + // Create a queue to hold one uint32_t value. It is strongly + // recommended *not* to use xQueueOverwriteFromISR() on queues that can + // contain more than one value, and doing so will trigger an assertion + // if configASSERT() is defined. + xQueue = xQueueCreate( 1, sizeof( uint32_t ) ); +} + +void vAnInterruptHandler( void ) +{ +// xHigherPriorityTaskWoken must be set to pdFALSE before it is used. +BaseType_t xHigherPriorityTaskWoken = pdFALSE; +uint32_t ulVarToSend, ulValReceived; + + // Write the value 10 to the queue using xQueueOverwriteFromISR(). + ulVarToSend = 10; + xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + + // The queue is full, but calling xQueueOverwriteFromISR() again will still + // pass because the value held in the queue will be overwritten with the + // new value. + ulVarToSend = 100; + xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken ); + + // Reading from the queue will now return 100. + + // ... + + if( xHigherPrioritytaskWoken == pdTRUE ) + { + // Writing to the queue caused a task to unblock and the unblocked task + // has a priority higher than or equal to the priority of the currently + // executing task (the task this interrupt interrupted). Perform a context + // switch so this interrupt returns directly to the unblocked task. + portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port. + } +} ++ * \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR + * \ingroup QueueManagement + */ +#define xQueueOverwriteFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueOVERWRITE ) + +/** + * queue. h + *+ BaseType_t xQueueSendFromISR( + QueueHandle_t xQueue, + const void *pvItemToQueue, + BaseType_t *pxHigherPriorityTaskWoken + ); ++ * + * This is a macro that calls xQueueGenericSendFromISR(). It is included + * for backward compatibility with versions of FreeRTOS.org that did not + * include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR() + * macros. + * + * Post an item to the back of a queue. It is safe to use this function from + * within an interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueSendFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueSendFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): ++ void vBufferISR( void ) + { + char cIn; + BaseType_t xHigherPriorityTaskWoken; + + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWoken = pdFALSE; + + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + + // Post the byte. + xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken ); + + } while( portINPUT_BYTE( BUFFER_COUNT ) ); + + // Now the buffer is empty we can switch context if necessary. + if( xHigherPriorityTaskWoken ) + { + // Actual macro used here is port specific. + portYIELD_FROM_ISR (); + } + } ++ * + * \defgroup xQueueSendFromISR xQueueSendFromISR + * \ingroup QueueManagement + */ +#define xQueueSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK ) + +/** + * queue. h + *+ BaseType_t xQueueGenericSendFromISR( + QueueHandle_t xQueue, + const void *pvItemToQueue, + BaseType_t *pxHigherPriorityTaskWoken, + BaseType_t xCopyPosition + ); ++ * + * It is preferred that the macros xQueueSendFromISR(), + * xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place + * of calling this function directly. xQueueGiveFromISR() is an + * equivalent for use by semaphores that don't actually copy any data. + * + * Post an item on a queue. It is safe to use this function from within an + * interrupt service routine. + * + * Items are queued by copy not reference so it is preferable to only + * queue small items, especially when called from an ISR. In most cases + * it would be preferable to store a pointer to the item being queued. + * + * @param xQueue The handle to the queue on which the item is to be posted. + * + * @param pvItemToQueue A pointer to the item that is to be placed on the + * queue. The size of the items the queue will hold was defined when the + * queue was created, so this many bytes will be copied from pvItemToQueue + * into the queue storage area. + * + * @param pxHigherPriorityTaskWoken xQueueGenericSendFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xQueueGenericSendFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the + * item at the back of the queue, or queueSEND_TO_FRONT to place the item + * at the front of the queue (for high priority messages). + * + * @return pdTRUE if the data was successfully sent to the queue, otherwise + * errQUEUE_FULL. + * + * Example usage for buffered IO (where the ISR can obtain more than one value + * per call): ++ void vBufferISR( void ) + { + char cIn; + BaseType_t xHigherPriorityTaskWokenByPost; + + // We have not woken a task at the start of the ISR. + xHigherPriorityTaskWokenByPost = pdFALSE; + + // Loop until the buffer is empty. + do + { + // Obtain a byte from the buffer. + cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS ); + + // Post each byte. + xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK ); + + } while( portINPUT_BYTE( BUFFER_COUNT ) ); + + // Now the buffer is empty we can switch context if necessary. Note that the + // name of the yield function required is port specific. + if( xHigherPriorityTaskWokenByPost ) + { + portYIELD_FROM_ISR(); + } + } ++ * + * \defgroup xQueueSendFromISR xQueueSendFromISR + * \ingroup QueueManagement + */ +BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, const void * const pvItemToQueue, BaseType_t * const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * queue. h + *+ BaseType_t xQueueReceiveFromISR( + QueueHandle_t xQueue, + void *pvBuffer, + BaseType_t *pxTaskWoken + ); + *+ * + * Receive an item from a queue. It is safe to use this function from within an + * interrupt service routine. + * + * @param xQueue The handle to the queue from which the item is to be + * received. + * + * @param pvBuffer Pointer to the buffer into which the received item will + * be copied. + * + * @param pxTaskWoken A task may be blocked waiting for space to become + * available on the queue. If xQueueReceiveFromISR causes such a task to + * unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will + * remain unchanged. + * + * @return pdTRUE if an item was successfully received from the queue, + * otherwise pdFALSE. + * + * Example usage: ++ + QueueHandle_t xQueue; + + // Function to create a queue and post some values. + void vAFunction( void *pvParameters ) + { + char cValueToPost; + const TickType_t xTicksToWait = ( TickType_t )0xff; + + // Create a queue capable of containing 10 characters. + xQueue = xQueueCreate( 10, sizeof( char ) ); + if( xQueue == 0 ) + { + // Failed to create the queue. + } + + // ... + + // Post some characters that will be used within an ISR. If the queue + // is full then this task will block for xTicksToWait ticks. + cValueToPost = 'a'; + xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + cValueToPost = 'b'; + xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + + // ... keep posting characters ... this task may block when the queue + // becomes full. + + cValueToPost = 'c'; + xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait ); + } + + // ISR that outputs all the characters received on the queue. + void vISR_Routine( void ) + { + BaseType_t xTaskWokenByReceive = pdFALSE; + char cRxedChar; + + while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) ) + { + // A character was received. Output the character now. + vOutputCharacter( cRxedChar ); + + // If removing the character from the queue woke the task that was + // posting onto the queue cTaskWokenByReceive will have been set to + // pdTRUE. No matter how many times this loop iterates only one + // task will be woken. + } + + if( cTaskWokenByPost != ( char ) pdFALSE; + { + taskYIELD (); + } + } ++ * \defgroup xQueueReceiveFromISR xQueueReceiveFromISR + * \ingroup QueueManagement + */ +BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, void * const pvBuffer, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/* + * Utilities to query queues that are safe to use from an ISR. These utilities + * should be used only from witin an ISR, or within a critical section. + */ +BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + +/* + * The functions defined above are for passing data to and from tasks. The + * functions below are the equivalents for passing data to and from + * co-routines. + * + * These functions are called from the co-routine macro implementation and + * should not be called directly from application code. Instead use the macro + * wrappers defined within croutine.h. + */ +BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken ); +BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxTaskWoken ); +BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait ); +BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait ); + +/* + * For internal use only. Use xSemaphoreCreateMutex(), + * xSemaphoreCreateCounting() or xSemaphoreGetMutexHolder() instead of calling + * these functions directly. + */ +QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) PRIVILEGED_FUNCTION; +QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) PRIVILEGED_FUNCTION; +QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) PRIVILEGED_FUNCTION; +BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; +TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Use xSemaphoreTakeMutexRecursive() or + * xSemaphoreGiveMutexRecursive() instead of calling these functions directly. + */ +BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) PRIVILEGED_FUNCTION; + +/* + * Reset a queue back to its original empty state. The return value is now + * obsolete and is always set to pdPASS. + */ +#define xQueueReset( xQueue ) xQueueGenericReset( xQueue, pdFALSE ) + +/* + * The registry is provided as a means for kernel aware debuggers to + * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add + * a queue, semaphore or mutex handle to the registry if you want the handle + * to be available to a kernel aware debugger. If you are not using a kernel + * aware debugger then this function can be ignored. + * + * configQUEUE_REGISTRY_SIZE defines the maximum number of handles the + * registry can hold. configQUEUE_REGISTRY_SIZE must be greater than 0 + * within FreeRTOSConfig.h for the registry to be available. Its value + * does not effect the number of queues, semaphores and mutexes that can be + * created - just the number that the registry can hold. + * + * @param xQueue The handle of the queue being added to the registry. This + * is the handle returned by a call to xQueueCreate(). Semaphore and mutex + * handles can also be passed in here. + * + * @param pcName The name to be associated with the handle. This is the + * name that the kernel aware debugger will display. The queue registry only + * stores a pointer to the string - so the string must be persistent (global or + * preferably in ROM/Flash), not on the stack. + */ +#if( configQUEUE_REGISTRY_SIZE > 0 ) + void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +#endif + +/* + * The registry is provided as a means for kernel aware debuggers to + * locate queues, semaphores and mutexes. Call vQueueAddToRegistry() add + * a queue, semaphore or mutex handle to the registry if you want the handle + * to be available to a kernel aware debugger, and vQueueUnregisterQueue() to + * remove the queue, semaphore or mutex from the register. If you are not using + * a kernel aware debugger then this function can be ignored. + * + * @param xQueue The handle of the queue being removed from the registry. + */ +#if( configQUEUE_REGISTRY_SIZE > 0 ) + void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +#endif + +/* + * The queue registry is provided as a means for kernel aware debuggers to + * locate queues, semaphores and mutexes. Call pcQueueGetName() to look + * up and return the name of a queue in the queue registry from the queue's + * handle. + * + * @param xQueue The handle of the queue the name of which will be returned. + * @return If the queue is in the registry then a pointer to the name of the + * queue is returned. If the queue is not in the registry then NULL is + * returned. + */ +#if( configQUEUE_REGISTRY_SIZE > 0 ) + const char *pcQueueGetName( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +#endif + +/* + * Generic version of the function used to creaet a queue using dynamic memory + * allocation. This is called by other functions and macros that create other + * RTOS objects that use the queue structure as their base. + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +#endif + +/* + * Generic version of the function used to creaet a queue using dynamic memory + * allocation. This is called by other functions and macros that create other + * RTOS objects that use the queue structure as their base. + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION; +#endif + +/* + * Queue sets provide a mechanism to allow a task to block (pend) on a read + * operation from multiple queues or semaphores simultaneously. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * A queue set must be explicitly created using a call to xQueueCreateSet() + * before it can be used. Once created, standard FreeRTOS queues and semaphores + * can be added to the set using calls to xQueueAddToSet(). + * xQueueSelectFromSet() is then used to determine which, if any, of the queues + * or semaphores contained in the set is in a state where a queue read or + * semaphore take operation would be successful. + * + * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html + * for reasons why queue sets are very rarely needed in practice as there are + * simpler methods of blocking on multiple objects. + * + * Note 2: Blocking on a queue set that contains a mutex will not cause the + * mutex holder to inherit the priority of the blocked task. + * + * Note 3: An additional 4 bytes of RAM is required for each space in a every + * queue added to a queue set. Therefore counting semaphores that have a high + * maximum count value should not be added to a queue set. + * + * Note 4: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param uxEventQueueLength Queue sets store events that occur on + * the queues and semaphores contained in the set. uxEventQueueLength specifies + * the maximum number of events that can be queued at once. To be absolutely + * certain that events are not lost uxEventQueueLength should be set to the + * total sum of the length of the queues added to the set, where binary + * semaphores and mutexes have a length of 1, and counting semaphores have a + * length set by their maximum count value. Examples: + * + If a queue set is to hold a queue of length 5, another queue of length 12, + * and a binary semaphore, then uxEventQueueLength should be set to + * (5 + 12 + 1), or 18. + * + If a queue set is to hold three binary semaphores then uxEventQueueLength + * should be set to (1 + 1 + 1 ), or 3. + * + If a queue set is to hold a counting semaphore that has a maximum count of + * 5, and a counting semaphore that has a maximum count of 3, then + * uxEventQueueLength should be set to (5 + 3), or 8. + * + * @return If the queue set is created successfully then a handle to the created + * queue set is returned. Otherwise NULL is returned. + */ +QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION; + +/* + * Adds a queue or semaphore to a queue set that was previously created by a + * call to xQueueCreateSet(). + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * Note 1: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param xQueueOrSemaphore The handle of the queue or semaphore being added to + * the queue set (cast to an QueueSetMemberHandle_t type). + * + * @param xQueueSet The handle of the queue set to which the queue or semaphore + * is being added. + * + * @return If the queue or semaphore was successfully added to the queue set + * then pdPASS is returned. If the queue could not be successfully added to the + * queue set because it is already a member of a different queue set then pdFAIL + * is returned. + */ +BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* + * Removes a queue or semaphore from a queue set. A queue or semaphore can only + * be removed from a set if the queue or semaphore is empty. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * @param xQueueOrSemaphore The handle of the queue or semaphore being removed + * from the queue set (cast to an QueueSetMemberHandle_t type). + * + * @param xQueueSet The handle of the queue set in which the queue or semaphore + * is included. + * + * @return If the queue or semaphore was successfully removed from the queue set + * then pdPASS is returned. If the queue was not in the queue set, or the + * queue (or semaphore) was not empty, then pdFAIL is returned. + */ +BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* + * xQueueSelectFromSet() selects from the members of a queue set a queue or + * semaphore that either contains data (in the case of a queue) or is available + * to take (in the case of a semaphore). xQueueSelectFromSet() effectively + * allows a task to block (pend) on a read operation on all the queues and + * semaphores in a queue set simultaneously. + * + * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this + * function. + * + * Note 1: See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html + * for reasons why queue sets are very rarely needed in practice as there are + * simpler methods of blocking on multiple objects. + * + * Note 2: Blocking on a queue set that contains a mutex will not cause the + * mutex holder to inherit the priority of the blocked task. + * + * Note 3: A receive (in the case of a queue) or take (in the case of a + * semaphore) operation must not be performed on a member of a queue set unless + * a call to xQueueSelectFromSet() has first returned a handle to that set member. + * + * @param xQueueSet The queue set on which the task will (potentially) block. + * + * @param xTicksToWait The maximum time, in ticks, that the calling task will + * remain in the Blocked state (with other tasks executing) to wait for a member + * of the queue set to be ready for a successful queue read or semaphore take + * operation. + * + * @return xQueueSelectFromSet() will return the handle of a queue (cast to + * a QueueSetMemberHandle_t type) contained in the queue set that contains data, + * or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained + * in the queue set that is available, or NULL if no such queue or semaphore + * exists before before the specified block time expires. + */ +QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/* + * A version of xQueueSelectFromSet() that can be used from an ISR. + */ +QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION; + +/* Not public API functions. */ +void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; +BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) PRIVILEGED_FUNCTION; +void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) PRIVILEGED_FUNCTION; +UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; +uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION; + + +#ifdef __cplusplus +} +#endif + +#endif /* QUEUE_H */ + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h b/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h new file mode 100644 index 0000000..787c791 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/semphr.h @@ -0,0 +1,1140 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef SEMAPHORE_H +#define SEMAPHORE_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h" must appear in source files before "include semphr.h" +#endif + +#include "queue.h" + +typedef QueueHandle_t SemaphoreHandle_t; + +#define semBINARY_SEMAPHORE_QUEUE_LENGTH ( ( uint8_t ) 1U ) +#define semSEMAPHORE_QUEUE_ITEM_LENGTH ( ( uint8_t ) 0U ) +#define semGIVE_BLOCK_TIME ( ( TickType_t ) 0U ) + + +/** + * semphr. h + *vSemaphoreCreateBinary( SemaphoreHandle_t xSemaphore )+ * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * Macro that implements a semaphore by using the existing queue mechanism. + * The queue length is 1 as this is a binary semaphore. The data size is 0 + * as we don't want to actually store any data - we just want to know if the + * queue is empty or full. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param xSemaphore Handle to the created semaphore. Should be of type SemaphoreHandle_t. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore = NULL; + + void vATask( void * pvParameters ) + { + // Semaphore cannot be used before a call to vSemaphoreCreateBinary (). + // This is a macro so pass the variable in directly. + vSemaphoreCreateBinary( xSemaphore ); + + if( xSemaphore != NULL ) + { + // The semaphore was created successfully. + // The semaphore can now be used. + } + } ++ * \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary + * \ingroup Semaphores + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define vSemaphoreCreateBinary( xSemaphore ) \ + { \ + ( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ); \ + if( ( xSemaphore ) != NULL ) \ + { \ + ( void ) xSemaphoreGive( ( xSemaphore ) ); \ + } \ + } +#endif + +/** + * semphr. h + *SemaphoreHandle_t xSemaphoreCreateBinary( void )+ * + * Creates a new binary semaphore instance, and returns a handle by which the + * new semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see http://www.freertos.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this + * xSemaphoreCreateBinary() function. Note that binary semaphores created using + * the vSemaphoreCreateBinary() macro are created in a state such that the + * first call to 'take' the semaphore would pass, whereas binary semaphores + * created using xSemaphoreCreateBinary() are created in a state such that the + * the semaphore must first be 'given' before it can be 'taken'. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @return Handle to the created semaphore, or NULL if the memory required to + * hold the semaphore's data structures could not be allocated. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore = NULL; + + void vATask( void * pvParameters ) + { + // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). + // This is a macro so pass the variable in directly. + xSemaphore = xSemaphoreCreateBinary(); + + if( xSemaphore != NULL ) + { + // The semaphore was created successfully. + // The semaphore can now be used. + } + } ++ * \defgroup xSemaphoreCreateBinary xSemaphoreCreateBinary + * \ingroup Semaphores + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE ) +#endif + +/** + * semphr. h + *SemaphoreHandle_t xSemaphoreCreateBinaryStatic( StaticSemaphore_t *pxSemaphoreBuffer )+ * + * Creates a new binary semaphore instance, and returns a handle by which the + * new semaphore can be referenced. + * + * NOTE: In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a binary semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, binary semaphores use a block + * of memory, in which the semaphore structure is stored. If a binary semaphore + * is created using xSemaphoreCreateBinary() then the required memory is + * automatically dynamically allocated inside the xSemaphoreCreateBinary() + * function. (see http://www.freertos.org/a00111.html). If a binary semaphore + * is created using xSemaphoreCreateBinaryStatic() then the application writer + * must provide the memory. xSemaphoreCreateBinaryStatic() therefore allows a + * binary semaphore to be created without using any dynamic memory allocation. + * + * This type of semaphore can be used for pure synchronisation between tasks or + * between an interrupt and a task. The semaphore need not be given back once + * obtained, so one task/interrupt can continuously 'give' the semaphore while + * another continuously 'takes' the semaphore. For this reason this type of + * semaphore does not use a priority inheritance mechanism. For an alternative + * that does use priority inheritance see xSemaphoreCreateMutex(). + * + * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the semaphore is created then a handle to the created semaphore is + * returned. If pxSemaphoreBuffer is NULL then NULL is returned. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore = NULL; + StaticSemaphore_t xSemaphoreBuffer; + + void vATask( void * pvParameters ) + { + // Semaphore cannot be used before a call to xSemaphoreCreateBinary(). + // The semaphore's data structures will be placed in the xSemaphoreBuffer + // variable, the address of which is passed into the function. The + // function's parameter is not NULL, so the function will not attempt any + // dynamic memory allocation, and therefore the function will not return + // return NULL. + xSemaphore = xSemaphoreCreateBinary( &xSemaphoreBuffer ); + + // Rest of task code goes here. + } ++ * \defgroup xSemaphoreCreateBinaryStatic xSemaphoreCreateBinaryStatic + * \ingroup Semaphores + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateBinaryStatic( pxStaticSemaphore ) xQueueGenericCreateStatic( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticSemaphore, queueQUEUE_TYPE_BINARY_SEMAPHORE ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * semphr. h + *xSemaphoreTake( + * SemaphoreHandle_t xSemaphore, + * TickType_t xBlockTime + * )+ * + * Macro to obtain a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or + * xSemaphoreCreateCounting(). + * + * @param xSemaphore A handle to the semaphore being taken - obtained when + * the semaphore was created. + * + * @param xBlockTime The time in ticks to wait for the semaphore to become + * available. The macro portTICK_PERIOD_MS can be used to convert this to a + * real time. A block time of zero can be used to poll the semaphore. A block + * time of portMAX_DELAY can be used to block indefinitely (provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h). + * + * @return pdTRUE if the semaphore was obtained. pdFALSE + * if xBlockTime expired without the semaphore becoming available. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore = NULL; + + // A task that creates a semaphore. + void vATask( void * pvParameters ) + { + // Create the semaphore to guard a shared resource. + xSemaphore = xSemaphoreCreateBinary(); + } + + // A task that uses the semaphore. + void vAnotherTask( void * pvParameters ) + { + // ... Do other things. + + if( xSemaphore != NULL ) + { + // See if we can obtain the semaphore. If the semaphore is not available + // wait 10 ticks to see if it becomes free. + if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) + { + // We were able to obtain the semaphore and can now access the + // shared resource. + + // ... + + // We have finished accessing the shared resource. Release the + // semaphore. + xSemaphoreGive( xSemaphore ); + } + else + { + // We could not obtain the semaphore and can therefore not access + // the shared resource safely. + } + } + } ++ * \defgroup xSemaphoreTake xSemaphoreTake + * \ingroup Semaphores + */ +#define xSemaphoreTake( xSemaphore, xBlockTime ) xQueueSemaphoreTake( ( xSemaphore ), ( xBlockTime ) ) + +/** + * semphr. h + * xSemaphoreTakeRecursive( + * SemaphoreHandle_t xMutex, + * TickType_t xBlockTime + * ) + * + * Macro to recursively obtain, or 'take', a mutex type semaphore. + * The mutex must have previously been created using a call to + * xSemaphoreCreateRecursiveMutex(); + * + * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this + * macro to be available. + * + * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * @param xMutex A handle to the mutex being obtained. This is the + * handle returned by xSemaphoreCreateRecursiveMutex(); + * + * @param xBlockTime The time in ticks to wait for the semaphore to become + * available. The macro portTICK_PERIOD_MS can be used to convert this to a + * real time. A block time of zero can be used to poll the semaphore. If + * the task already owns the semaphore then xSemaphoreTakeRecursive() will + * return immediately no matter what the value of xBlockTime. + * + * @return pdTRUE if the semaphore was obtained. pdFALSE if xBlockTime + * expired without the semaphore becoming available. + * + * Example usage: ++ SemaphoreHandle_t xMutex = NULL; + + // A task that creates a mutex. + void vATask( void * pvParameters ) + { + // Create the mutex to guard a shared resource. + xMutex = xSemaphoreCreateRecursiveMutex(); + } + + // A task that uses the mutex. + void vAnotherTask( void * pvParameters ) + { + // ... Do other things. + + if( xMutex != NULL ) + { + // See if we can obtain the mutex. If the mutex is not available + // wait 10 ticks to see if it becomes free. + if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) + { + // We were able to obtain the mutex and can now access the + // shared resource. + + // ... + // For some reason due to the nature of the code further calls to + // xSemaphoreTakeRecursive() are made on the same mutex. In real + // code these would not be just sequential calls as this would make + // no sense. Instead the calls are likely to be buried inside + // a more complex call structure. + xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + + // The mutex has now been 'taken' three times, so will not be + // available to another task until it has also been given back + // three times. Again it is unlikely that real code would have + // these calls sequentially, but instead buried in a more complex + // call structure. This is just for illustrative purposes. + xSemaphoreGiveRecursive( xMutex ); + xSemaphoreGiveRecursive( xMutex ); + xSemaphoreGiveRecursive( xMutex ); + + // Now the mutex can be taken by other tasks. + } + else + { + // We could not obtain the mutex and can therefore not access + // the shared resource safely. + } + } + } ++ * \defgroup xSemaphoreTakeRecursive xSemaphoreTakeRecursive + * \ingroup Semaphores + */ +#if( configUSE_RECURSIVE_MUTEXES == 1 ) + #define xSemaphoreTakeRecursive( xMutex, xBlockTime ) xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) ) +#endif + +/** + * semphr. h + *xSemaphoreGive( SemaphoreHandle_t xSemaphore )+ * + * Macro to release a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary(), xSemaphoreCreateMutex() or + * xSemaphoreCreateCounting(). and obtained using sSemaphoreTake(). + * + * This macro must not be used from an ISR. See xSemaphoreGiveFromISR () for + * an alternative which can be used from an ISR. + * + * This macro must also not be used on semaphores created using + * xSemaphoreCreateRecursiveMutex(). + * + * @param xSemaphore A handle to the semaphore being released. This is the + * handle returned when the semaphore was created. + * + * @return pdTRUE if the semaphore was released. pdFALSE if an error occurred. + * Semaphores are implemented using queues. An error can occur if there is + * no space on the queue to post a message - indicating that the + * semaphore was not first obtained correctly. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore = NULL; + + void vATask( void * pvParameters ) + { + // Create the semaphore to guard a shared resource. + xSemaphore = vSemaphoreCreateBinary(); + + if( xSemaphore != NULL ) + { + if( xSemaphoreGive( xSemaphore ) != pdTRUE ) + { + // We would expect this call to fail because we cannot give + // a semaphore without first "taking" it! + } + + // Obtain the semaphore - don't block if the semaphore is not + // immediately available. + if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) ) + { + // We now have the semaphore and can access the shared resource. + + // ... + + // We have finished accessing the shared resource so can free the + // semaphore. + if( xSemaphoreGive( xSemaphore ) != pdTRUE ) + { + // We would not expect this call to fail because we must have + // obtained the semaphore to get here. + } + } + } + } ++ * \defgroup xSemaphoreGive xSemaphoreGive + * \ingroup Semaphores + */ +#define xSemaphoreGive( xSemaphore ) xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK ) + +/** + * semphr. h + *xSemaphoreGiveRecursive( SemaphoreHandle_t xMutex )+ * + * Macro to recursively release, or 'give', a mutex type semaphore. + * The mutex must have previously been created using a call to + * xSemaphoreCreateRecursiveMutex(); + * + * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this + * macro to be available. + * + * This macro must not be used on mutexes created using xSemaphoreCreateMutex(). + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * @param xMutex A handle to the mutex being released, or 'given'. This is the + * handle returned by xSemaphoreCreateMutex(); + * + * @return pdTRUE if the semaphore was given. + * + * Example usage: ++ SemaphoreHandle_t xMutex = NULL; + + // A task that creates a mutex. + void vATask( void * pvParameters ) + { + // Create the mutex to guard a shared resource. + xMutex = xSemaphoreCreateRecursiveMutex(); + } + + // A task that uses the mutex. + void vAnotherTask( void * pvParameters ) + { + // ... Do other things. + + if( xMutex != NULL ) + { + // See if we can obtain the mutex. If the mutex is not available + // wait 10 ticks to see if it becomes free. + if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE ) + { + // We were able to obtain the mutex and can now access the + // shared resource. + + // ... + // For some reason due to the nature of the code further calls to + // xSemaphoreTakeRecursive() are made on the same mutex. In real + // code these would not be just sequential calls as this would make + // no sense. Instead the calls are likely to be buried inside + // a more complex call structure. + xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ); + + // The mutex has now been 'taken' three times, so will not be + // available to another task until it has also been given back + // three times. Again it is unlikely that real code would have + // these calls sequentially, it would be more likely that the calls + // to xSemaphoreGiveRecursive() would be called as a call stack + // unwound. This is just for demonstrative purposes. + xSemaphoreGiveRecursive( xMutex ); + xSemaphoreGiveRecursive( xMutex ); + xSemaphoreGiveRecursive( xMutex ); + + // Now the mutex can be taken by other tasks. + } + else + { + // We could not obtain the mutex and can therefore not access + // the shared resource safely. + } + } + } ++ * \defgroup xSemaphoreGiveRecursive xSemaphoreGiveRecursive + * \ingroup Semaphores + */ +#if( configUSE_RECURSIVE_MUTEXES == 1 ) + #define xSemaphoreGiveRecursive( xMutex ) xQueueGiveMutexRecursive( ( xMutex ) ) +#endif + +/** + * semphr. h + *+ xSemaphoreGiveFromISR( + SemaphoreHandle_t xSemaphore, + BaseType_t *pxHigherPriorityTaskWoken + )+ * + * Macro to release a semaphore. The semaphore must have previously been + * created with a call to xSemaphoreCreateBinary() or xSemaphoreCreateCounting(). + * + * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) + * must not be used with this macro. + * + * This macro can be used from an ISR. + * + * @param xSemaphore A handle to the semaphore being released. This is the + * handle returned when the semaphore was created. + * + * @param pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xSemaphoreGiveFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL. + * + * Example usage: ++ \#define LONG_TIME 0xffff + \#define TICKS_TO_WAIT 10 + SemaphoreHandle_t xSemaphore = NULL; + + // Repetitive task. + void vATask( void * pvParameters ) + { + for( ;; ) + { + // We want this task to run every 10 ticks of a timer. The semaphore + // was created before this task was started. + + // Block waiting for the semaphore to become available. + if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE ) + { + // It is time to execute. + + // ... + + // We have finished our task. Return to the top of the loop where + // we will block on the semaphore until it is time to execute + // again. Note when using the semaphore for synchronisation with an + // ISR in this manner there is no need to 'give' the semaphore back. + } + } + } + + // Timer ISR + void vTimerISR( void * pvParameters ) + { + static uint8_t ucLocalTickCount = 0; + static BaseType_t xHigherPriorityTaskWoken; + + // A timer tick has occurred. + + // ... Do other time functions. + + // Is it time for vATask () to run? + xHigherPriorityTaskWoken = pdFALSE; + ucLocalTickCount++; + if( ucLocalTickCount >= TICKS_TO_WAIT ) + { + // Unblock the task by releasing the semaphore. + xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken ); + + // Reset the count so we release the semaphore again in 10 ticks time. + ucLocalTickCount = 0; + } + + if( xHigherPriorityTaskWoken != pdFALSE ) + { + // We can force a context switch here. Context switching from an + // ISR uses port specific syntax. Check the demo task for your port + // to find the syntax required. + } + } ++ * \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR + * \ingroup Semaphores + */ +#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) ) + +/** + * semphr. h + *+ xSemaphoreTakeFromISR( + SemaphoreHandle_t xSemaphore, + BaseType_t *pxHigherPriorityTaskWoken + )+ * + * Macro to take a semaphore from an ISR. The semaphore must have + * previously been created with a call to xSemaphoreCreateBinary() or + * xSemaphoreCreateCounting(). + * + * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex()) + * must not be used with this macro. + * + * This macro can be used from an ISR, however taking a semaphore from an ISR + * is not a common operation. It is likely to only be useful when taking a + * counting semaphore when an interrupt is obtaining an object from a resource + * pool (when the semaphore count indicates the number of resources available). + * + * @param xSemaphore A handle to the semaphore being taken. This is the + * handle returned when the semaphore was created. + * + * @param pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task + * to unblock, and the unblocked task has a priority higher than the currently + * running task. If xSemaphoreTakeFromISR() sets this value to pdTRUE then + * a context switch should be requested before the interrupt is exited. + * + * @return pdTRUE if the semaphore was successfully taken, otherwise + * pdFALSE + */ +#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken ) xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) ) + +/** + * semphr. h + *SemaphoreHandle_t xSemaphoreCreateMutex( void )+ * + * Creates a new mutex type semaphore instance, and returns a handle by which + * the new mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, mutex semaphores use a block + * of memory, in which the mutex structure is stored. If a mutex is created + * using xSemaphoreCreateMutex() then the required memory is automatically + * dynamically allocated inside the xSemaphoreCreateMutex() function. (see + * http://www.freertos.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return If the mutex was successfully created then a handle to the created + * semaphore is returned. If there was not enough heap to allocate the mutex + * data structures then NULL is returned. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore; + + void vATask( void * pvParameters ) + { + // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). + // This is a macro so pass the variable in directly. + xSemaphore = xSemaphoreCreateMutex(); + + if( xSemaphore != NULL ) + { + // The semaphore was created successfully. + // The semaphore can now be used. + } + } ++ * \defgroup xSemaphoreCreateMutex xSemaphoreCreateMutex + * \ingroup Semaphores + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX ) +#endif + +/** + * semphr. h + *SemaphoreHandle_t xSemaphoreCreateMutexStatic( StaticSemaphore_t *pxMutexBuffer )+ * + * Creates a new mutex type semaphore instance, and returns a handle by which + * the new mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, mutex semaphores use a block + * of memory, in which the mutex structure is stored. If a mutex is created + * using xSemaphoreCreateMutex() then the required memory is automatically + * dynamically allocated inside the xSemaphoreCreateMutex() function. (see + * http://www.freertos.org/a00111.html). If a mutex is created using + * xSemaphoreCreateMutexStatic() then the application writer must provided the + * memory. xSemaphoreCreateMutexStatic() therefore allows a mutex to be created + * without using any dynamic memory allocation. + * + * Mutexes created using this function can be accessed using the xSemaphoreTake() + * and xSemaphoreGive() macros. The xSemaphoreTakeRecursive() and + * xSemaphoreGiveRecursive() macros must not be used. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, + * which will be used to hold the mutex's data structure, removing the need for + * the memory to be allocated dynamically. + * + * @return If the mutex was successfully created then a handle to the created + * mutex is returned. If pxMutexBuffer was NULL then NULL is returned. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore; + StaticSemaphore_t xMutexBuffer; + + void vATask( void * pvParameters ) + { + // A mutex cannot be used before it has been created. xMutexBuffer is + // into xSemaphoreCreateMutexStatic() so no dynamic memory allocation is + // attempted. + xSemaphore = xSemaphoreCreateMutexStatic( &xMutexBuffer ); + + // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, + // so there is no need to check it. + } ++ * \defgroup xSemaphoreCreateMutexStatic xSemaphoreCreateMutexStatic + * \ingroup Semaphores + */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateMutexStatic( pxMutexBuffer ) xQueueCreateMutexStatic( queueQUEUE_TYPE_MUTEX, ( pxMutexBuffer ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + + +/** + * semphr. h + *SemaphoreHandle_t xSemaphoreCreateRecursiveMutex( void )+ * + * Creates a new recursive mutex type semaphore instance, and returns a handle + * by which the new recursive mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, recursive mutexs use a block + * of memory, in which the mutex structure is stored. If a recursive mutex is + * created using xSemaphoreCreateRecursiveMutex() then the required memory is + * automatically dynamically allocated inside the + * xSemaphoreCreateRecursiveMutex() function. (see + * http://www.freertos.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @return xSemaphore Handle to the created mutex semaphore. Should be of type + * SemaphoreHandle_t. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore; + + void vATask( void * pvParameters ) + { + // Semaphore cannot be used before a call to xSemaphoreCreateMutex(). + // This is a macro so pass the variable in directly. + xSemaphore = xSemaphoreCreateRecursiveMutex(); + + if( xSemaphore != NULL ) + { + // The semaphore was created successfully. + // The semaphore can now be used. + } + } ++ * \defgroup xSemaphoreCreateRecursiveMutex xSemaphoreCreateRecursiveMutex + * \ingroup Semaphores + */ +#if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) + #define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX ) +#endif + +/** + * semphr. h + *SemaphoreHandle_t xSemaphoreCreateRecursiveMutexStatic( StaticSemaphore_t *pxMutexBuffer )+ * + * Creates a new recursive mutex type semaphore instance, and returns a handle + * by which the new recursive mutex can be referenced. + * + * Internally, within the FreeRTOS implementation, recursive mutexs use a block + * of memory, in which the mutex structure is stored. If a recursive mutex is + * created using xSemaphoreCreateRecursiveMutex() then the required memory is + * automatically dynamically allocated inside the + * xSemaphoreCreateRecursiveMutex() function. (see + * http://www.freertos.org/a00111.html). If a recursive mutex is created using + * xSemaphoreCreateRecursiveMutexStatic() then the application writer must + * provide the memory that will get used by the mutex. + * xSemaphoreCreateRecursiveMutexStatic() therefore allows a recursive mutex to + * be created without using any dynamic memory allocation. + * + * Mutexes created using this macro can be accessed using the + * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros. The + * xSemaphoreTake() and xSemaphoreGive() macros must not be used. + * + * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex + * doesn't become available again until the owner has called + * xSemaphoreGiveRecursive() for each successful 'take' request. For example, + * if a task successfully 'takes' the same mutex 5 times then the mutex will + * not be available to any other task until it has also 'given' the mutex back + * exactly five times. + * + * This type of semaphore uses a priority inheritance mechanism so a task + * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the + * semaphore it is no longer required. + * + * Mutex type semaphores cannot be used from within interrupt service routines. + * + * See xSemaphoreCreateBinary() for an alternative implementation that can be + * used for pure synchronisation (where one task or interrupt always 'gives' the + * semaphore and another always 'takes' the semaphore) and from within interrupt + * service routines. + * + * @param pxMutexBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the recursive mutex's data structure, + * removing the need for the memory to be allocated dynamically. + * + * @return If the recursive mutex was successfully created then a handle to the + * created recursive mutex is returned. If pxMutexBuffer was NULL then NULL is + * returned. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore; + StaticSemaphore_t xMutexBuffer; + + void vATask( void * pvParameters ) + { + // A recursive semaphore cannot be used before it is created. Here a + // recursive mutex is created using xSemaphoreCreateRecursiveMutexStatic(). + // The address of xMutexBuffer is passed into the function, and will hold + // the mutexes data structures - so no dynamic memory allocation will be + // attempted. + xSemaphore = xSemaphoreCreateRecursiveMutexStatic( &xMutexBuffer ); + + // As no dynamic memory allocation was performed, xSemaphore cannot be NULL, + // so there is no need to check it. + } ++ * \defgroup xSemaphoreCreateRecursiveMutexStatic xSemaphoreCreateRecursiveMutexStatic + * \ingroup Semaphores + */ +#if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configUSE_RECURSIVE_MUTEXES == 1 ) ) + #define xSemaphoreCreateRecursiveMutexStatic( pxStaticSemaphore ) xQueueCreateMutexStatic( queueQUEUE_TYPE_RECURSIVE_MUTEX, pxStaticSemaphore ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * semphr. h + *SemaphoreHandle_t xSemaphoreCreateCounting( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount )+ * + * Creates a new counting semaphore instance, and returns a handle by which the + * new counting semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a counting semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * http://www.freertos.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer can + * instead optionally provide the memory that will get used by the counting + * semaphore. xSemaphoreCreateCountingStatic() therefore allows a counting + * semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @return Handle to the created semaphore. Null if the semaphore could not be + * created. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore; + + void vATask( void * pvParameters ) + { + SemaphoreHandle_t xSemaphore = NULL; + + // Semaphore cannot be used before a call to xSemaphoreCreateCounting(). + // The max value to which the semaphore can count should be 10, and the + // initial value assigned to the count should be 0. + xSemaphore = xSemaphoreCreateCounting( 10, 0 ); + + if( xSemaphore != NULL ) + { + // The semaphore was created successfully. + // The semaphore can now be used. + } + } ++ * \defgroup xSemaphoreCreateCounting xSemaphoreCreateCounting + * \ingroup Semaphores + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + #define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) ) +#endif + +/** + * semphr. h + *SemaphoreHandle_t xSemaphoreCreateCountingStatic( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount, StaticSemaphore_t *pxSemaphoreBuffer )+ * + * Creates a new counting semaphore instance, and returns a handle by which the + * new counting semaphore can be referenced. + * + * In many usage scenarios it is faster and more memory efficient to use a + * direct to task notification in place of a counting semaphore! + * http://www.freertos.org/RTOS-task-notifications.html + * + * Internally, within the FreeRTOS implementation, counting semaphores use a + * block of memory, in which the counting semaphore structure is stored. If a + * counting semaphore is created using xSemaphoreCreateCounting() then the + * required memory is automatically dynamically allocated inside the + * xSemaphoreCreateCounting() function. (see + * http://www.freertos.org/a00111.html). If a counting semaphore is created + * using xSemaphoreCreateCountingStatic() then the application writer must + * provide the memory. xSemaphoreCreateCountingStatic() therefore allows a + * counting semaphore to be created without using any dynamic memory allocation. + * + * Counting semaphores are typically used for two things: + * + * 1) Counting events. + * + * In this usage scenario an event handler will 'give' a semaphore each time + * an event occurs (incrementing the semaphore count value), and a handler + * task will 'take' a semaphore each time it processes an event + * (decrementing the semaphore count value). The count value is therefore + * the difference between the number of events that have occurred and the + * number that have been processed. In this case it is desirable for the + * initial count value to be zero. + * + * 2) Resource management. + * + * In this usage scenario the count value indicates the number of resources + * available. To obtain control of a resource a task must first obtain a + * semaphore - decrementing the semaphore count value. When the count value + * reaches zero there are no free resources. When a task finishes with the + * resource it 'gives' the semaphore back - incrementing the semaphore count + * value. In this case it is desirable for the initial count value to be + * equal to the maximum count value, indicating that all resources are free. + * + * @param uxMaxCount The maximum count value that can be reached. When the + * semaphore reaches this value it can no longer be 'given'. + * + * @param uxInitialCount The count value assigned to the semaphore when it is + * created. + * + * @param pxSemaphoreBuffer Must point to a variable of type StaticSemaphore_t, + * which will then be used to hold the semaphore's data structure, removing the + * need for the memory to be allocated dynamically. + * + * @return If the counting semaphore was successfully created then a handle to + * the created counting semaphore is returned. If pxSemaphoreBuffer was NULL + * then NULL is returned. + * + * Example usage: ++ SemaphoreHandle_t xSemaphore; + StaticSemaphore_t xSemaphoreBuffer; + + void vATask( void * pvParameters ) + { + SemaphoreHandle_t xSemaphore = NULL; + + // Counting semaphore cannot be used before they have been created. Create + // a counting semaphore using xSemaphoreCreateCountingStatic(). The max + // value to which the semaphore can count is 10, and the initial value + // assigned to the count will be 0. The address of xSemaphoreBuffer is + // passed in and will be used to hold the semaphore structure, so no dynamic + // memory allocation will be used. + xSemaphore = xSemaphoreCreateCounting( 10, 0, &xSemaphoreBuffer ); + + // No memory allocation was attempted so xSemaphore cannot be NULL, so there + // is no need to check its value. + } ++ * \defgroup xSemaphoreCreateCountingStatic xSemaphoreCreateCountingStatic + * \ingroup Semaphores + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + #define xSemaphoreCreateCountingStatic( uxMaxCount, uxInitialCount, pxSemaphoreBuffer ) xQueueCreateCountingSemaphoreStatic( ( uxMaxCount ), ( uxInitialCount ), ( pxSemaphoreBuffer ) ) +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * semphr. h + *void vSemaphoreDelete( SemaphoreHandle_t xSemaphore );+ * + * Delete a semaphore. This function must be used with care. For example, + * do not delete a mutex type semaphore if the mutex is held by a task. + * + * @param xSemaphore A handle to the semaphore to be deleted. + * + * \defgroup vSemaphoreDelete vSemaphoreDelete + * \ingroup Semaphores + */ +#define vSemaphoreDelete( xSemaphore ) vQueueDelete( ( QueueHandle_t ) ( xSemaphore ) ) + +/** + * semphr.h + *TaskHandle_t xSemaphoreGetMutexHolder( SemaphoreHandle_t xMutex );+ * + * If xMutex is indeed a mutex type semaphore, return the current mutex holder. + * If xMutex is not a mutex type semaphore, or the mutex is available (not held + * by a task), return NULL. + * + * Note: This is a good way of determining if the calling task is the mutex + * holder, but not a good way of determining the identity of the mutex holder as + * the holder may change between the function exiting and the returned value + * being tested. + */ +#define xSemaphoreGetMutexHolder( xSemaphore ) xQueueGetMutexHolder( ( xSemaphore ) ) + +/** + * semphr.h + *TaskHandle_t xSemaphoreGetMutexHolderFromISR( SemaphoreHandle_t xMutex );+ * + * If xMutex is indeed a mutex type semaphore, return the current mutex holder. + * If xMutex is not a mutex type semaphore, or the mutex is available (not held + * by a task), return NULL. + * + */ +#define xSemaphoreGetMutexHolderFromISR( xSemaphore ) xQueueGetMutexHolderFromISR( ( xSemaphore ) ) + +/** + * semphr.h + *UBaseType_t uxSemaphoreGetCount( SemaphoreHandle_t xSemaphore );+ * + * If the semaphore is a counting semaphore then uxSemaphoreGetCount() returns + * its current count value. If the semaphore is a binary semaphore then + * uxSemaphoreGetCount() returns 1 if the semaphore is available, and 0 if the + * semaphore is not available. + * + */ +#define uxSemaphoreGetCount( xSemaphore ) uxQueueMessagesWaiting( ( QueueHandle_t ) ( xSemaphore ) ) + +#endif /* SEMAPHORE_H */ + + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h b/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h new file mode 100644 index 0000000..b5bac08 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/stack_macros.h @@ -0,0 +1,129 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#ifndef STACK_MACROS_H +#define STACK_MACROS_H + +/* + * Call the stack overflow hook function if the stack of the task being swapped + * out is currently overflowed, or looks like it might have overflowed in the + * past. + * + * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check + * the current stack state only - comparing the current top of stack value to + * the stack limit. Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1 + * will also cause the last few stack bytes to be checked to ensure the value + * to which the bytes were set when the task was created have not been + * overwritten. Note this second test does not guarantee that an overflowed + * stack will always be recognised. + */ + +/*-----------------------------------------------------------*/ + +#if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH < 0 ) ) + + /* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } + +#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ +/*-----------------------------------------------------------*/ + +#if( ( configCHECK_FOR_STACK_OVERFLOW == 1 ) && ( portSTACK_GROWTH > 0 ) ) + + /* Only the current stack state is to be checked. */ + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + \ + /* Is the currently saved stack pointer within the stack limit? */ \ + if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } + +#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */ +/*-----------------------------------------------------------*/ + +#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) ) + + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + const uint32_t * const pulStack = ( uint32_t * ) pxCurrentTCB->pxStack; \ + const uint32_t ulCheckValue = ( uint32_t ) 0xa5a5a5a5; \ + \ + if( ( pulStack[ 0 ] != ulCheckValue ) || \ + ( pulStack[ 1 ] != ulCheckValue ) || \ + ( pulStack[ 2 ] != ulCheckValue ) || \ + ( pulStack[ 3 ] != ulCheckValue ) ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } + +#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ +/*-----------------------------------------------------------*/ + +#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) ) + + #define taskCHECK_FOR_STACK_OVERFLOW() \ + { \ + int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack; \ + static const uint8_t ucExpectedStackBytes[] = { tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, \ + tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE }; \ + \ + \ + pcEndOfStack -= sizeof( ucExpectedStackBytes ); \ + \ + /* Has the extremity of the task stack ever been written over? */ \ + if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 ) \ + { \ + vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName ); \ + } \ + } + +#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */ +/*-----------------------------------------------------------*/ + +/* Remove stack overflow macro if not being used. */ +#ifndef taskCHECK_FOR_STACK_OVERFLOW + #define taskCHECK_FOR_STACK_OVERFLOW() +#endif + + + +#endif /* STACK_MACROS_H */ + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h b/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h new file mode 100644 index 0000000..a8b68ad --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/stream_buffer.h @@ -0,0 +1,859 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * Stream buffers are used to send a continuous stream of data from one task or + * interrupt to another. Their implementation is light weight, making them + * particularly suited for interrupt to task and core to core communication + * scenarios. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section section and set the + * receive block time to 0. + * + */ + +#ifndef STREAM_BUFFER_H +#define STREAM_BUFFER_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include stream_buffer.h" +#endif + +#if defined( __cplusplus ) +extern "C" { +#endif + +/** + * Type by which stream buffers are referenced. For example, a call to + * xStreamBufferCreate() returns an StreamBufferHandle_t variable that can + * then be used as a parameter to xStreamBufferSend(), xStreamBufferReceive(), + * etc. + */ +struct StreamBufferDef_t; +typedef struct StreamBufferDef_t * StreamBufferHandle_t; + + +/** + * message_buffer.h + * ++StreamBufferHandle_t xStreamBufferCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes ); ++ * + * Creates a new stream buffer using dynamically allocated memory. See + * xStreamBufferCreateStatic() for a version that uses statically allocated + * memory (memory that is allocated at compile time). + * + * configSUPPORT_DYNAMIC_ALLOCATION must be set to 1 or left undefined in + * FreeRTOSConfig.h for xStreamBufferCreate() to be available. + * + * @param xBufferSizeBytes The total number of bytes the stream buffer will be + * able to hold at any one time. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * buffer before a task that is blocked on the stream buffer to wait for data is + * moved out of the blocked state. For example, if a task is blocked on a read + * of an empty stream buffer that has a trigger level of 1 then the task will be + * unblocked when a single byte is written to the buffer or the task's block + * time expires. As another example, if a task is blocked on a read of an empty + * stream buffer that has a trigger level of 10 then the task will not be + * unblocked until the stream buffer contains at least 10 bytes or the task's + * block time expires. If a reading task's block time expires before the + * trigger level is reached then the task will still receive however many bytes + * are actually available. Setting a trigger level of 0 will result in a + * trigger level of 1 being used. It is not valid to specify a trigger level + * that is greater than the buffer size. + * + * @return If NULL is returned, then the stream buffer cannot be created + * because there is insufficient heap memory available for FreeRTOS to allocate + * the stream buffer data structures and storage area. A non-NULL value being + * returned indicates that the stream buffer has been created successfully - + * the returned value should be stored as the handle to the created stream + * buffer. + * + * Example use: ++ +void vAFunction( void ) +{ +StreamBufferHandle_t xStreamBuffer; +const size_t xStreamBufferSizeBytes = 100, xTriggerLevel = 10; + + // Create a stream buffer that can hold 100 bytes. The memory used to hold + // both the stream buffer structure and the data in the stream buffer is + // allocated dynamically. + xStreamBuffer = xStreamBufferCreate( xStreamBufferSizeBytes, xTriggerLevel ); + + if( xStreamBuffer == NULL ) + { + // There was not enough heap memory space available to create the + // stream buffer. + } + else + { + // The stream buffer was created successfully and can now be used. + } +} ++ * \defgroup xStreamBufferCreate xStreamBufferCreate + * \ingroup StreamBufferManagement + */ +#define xStreamBufferCreate( xBufferSizeBytes, xTriggerLevelBytes ) xStreamBufferGenericCreate( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE ) + +/** + * stream_buffer.h + * ++StreamBufferHandle_t xStreamBufferCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t *pucStreamBufferStorageArea, + StaticStreamBuffer_t *pxStaticStreamBuffer ); ++ * Creates a new stream buffer using statically allocated memory. See + * xStreamBufferCreate() for a version that uses dynamically allocated memory. + * + * configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h for + * xStreamBufferCreateStatic() to be available. + * + * @param xBufferSizeBytes The size, in bytes, of the buffer pointed to by the + * pucStreamBufferStorageArea parameter. + * + * @param xTriggerLevelBytes The number of bytes that must be in the stream + * buffer before a task that is blocked on the stream buffer to wait for data is + * moved out of the blocked state. For example, if a task is blocked on a read + * of an empty stream buffer that has a trigger level of 1 then the task will be + * unblocked when a single byte is written to the buffer or the task's block + * time expires. As another example, if a task is blocked on a read of an empty + * stream buffer that has a trigger level of 10 then the task will not be + * unblocked until the stream buffer contains at least 10 bytes or the task's + * block time expires. If a reading task's block time expires before the + * trigger level is reached then the task will still receive however many bytes + * are actually available. Setting a trigger level of 0 will result in a + * trigger level of 1 being used. It is not valid to specify a trigger level + * that is greater than the buffer size. + * + * @param pucStreamBufferStorageArea Must point to a uint8_t array that is at + * least xBufferSizeBytes + 1 big. This is the array to which streams are + * copied when they are written to the stream buffer. + * + * @param pxStaticStreamBuffer Must point to a variable of type + * StaticStreamBuffer_t, which will be used to hold the stream buffer's data + * structure. + * + * @return If the stream buffer is created successfully then a handle to the + * created stream buffer is returned. If either pucStreamBufferStorageArea or + * pxStaticstreamBuffer are NULL then NULL is returned. + * + * Example use: ++ +// Used to dimension the array used to hold the streams. The available space +// will actually be one less than this, so 999. +#define STORAGE_SIZE_BYTES 1000 + +// Defines the memory that will actually hold the streams within the stream +// buffer. +static uint8_t ucStorageBuffer[ STORAGE_SIZE_BYTES ]; + +// The variable used to hold the stream buffer structure. +StaticStreamBuffer_t xStreamBufferStruct; + +void MyFunction( void ) +{ +StreamBufferHandle_t xStreamBuffer; +const size_t xTriggerLevel = 1; + + xStreamBuffer = xStreamBufferCreateStatic( sizeof( ucBufferStorage ), + xTriggerLevel, + ucBufferStorage, + &xStreamBufferStruct ); + + // As neither the pucStreamBufferStorageArea or pxStaticStreamBuffer + // parameters were NULL, xStreamBuffer will not be NULL, and can be used to + // reference the created stream buffer in other stream buffer API calls. + + // Other code that uses the stream buffer can go here. +} + ++ * \defgroup xStreamBufferCreateStatic xStreamBufferCreateStatic + * \ingroup StreamBufferManagement + */ +#define xStreamBufferCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pucStreamBufferStorageArea, pxStaticStreamBuffer ) xStreamBufferGenericCreateStatic( xBufferSizeBytes, xTriggerLevelBytes, pdFALSE, pucStreamBufferStorageArea, pxStaticStreamBuffer ) + +/** + * stream_buffer.h + * ++size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ); ++ * + * Sends bytes to a stream buffer. The bytes are copied into the stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferSend() to write to a stream buffer from a task. Use + * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt + * service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer to which a stream is + * being sent. + * + * @param pvTxData A pointer to the buffer that holds the bytes to be copied + * into the stream buffer. + * + * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData + * into the stream buffer. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for enough space to become available in the stream + * buffer, should the stream buffer contain too little space to hold the + * another xDataLengthBytes bytes. The block time is specified in tick periods, + * so the absolute time it represents is dependent on the tick frequency. The + * macro pdMS_TO_TICKS() can be used to convert a time specified in milliseconds + * into a time specified in ticks. Setting xTicksToWait to portMAX_DELAY will + * cause the task to wait indefinitely (without timing out), provided + * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h. If a task times out + * before it can write all xDataLengthBytes into the buffer it will still write + * as many bytes as possible. A task does not use any CPU time when it is in + * the blocked state. + * + * @return The number of bytes written to the stream buffer. If a task times + * out before it can write all xDataLengthBytes into the buffer it will still + * write as many bytes as possible. + * + * Example use: ++void vAFunction( StreamBufferHandle_t xStreamBuffer ) +{ +size_t xBytesSent; +uint8_t ucArrayToSend[] = { 0, 1, 2, 3 }; +char *pcStringToSend = "String to send"; +const TickType_t x100ms = pdMS_TO_TICKS( 100 ); + + // Send an array to the stream buffer, blocking for a maximum of 100ms to + // wait for enough space to be available in the stream buffer. + xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) ucArrayToSend, sizeof( ucArrayToSend ), x100ms ); + + if( xBytesSent != sizeof( ucArrayToSend ) ) + { + // The call to xStreamBufferSend() times out before there was enough + // space in the buffer for the data to be written, but it did + // successfully write xBytesSent bytes. + } + + // Send the string to the stream buffer. Return immediately if there is not + // enough space in the buffer. + xBytesSent = xStreamBufferSend( xStreamBuffer, ( void * ) pcStringToSend, strlen( pcStringToSend ), 0 ); + + if( xBytesSent != strlen( pcStringToSend ) ) + { + // The entire string could not be added to the stream buffer because + // there was not enough free space in the buffer, but xBytesSent bytes + // were sent. Could try again to send the remaining bytes. + } +} ++ * \defgroup xStreamBufferSend xStreamBufferSend + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + BaseType_t *pxHigherPriorityTaskWoken ); ++ * + * Interrupt safe version of the API function that sends a stream of bytes to + * the stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferSend() to write to a stream buffer from a task. Use + * xStreamBufferSendFromISR() to write to a stream buffer from an interrupt + * service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer to which a stream is + * being sent. + * + * @param pvTxData A pointer to the data that is to be copied into the stream + * buffer. + * + * @param xDataLengthBytes The maximum number of bytes to copy from pvTxData + * into the stream buffer. + * + * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will + * have a task blocked on it waiting for data. Calling + * xStreamBufferSendFromISR() can make data available, and so cause a task that + * was waiting for data to leave the Blocked state. If calling + * xStreamBufferSendFromISR() causes a task to leave the Blocked state, and the + * unblocked task has a priority higher than the currently executing task (the + * task that was interrupted), then, internally, xStreamBufferSendFromISR() + * will set *pxHigherPriorityTaskWoken to pdTRUE. If + * xStreamBufferSendFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. This will + * ensure that the interrupt returns directly to the highest priority Ready + * state task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it + * is passed into the function. See the example code below for an example. + * + * @return The number of bytes actually written to the stream buffer, which will + * be less than xDataLengthBytes if the stream buffer didn't have enough free + * space for all the bytes to be written. + * + * Example use: ++// A stream buffer that has already been created. +StreamBufferHandle_t xStreamBuffer; + +void vAnInterruptServiceRoutine( void ) +{ +size_t xBytesSent; +char *pcStringToSend = "String to send"; +BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + + // Attempt to send the string to the stream buffer. + xBytesSent = xStreamBufferSendFromISR( xStreamBuffer, + ( void * ) pcStringToSend, + strlen( pcStringToSend ), + &xHigherPriorityTaskWoken ); + + if( xBytesSent != strlen( pcStringToSend ) ) + { + // There was not enough free space in the stream buffer for the entire + // string to be written, ut xBytesSent bytes were written. + } + + // If xHigherPriorityTaskWoken was set to pdTRUE inside + // xStreamBufferSendFromISR() then a task that has a priority above the + // priority of the currently executing task was unblocked and a context + // switch should be performed to ensure the ISR returns to the unblocked + // task. In most FreeRTOS ports this is done by simply passing + // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the + // variables value, and perform the context switch if necessary. Check the + // documentation for the port in use for port specific instructions. + taskYIELD_FROM_ISR( xHigherPriorityTaskWoken ); +} ++ * \defgroup xStreamBufferSendFromISR xStreamBufferSendFromISR + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ); ++ * + * Receives bytes from a stream buffer. + * + * ***NOTE***: Uniquely among FreeRTOS objects, the stream buffer + * implementation (so also the message buffer implementation, as message buffers + * are built on top of stream buffers) assumes there is only one task or + * interrupt that will write to the buffer (the writer), and only one task or + * interrupt that will read from the buffer (the reader). It is safe for the + * writer and reader to be different tasks or interrupts, but, unlike other + * FreeRTOS objects, it is not safe to have multiple different writers or + * multiple different readers. If there are to be multiple different writers + * then the application writer must place each call to a writing API function + * (such as xStreamBufferSend()) inside a critical section and set the send + * block time to 0. Likewise, if there are to be multiple different readers + * then the application writer must place each call to a reading API function + * (such as xStreamBufferReceive()) inside a critical section and set the receive + * block time to 0. + * + * Use xStreamBufferReceive() to read from a stream buffer from a task. Use + * xStreamBufferReceiveFromISR() to read from a stream buffer from an + * interrupt service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer from which bytes are to + * be received. + * + * @param pvRxData A pointer to the buffer into which the received bytes will be + * copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the + * pvRxData parameter. This sets the maximum number of bytes to receive in one + * call. xStreamBufferReceive will return as many bytes as possible up to a + * maximum set by xBufferLengthBytes. + * + * @param xTicksToWait The maximum amount of time the task should remain in the + * Blocked state to wait for data to become available if the stream buffer is + * empty. xStreamBufferReceive() will return immediately if xTicksToWait is + * zero. The block time is specified in tick periods, so the absolute time it + * represents is dependent on the tick frequency. The macro pdMS_TO_TICKS() can + * be used to convert a time specified in milliseconds into a time specified in + * ticks. Setting xTicksToWait to portMAX_DELAY will cause the task to wait + * indefinitely (without timing out), provided INCLUDE_vTaskSuspend is set to 1 + * in FreeRTOSConfig.h. A task does not use any CPU time when it is in the + * Blocked state. + * + * @return The number of bytes actually read from the stream buffer, which will + * be less than xBufferLengthBytes if the call to xStreamBufferReceive() timed + * out before xBufferLengthBytes were available. + * + * Example use: ++void vAFunction( StreamBuffer_t xStreamBuffer ) +{ +uint8_t ucRxData[ 20 ]; +size_t xReceivedBytes; +const TickType_t xBlockTime = pdMS_TO_TICKS( 20 ); + + // Receive up to another sizeof( ucRxData ) bytes from the stream buffer. + // Wait in the Blocked state (so not using any CPU processing time) for a + // maximum of 100ms for the full sizeof( ucRxData ) number of bytes to be + // available. + xReceivedBytes = xStreamBufferReceive( xStreamBuffer, + ( void * ) ucRxData, + sizeof( ucRxData ), + xBlockTime ); + + if( xReceivedBytes > 0 ) + { + // A ucRxData contains another xRecievedBytes bytes of data, which can + // be processed here.... + } +} ++ * \defgroup xStreamBufferReceive xStreamBufferReceive + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + BaseType_t *pxHigherPriorityTaskWoken ); ++ * + * An interrupt safe version of the API function that receives bytes from a + * stream buffer. + * + * Use xStreamBufferReceive() to read bytes from a stream buffer from a task. + * Use xStreamBufferReceiveFromISR() to read bytes from a stream buffer from an + * interrupt service routine (ISR). + * + * @param xStreamBuffer The handle of the stream buffer from which a stream + * is being received. + * + * @param pvRxData A pointer to the buffer into which the received bytes are + * copied. + * + * @param xBufferLengthBytes The length of the buffer pointed to by the + * pvRxData parameter. This sets the maximum number of bytes to receive in one + * call. xStreamBufferReceive will return as many bytes as possible up to a + * maximum set by xBufferLengthBytes. + * + * @param pxHigherPriorityTaskWoken It is possible that a stream buffer will + * have a task blocked on it waiting for space to become available. Calling + * xStreamBufferReceiveFromISR() can make space available, and so cause a task + * that is waiting for space to leave the Blocked state. If calling + * xStreamBufferReceiveFromISR() causes a task to leave the Blocked state, and + * the unblocked task has a priority higher than the currently executing task + * (the task that was interrupted), then, internally, + * xStreamBufferReceiveFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE. + * If xStreamBufferReceiveFromISR() sets this value to pdTRUE, then normally a + * context switch should be performed before the interrupt is exited. That will + * ensure the interrupt returns directly to the highest priority Ready state + * task. *pxHigherPriorityTaskWoken should be set to pdFALSE before it is + * passed into the function. See the code example below for an example. + * + * @return The number of bytes read from the stream buffer, if any. + * + * Example use: ++// A stream buffer that has already been created. +StreamBuffer_t xStreamBuffer; + +void vAnInterruptServiceRoutine( void ) +{ +uint8_t ucRxData[ 20 ]; +size_t xReceivedBytes; +BaseType_t xHigherPriorityTaskWoken = pdFALSE; // Initialised to pdFALSE. + + // Receive the next stream from the stream buffer. + xReceivedBytes = xStreamBufferReceiveFromISR( xStreamBuffer, + ( void * ) ucRxData, + sizeof( ucRxData ), + &xHigherPriorityTaskWoken ); + + if( xReceivedBytes > 0 ) + { + // ucRxData contains xReceivedBytes read from the stream buffer. + // Process the stream here.... + } + + // If xHigherPriorityTaskWoken was set to pdTRUE inside + // xStreamBufferReceiveFromISR() then a task that has a priority above the + // priority of the currently executing task was unblocked and a context + // switch should be performed to ensure the ISR returns to the unblocked + // task. In most FreeRTOS ports this is done by simply passing + // xHigherPriorityTaskWoken into taskYIELD_FROM_ISR(), which will test the + // variables value, and perform the context switch if necessary. Check the + // documentation for the port in use for port specific instructions. + taskYIELD_FROM_ISR( xHigherPriorityTaskWoken ); +} ++ * \defgroup xStreamBufferReceiveFromISR xStreamBufferReceiveFromISR + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ); ++ * + * Deletes a stream buffer that was previously created using a call to + * xStreamBufferCreate() or xStreamBufferCreateStatic(). If the stream + * buffer was created using dynamic memory (that is, by xStreamBufferCreate()), + * then the allocated memory is freed. + * + * A stream buffer handle must not be used after the stream buffer has been + * deleted. + * + * @param xStreamBuffer The handle of the stream buffer to be deleted. + * + * \defgroup vStreamBufferDelete vStreamBufferDelete + * \ingroup StreamBufferManagement + */ +void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ); ++ * + * Queries a stream buffer to see if it is full. A stream buffer is full if it + * does not have any free space, and therefore cannot accept any more data. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return If the stream buffer is full then pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \defgroup xStreamBufferIsFull xStreamBufferIsFull + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ); ++ * + * Queries a stream buffer to see if it is empty. A stream buffer is empty if + * it does not contain any data. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return If the stream buffer is empty then pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \defgroup xStreamBufferIsEmpty xStreamBufferIsEmpty + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ); ++ * + * Resets a stream buffer to its initial, empty, state. Any data that was in + * the stream buffer is discarded. A stream buffer can only be reset if there + * are no tasks blocked waiting to either send to or receive from the stream + * buffer. + * + * @param xStreamBuffer The handle of the stream buffer being reset. + * + * @return If the stream buffer is reset then pdPASS is returned. If there was + * a task blocked waiting to send to or read from the stream buffer then the + * stream buffer is not reset and pdFAIL is returned. + * + * \defgroup xStreamBufferReset xStreamBufferReset + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ); ++ * + * Queries a stream buffer to see how much free space it contains, which is + * equal to the amount of data that can be sent to the stream buffer before it + * is full. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return The number of bytes that can be written to the stream buffer before + * the stream buffer would be full. + * + * \defgroup xStreamBufferSpacesAvailable xStreamBufferSpacesAvailable + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ); ++ * + * Queries a stream buffer to see how much data it contains, which is equal to + * the number of bytes that can be read from the stream buffer before the stream + * buffer would be empty. + * + * @param xStreamBuffer The handle of the stream buffer being queried. + * + * @return The number of bytes that can be read from the stream buffer before + * the stream buffer would be empty. + * + * \defgroup xStreamBufferBytesAvailable xStreamBufferBytesAvailable + * \ingroup StreamBufferManagement + */ +size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ); ++ * + * A stream buffer's trigger level is the number of bytes that must be in the + * stream buffer before a task that is blocked on the stream buffer to + * wait for data is moved out of the blocked state. For example, if a task is + * blocked on a read of an empty stream buffer that has a trigger level of 1 + * then the task will be unblocked when a single byte is written to the buffer + * or the task's block time expires. As another example, if a task is blocked + * on a read of an empty stream buffer that has a trigger level of 10 then the + * task will not be unblocked until the stream buffer contains at least 10 bytes + * or the task's block time expires. If a reading task's block time expires + * before the trigger level is reached then the task will still receive however + * many bytes are actually available. Setting a trigger level of 0 will result + * in a trigger level of 1 being used. It is not valid to specify a trigger + * level that is greater than the buffer size. + * + * A trigger level is set when the stream buffer is created, and can be modified + * using xStreamBufferSetTriggerLevel(). + * + * @param xStreamBuffer The handle of the stream buffer being updated. + * + * @param xTriggerLevel The new trigger level for the stream buffer. + * + * @return If xTriggerLevel was less than or equal to the stream buffer's length + * then the trigger level will be updated and pdTRUE is returned. Otherwise + * pdFALSE is returned. + * + * \defgroup xStreamBufferSetTriggerLevel xStreamBufferSetTriggerLevel + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ); ++ * + * For advanced users only. + * + * The sbSEND_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is sent to a message buffer or stream buffer. If there was a task that + * was blocked on the message or stream buffer waiting for data to arrive then + * the sbSEND_COMPLETED() macro sends a notification to the task to remove it + * from the Blocked state. xStreamBufferSendCompletedFromISR() does the same + * thing. It is provided to enable application writers to implement their own + * version of sbSEND_COMPLETED(), and MUST NOT BE USED AT ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xStreamBuffer The handle of the stream buffer to which data was + * written. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xStreamBufferSendCompletedFromISR(). If calling + * xStreamBufferSendCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xStreamBufferSendCompletedFromISR xStreamBufferSendCompletedFromISR + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * stream_buffer.h + * ++BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ); ++ * + * For advanced users only. + * + * The sbRECEIVE_COMPLETED() macro is called from within the FreeRTOS APIs when + * data is read out of a message buffer or stream buffer. If there was a task + * that was blocked on the message or stream buffer waiting for data to arrive + * then the sbRECEIVE_COMPLETED() macro sends a notification to the task to + * remove it from the Blocked state. xStreamBufferReceiveCompletedFromISR() + * does the same thing. It is provided to enable application writers to + * implement their own version of sbRECEIVE_COMPLETED(), and MUST NOT BE USED AT + * ANY OTHER TIME. + * + * See the example implemented in FreeRTOS/Demo/Minimal/MessageBufferAMP.c for + * additional information. + * + * @param xStreamBuffer The handle of the stream buffer from which data was + * read. + * + * @param pxHigherPriorityTaskWoken *pxHigherPriorityTaskWoken should be + * initialised to pdFALSE before it is passed into + * xStreamBufferReceiveCompletedFromISR(). If calling + * xStreamBufferReceiveCompletedFromISR() removes a task from the Blocked state, + * and the task has a priority above the priority of the currently running task, + * then *pxHigherPriorityTaskWoken will get set to pdTRUE indicating that a + * context switch should be performed before exiting the ISR. + * + * @return If a task was removed from the Blocked state then pdTRUE is returned. + * Otherwise pdFALSE is returned. + * + * \defgroup xStreamBufferReceiveCompletedFromISR xStreamBufferReceiveCompletedFromISR + * \ingroup StreamBufferManagement + */ +BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/* Functions below here are not part of the public API. */ +StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer ) PRIVILEGED_FUNCTION; + +StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) PRIVILEGED_FUNCTION; + +size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + +#if( configUSE_TRACE_FACILITY == 1 ) + void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; + uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) PRIVILEGED_FUNCTION; +#endif + +#if defined( __cplusplus ) +} +#endif + +#endif /* !defined( STREAM_BUFFER_H ) */ diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/task.h b/Middlewares/Third_Party/FreeRTOS/Source/include/task.h new file mode 100644 index 0000000..b0cc60b --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/task.h @@ -0,0 +1,2543 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +#ifndef INC_TASK_H +#define INC_TASK_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include task.h" +#endif + +#include "list.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/*----------------------------------------------------------- + * MACROS AND DEFINITIONS + *----------------------------------------------------------*/ + +#define tskKERNEL_VERSION_NUMBER "V10.3.1" +#define tskKERNEL_VERSION_MAJOR 10 +#define tskKERNEL_VERSION_MINOR 3 +#define tskKERNEL_VERSION_BUILD 1 + +/* MPU region parameters passed in ulParameters + * of MemoryRegion_t struct. */ +#define tskMPU_REGION_READ_ONLY ( 1UL << 0UL ) +#define tskMPU_REGION_READ_WRITE ( 1UL << 1UL ) +#define tskMPU_REGION_EXECUTE_NEVER ( 1UL << 2UL ) +#define tskMPU_REGION_NORMAL_MEMORY ( 1UL << 3UL ) +#define tskMPU_REGION_DEVICE_MEMORY ( 1UL << 4UL ) + +/** + * task. h + * + * Type by which tasks are referenced. For example, a call to xTaskCreate + * returns (via a pointer parameter) an TaskHandle_t variable that can then + * be used as a parameter to vTaskDelete to delete the task. + * + * \defgroup TaskHandle_t TaskHandle_t + * \ingroup Tasks + */ +struct tskTaskControlBlock; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct tskTaskControlBlock* TaskHandle_t; + +/* + * Defines the prototype to which the application task hook function must + * conform. + */ +typedef BaseType_t (*TaskHookFunction_t)( void * ); + +/* Task states returned by eTaskGetState. */ +typedef enum +{ + eRunning = 0, /* A task is querying the state of itself, so must be running. */ + eReady, /* The task being queried is in a read or pending ready list. */ + eBlocked, /* The task being queried is in the Blocked state. */ + eSuspended, /* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */ + eDeleted, /* The task being queried has been deleted, but its TCB has not yet been freed. */ + eInvalid /* Used as an 'invalid state' value. */ +} eTaskState; + +/* Actions that can be performed when vTaskNotify() is called. */ +typedef enum +{ + eNoAction = 0, /* Notify the task without updating its notify value. */ + eSetBits, /* Set bits in the task's notification value. */ + eIncrement, /* Increment the task's notification value. */ + eSetValueWithOverwrite, /* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */ + eSetValueWithoutOverwrite /* Set the task's notification value if the previous value has been read by the task. */ +} eNotifyAction; + +/* + * Used internally only. + */ +typedef struct xTIME_OUT +{ + BaseType_t xOverflowCount; + TickType_t xTimeOnEntering; +} TimeOut_t; + +/* + * Defines the memory ranges allocated to the task when an MPU is used. + */ +typedef struct xMEMORY_REGION +{ + void *pvBaseAddress; + uint32_t ulLengthInBytes; + uint32_t ulParameters; +} MemoryRegion_t; + +/* + * Parameters required to create an MPU protected task. + */ +typedef struct xTASK_PARAMETERS +{ + TaskFunction_t pvTaskCode; + const char * const pcName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + configSTACK_DEPTH_TYPE usStackDepth; + void *pvParameters; + UBaseType_t uxPriority; + StackType_t *puxStackBuffer; + MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ]; + #if ( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + StaticTask_t * const pxTaskBuffer; + #endif +} TaskParameters_t; + +/* Used with the uxTaskGetSystemState() function to return the state of each task +in the system. */ +typedef struct xTASK_STATUS +{ + TaskHandle_t xHandle; /* The handle of the task to which the rest of the information in the structure relates. */ + const char *pcTaskName; /* A pointer to the task's name. This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + UBaseType_t xTaskNumber; /* A number unique to the task. */ + eTaskState eCurrentState; /* The state in which the task existed when the structure was populated. */ + UBaseType_t uxCurrentPriority; /* The priority at which the task was running (may be inherited) when the structure was populated. */ + UBaseType_t uxBasePriority; /* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex. Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */ + uint32_t ulRunTimeCounter; /* The total run time allocated to the task so far, as defined by the run time stats clock. See http://www.freertos.org/rtos-run-time-stats.html. Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */ + StackType_t *pxStackBase; /* Points to the lowest address of the task's stack area. */ + configSTACK_DEPTH_TYPE usStackHighWaterMark; /* The minimum amount of stack space that has remained for the task since the task was created. The closer this value is to zero the closer the task has come to overflowing its stack. */ +} TaskStatus_t; + +/* Possible return values for eTaskConfirmSleepModeStatus(). */ +typedef enum +{ + eAbortSleep = 0, /* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */ + eStandardSleep, /* Enter a sleep mode that will not last any longer than the expected idle time. */ + eNoTasksWaitingTimeout /* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */ +} eSleepModeStatus; + +/** + * Defines the priority used by the idle task. This must not be modified. + * + * \ingroup TaskUtils + */ +#define tskIDLE_PRIORITY ( ( UBaseType_t ) 0U ) + +/** + * task. h + * + * Macro for forcing a context switch. + * + * \defgroup taskYIELD taskYIELD + * \ingroup SchedulerControl + */ +#define taskYIELD() portYIELD() + +/** + * task. h + * + * Macro to mark the start of a critical code region. Preemptive context + * switches cannot occur when in a critical region. + * + * NOTE: This may alter the stack (depending on the portable implementation) + * so must be used with care! + * + * \defgroup taskENTER_CRITICAL taskENTER_CRITICAL + * \ingroup SchedulerControl + */ +#define taskENTER_CRITICAL() portENTER_CRITICAL() +#define taskENTER_CRITICAL_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR() + +/** + * task. h + * + * Macro to mark the end of a critical code region. Preemptive context + * switches cannot occur when in a critical region. + * + * NOTE: This may alter the stack (depending on the portable implementation) + * so must be used with care! + * + * \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL + * \ingroup SchedulerControl + */ +#define taskEXIT_CRITICAL() portEXIT_CRITICAL() +#define taskEXIT_CRITICAL_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( x ) +/** + * task. h + * + * Macro to disable all maskable interrupts. + * + * \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS + * \ingroup SchedulerControl + */ +#define taskDISABLE_INTERRUPTS() portDISABLE_INTERRUPTS() + +/** + * task. h + * + * Macro to enable microcontroller interrupts. + * + * \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS + * \ingroup SchedulerControl + */ +#define taskENABLE_INTERRUPTS() portENABLE_INTERRUPTS() + +/* Definitions returned by xTaskGetSchedulerState(). taskSCHEDULER_SUSPENDED is +0 to generate more optimal code when configASSERT() is defined as the constant +is used in assert() statements. */ +#define taskSCHEDULER_SUSPENDED ( ( BaseType_t ) 0 ) +#define taskSCHEDULER_NOT_STARTED ( ( BaseType_t ) 1 ) +#define taskSCHEDULER_RUNNING ( ( BaseType_t ) 2 ) + + +/*----------------------------------------------------------- + * TASK CREATION API + *----------------------------------------------------------*/ + +/** + * task. h + *+ BaseType_t xTaskCreate( + TaskFunction_t pvTaskCode, + const char * const pcName, + configSTACK_DEPTH_TYPE usStackDepth, + void *pvParameters, + UBaseType_t uxPriority, + TaskHandle_t *pvCreatedTask + );+ * + * Create a new task and add it to the list of tasks that are ready to run. + * + * Internally, within the FreeRTOS implementation, tasks use two blocks of + * memory. The first block is used to hold the task's data structures. The + * second block is used by the task as its stack. If a task is created using + * xTaskCreate() then both blocks of memory are automatically dynamically + * allocated inside the xTaskCreate() function. (see + * http://www.freertos.org/a00111.html). If a task is created using + * xTaskCreateStatic() then the application writer must provide the required + * memory. xTaskCreateStatic() therefore allows a task to be created without + * using any dynamic memory allocation. + * + * See xTaskCreateStatic() for a version that does not use any dynamic memory + * allocation. + * + * xTaskCreate() can only be used to create a task that has unrestricted + * access to the entire microcontroller memory map. Systems that include MPU + * support can alternatively create an MPU constrained task using + * xTaskCreateRestricted(). + * + * @param pvTaskCode Pointer to the task entry function. Tasks + * must be implemented to never return (i.e. continuous loop). + * + * @param pcName A descriptive name for the task. This is mainly used to + * facilitate debugging. Max length defined by configMAX_TASK_NAME_LEN - default + * is 16. + * + * @param usStackDepth The size of the task stack specified as the number of + * variables the stack can hold - not the number of bytes. For example, if + * the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes + * will be allocated for stack storage. + * + * @param pvParameters Pointer that will be used as the parameter for the task + * being created. + * + * @param uxPriority The priority at which the task should run. Systems that + * include MPU support can optionally create tasks in a privileged (system) + * mode by setting bit portPRIVILEGE_BIT of the priority parameter. For + * example, to create a privileged task at priority 2 the uxPriority parameter + * should be set to ( 2 | portPRIVILEGE_BIT ). + * + * @param pvCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * @return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * Example usage: ++ // Task to be created. + void vTaskCode( void * pvParameters ) + { + for( ;; ) + { + // Task code goes here. + } + } + + // Function that creates a task. + void vOtherFunction( void ) + { + static uint8_t ucParameterToPass; + TaskHandle_t xHandle = NULL; + + // Create the task, storing the handle. Note that the passed parameter ucParameterToPass + // must exist for the lifetime of the task, so in this case is declared static. If it was just an + // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time + // the new task attempts to access it. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle ); + configASSERT( xHandle ); + + // Use the handle to delete the task. + if( xHandle != NULL ) + { + vTaskDelete( xHandle ); + } + } ++ * \defgroup xTaskCreate xTaskCreate + * \ingroup Tasks + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const configSTACK_DEPTH_TYPE usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif + +/** + * task. h + *+ TaskHandle_t xTaskCreateStatic( TaskFunction_t pvTaskCode, + const char * const pcName, + uint32_t ulStackDepth, + void *pvParameters, + UBaseType_t uxPriority, + StackType_t *pxStackBuffer, + StaticTask_t *pxTaskBuffer );+ * + * Create a new task and add it to the list of tasks that are ready to run. + * + * Internally, within the FreeRTOS implementation, tasks use two blocks of + * memory. The first block is used to hold the task's data structures. The + * second block is used by the task as its stack. If a task is created using + * xTaskCreate() then both blocks of memory are automatically dynamically + * allocated inside the xTaskCreate() function. (see + * http://www.freertos.org/a00111.html). If a task is created using + * xTaskCreateStatic() then the application writer must provide the required + * memory. xTaskCreateStatic() therefore allows a task to be created without + * using any dynamic memory allocation. + * + * @param pvTaskCode Pointer to the task entry function. Tasks + * must be implemented to never return (i.e. continuous loop). + * + * @param pcName A descriptive name for the task. This is mainly used to + * facilitate debugging. The maximum length of the string is defined by + * configMAX_TASK_NAME_LEN in FreeRTOSConfig.h. + * + * @param ulStackDepth The size of the task stack specified as the number of + * variables the stack can hold - not the number of bytes. For example, if + * the stack is 32-bits wide and ulStackDepth is defined as 100 then 400 bytes + * will be allocated for stack storage. + * + * @param pvParameters Pointer that will be used as the parameter for the task + * being created. + * + * @param uxPriority The priority at which the task will run. + * + * @param pxStackBuffer Must point to a StackType_t array that has at least + * ulStackDepth indexes - the array will then be used as the task's stack, + * removing the need for the stack to be allocated dynamically. + * + * @param pxTaskBuffer Must point to a variable of type StaticTask_t, which will + * then be used to hold the task's data structures, removing the need for the + * memory to be allocated dynamically. + * + * @return If neither pxStackBuffer or pxTaskBuffer are NULL, then the task will + * be created and a handle to the created task is returned. If either + * pxStackBuffer or pxTaskBuffer are NULL then the task will not be created and + * NULL is returned. + * + * Example usage: ++ + // Dimensions the buffer that the task being created will use as its stack. + // NOTE: This is the number of words the stack will hold, not the number of + // bytes. For example, if each stack item is 32-bits, and this is set to 100, + // then 400 bytes (100 * 32-bits) will be allocated. + #define STACK_SIZE 200 + + // Structure that will hold the TCB of the task being created. + StaticTask_t xTaskBuffer; + + // Buffer that the task being created will use as its stack. Note this is + // an array of StackType_t variables. The size of StackType_t is dependent on + // the RTOS port. + StackType_t xStack[ STACK_SIZE ]; + + // Function that implements the task being created. + void vTaskCode( void * pvParameters ) + { + // The parameter value is expected to be 1 as 1 is passed in the + // pvParameters value in the call to xTaskCreateStatic(). + configASSERT( ( uint32_t ) pvParameters == 1UL ); + + for( ;; ) + { + // Task code goes here. + } + } + + // Function that creates a task. + void vOtherFunction( void ) + { + TaskHandle_t xHandle = NULL; + + // Create the task without using any dynamic memory allocation. + xHandle = xTaskCreateStatic( + vTaskCode, // Function that implements the task. + "NAME", // Text name for the task. + STACK_SIZE, // Stack size in words, not bytes. + ( void * ) 1, // Parameter passed into the task. + tskIDLE_PRIORITY,// Priority at which the task is created. + xStack, // Array to use as the task's stack. + &xTaskBuffer ); // Variable to hold the task's data structure. + + // puxStackBuffer and pxTaskBuffer were not NULL, so the task will have + // been created, and xHandle will be the task's handle. Use the handle + // to suspend the task. + vTaskSuspend( xHandle ); + } ++ * \defgroup xTaskCreateStatic xTaskCreateStatic + * \ingroup Tasks + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * task. h + *+ BaseType_t xTaskCreateRestricted( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );+ * + * Only available when configSUPPORT_DYNAMIC_ALLOCATION is set to 1. + * + * xTaskCreateRestricted() should only be used in systems that include an MPU + * implementation. + * + * Create a new task and add it to the list of tasks that are ready to run. + * The function parameters define the memory regions and associated access + * permissions allocated to the task. + * + * See xTaskCreateRestrictedStatic() for a version that does not use any + * dynamic memory allocation. + * + * @param pxTaskDefinition Pointer to a structure that contains a member + * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API + * documentation) plus an optional stack buffer and the memory region + * definitions. + * + * @param pxCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * @return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * Example usage: ++// Create an TaskParameters_t structure that defines the task to be created. +static const TaskParameters_t xCheckTaskParameters = +{ + vATask, // pvTaskCode - the function that implements the task. + "ATask", // pcName - just a text name for the task to assist debugging. + 100, // usStackDepth - the stack size DEFINED IN WORDS. + NULL, // pvParameters - passed into the task function as the function parameters. + ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + + // xRegions - Allocate up to three separate memory regions for access by + // the task, with appropriate access permissions. Different processors have + // different memory alignment requirements - refer to the FreeRTOS documentation + // for full information. + { + // Base address Length Parameters + { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + } +}; + +int main( void ) +{ +TaskHandle_t xHandle; + + // Create a task from the const structure defined above. The task handle + // is requested (the second parameter is not NULL) but in this case just for + // demonstration purposes as its not actually used. + xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + + // Start the scheduler. + vTaskStartScheduler(); + + // Will only get here if there was insufficient memory to create the idle + // and/or timer task. + for( ;; ); +} ++ * \defgroup xTaskCreateRestricted xTaskCreateRestricted + * \ingroup Tasks + */ +#if( portUSING_MPU_WRAPPERS == 1 ) + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif + +/** + * task. h + *+ BaseType_t xTaskCreateRestrictedStatic( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );+ * + * Only available when configSUPPORT_STATIC_ALLOCATION is set to 1. + * + * xTaskCreateRestrictedStatic() should only be used in systems that include an + * MPU implementation. + * + * Internally, within the FreeRTOS implementation, tasks use two blocks of + * memory. The first block is used to hold the task's data structures. The + * second block is used by the task as its stack. If a task is created using + * xTaskCreateRestricted() then the stack is provided by the application writer, + * and the memory used to hold the task's data structure is automatically + * dynamically allocated inside the xTaskCreateRestricted() function. If a task + * is created using xTaskCreateRestrictedStatic() then the application writer + * must provide the memory used to hold the task's data structures too. + * xTaskCreateRestrictedStatic() therefore allows a memory protected task to be + * created without using any dynamic memory allocation. + * + * @param pxTaskDefinition Pointer to a structure that contains a member + * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API + * documentation) plus an optional stack buffer and the memory region + * definitions. If configSUPPORT_STATIC_ALLOCATION is set to 1 the structure + * contains an additional member, which is used to point to a variable of type + * StaticTask_t - which is then used to hold the task's data structure. + * + * @param pxCreatedTask Used to pass back a handle by which the created task + * can be referenced. + * + * @return pdPASS if the task was successfully created and added to a ready + * list, otherwise an error code defined in the file projdefs.h + * + * Example usage: ++// Create an TaskParameters_t structure that defines the task to be created. +// The StaticTask_t variable is only included in the structure when +// configSUPPORT_STATIC_ALLOCATION is set to 1. The PRIVILEGED_DATA macro can +// be used to force the variable into the RTOS kernel's privileged data area. +static PRIVILEGED_DATA StaticTask_t xTaskBuffer; +static const TaskParameters_t xCheckTaskParameters = +{ + vATask, // pvTaskCode - the function that implements the task. + "ATask", // pcName - just a text name for the task to assist debugging. + 100, // usStackDepth - the stack size DEFINED IN WORDS. + NULL, // pvParameters - passed into the task function as the function parameters. + ( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state. + cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack. + + // xRegions - Allocate up to three separate memory regions for access by + // the task, with appropriate access permissions. Different processors have + // different memory alignment requirements - refer to the FreeRTOS documentation + // for full information. + { + // Base address Length Parameters + { cReadWriteArray, 32, portMPU_REGION_READ_WRITE }, + { cReadOnlyArray, 32, portMPU_REGION_READ_ONLY }, + { cPrivilegedOnlyAccessArray, 128, portMPU_REGION_PRIVILEGED_READ_WRITE } + } + + &xTaskBuffer; // Holds the task's data structure. +}; + +int main( void ) +{ +TaskHandle_t xHandle; + + // Create a task from the const structure defined above. The task handle + // is requested (the second parameter is not NULL) but in this case just for + // demonstration purposes as its not actually used. + xTaskCreateRestricted( &xRegTest1Parameters, &xHandle ); + + // Start the scheduler. + vTaskStartScheduler(); + + // Will only get here if there was insufficient memory to create the idle + // and/or timer task. + for( ;; ); +} ++ * \defgroup xTaskCreateRestrictedStatic xTaskCreateRestrictedStatic + * \ingroup Tasks + */ +#if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) PRIVILEGED_FUNCTION; +#endif + +/** + * task. h + *+ void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions );+ * + * Memory regions are assigned to a restricted task when the task is created by + * a call to xTaskCreateRestricted(). These regions can be redefined using + * vTaskAllocateMPURegions(). + * + * @param xTask The handle of the task being updated. + * + * @param xRegions A pointer to an MemoryRegion_t structure that contains the + * new memory region definitions. + * + * Example usage: ++// Define an array of MemoryRegion_t structures that configures an MPU region +// allowing read/write access for 1024 bytes starting at the beginning of the +// ucOneKByte array. The other two of the maximum 3 definable regions are +// unused so set to zero. +static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] = +{ + // Base address Length Parameters + { ucOneKByte, 1024, portMPU_REGION_READ_WRITE }, + { 0, 0, 0 }, + { 0, 0, 0 } +}; + +void vATask( void *pvParameters ) +{ + // This task was created such that it has access to certain regions of + // memory as defined by the MPU configuration. At some point it is + // desired that these MPU regions are replaced with that defined in the + // xAltRegions const struct above. Use a call to vTaskAllocateMPURegions() + // for this purpose. NULL is used as the task handle to indicate that this + // function should modify the MPU regions of the calling task. + vTaskAllocateMPURegions( NULL, xAltRegions ); + + // Now the task can continue its function, but from this point on can only + // access its stack and the ucOneKByte array (unless any other statically + // defined or shared regions have been declared elsewhere). +} ++ * \defgroup xTaskCreateRestricted xTaskCreateRestricted + * \ingroup Tasks + */ +void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void vTaskDelete( TaskHandle_t xTask );+ * + * INCLUDE_vTaskDelete must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Remove a task from the RTOS real time kernel's management. The task being + * deleted will be removed from all ready, blocked, suspended and event lists. + * + * NOTE: The idle task is responsible for freeing the kernel allocated + * memory from tasks that have been deleted. It is therefore important that + * the idle task is not starved of microcontroller processing time if your + * application makes any calls to vTaskDelete (). Memory allocated by the + * task code is not automatically freed, and should be freed before the task + * is deleted. + * + * See the demo application file death.c for sample code that utilises + * vTaskDelete (). + * + * @param xTask The handle of the task to be deleted. Passing NULL will + * cause the calling task to be deleted. + * + * Example usage: ++ void vOtherFunction( void ) + { + TaskHandle_t xHandle; + + // Create the task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + + // Use the handle to delete the task. + vTaskDelete( xHandle ); + } ++ * \defgroup vTaskDelete vTaskDelete + * \ingroup Tasks + */ +void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- + * TASK CONTROL API + *----------------------------------------------------------*/ + +/** + * task. h + *void vTaskDelay( const TickType_t xTicksToDelay );+ * + * Delay a task for a given number of ticks. The actual time that the + * task remains blocked depends on the tick rate. The constant + * portTICK_PERIOD_MS can be used to calculate real time from the tick + * rate - with the resolution of one tick period. + * + * INCLUDE_vTaskDelay must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * + * vTaskDelay() specifies a time at which the task wishes to unblock relative to + * the time at which vTaskDelay() is called. For example, specifying a block + * period of 100 ticks will cause the task to unblock 100 ticks after + * vTaskDelay() is called. vTaskDelay() does not therefore provide a good method + * of controlling the frequency of a periodic task as the path taken through the + * code, as well as other task and interrupt activity, will effect the frequency + * at which vTaskDelay() gets called and therefore the time at which the task + * next executes. See vTaskDelayUntil() for an alternative API function designed + * to facilitate fixed frequency execution. It does this by specifying an + * absolute time (rather than a relative time) at which the calling task should + * unblock. + * + * @param xTicksToDelay The amount of time, in tick periods, that + * the calling task should block. + * + * Example usage: + + void vTaskFunction( void * pvParameters ) + { + // Block for 500ms. + const TickType_t xDelay = 500 / portTICK_PERIOD_MS; + + for( ;; ) + { + // Simply toggle the LED every 500ms, blocking between each toggle. + vToggleLED(); + vTaskDelay( xDelay ); + } + } + + * \defgroup vTaskDelay vTaskDelay + * \ingroup TaskCtrl + */ +void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void vTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement );+ * + * INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Delay a task until a specified time. This function can be used by periodic + * tasks to ensure a constant execution frequency. + * + * This function differs from vTaskDelay () in one important aspect: vTaskDelay () will + * cause a task to block for the specified number of ticks from the time vTaskDelay () is + * called. It is therefore difficult to use vTaskDelay () by itself to generate a fixed + * execution frequency as the time between a task starting to execute and that task + * calling vTaskDelay () may not be fixed [the task may take a different path though the + * code between calls, or may get interrupted or preempted a different number of times + * each time it executes]. + * + * Whereas vTaskDelay () specifies a wake time relative to the time at which the function + * is called, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to + * unblock. + * + * The constant portTICK_PERIOD_MS can be used to calculate real time from the tick + * rate - with the resolution of one tick period. + * + * @param pxPreviousWakeTime Pointer to a variable that holds the time at which the + * task was last unblocked. The variable must be initialised with the current time + * prior to its first use (see the example below). Following this the variable is + * automatically updated within vTaskDelayUntil (). + * + * @param xTimeIncrement The cycle time period. The task will be unblocked at + * time *pxPreviousWakeTime + xTimeIncrement. Calling vTaskDelayUntil with the + * same xTimeIncrement parameter value will cause the task to execute with + * a fixed interface period. + * + * Example usage: ++ // Perform an action every 10 ticks. + void vTaskFunction( void * pvParameters ) + { + TickType_t xLastWakeTime; + const TickType_t xFrequency = 10; + + // Initialise the xLastWakeTime variable with the current time. + xLastWakeTime = xTaskGetTickCount (); + for( ;; ) + { + // Wait for the next cycle. + vTaskDelayUntil( &xLastWakeTime, xFrequency ); + + // Perform action here. + } + } ++ * \defgroup vTaskDelayUntil vTaskDelayUntil + * \ingroup TaskCtrl + */ +void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION; + +/** + * task. h + *BaseType_t xTaskAbortDelay( TaskHandle_t xTask );+ * + * INCLUDE_xTaskAbortDelay must be defined as 1 in FreeRTOSConfig.h for this + * function to be available. + * + * A task will enter the Blocked state when it is waiting for an event. The + * event it is waiting for can be a temporal event (waiting for a time), such + * as when vTaskDelay() is called, or an event on an object, such as when + * xQueueReceive() or ulTaskNotifyTake() is called. If the handle of a task + * that is in the Blocked state is used in a call to xTaskAbortDelay() then the + * task will leave the Blocked state, and return from whichever function call + * placed the task into the Blocked state. + * + * There is no 'FromISR' version of this function as an interrupt would need to + * know which object a task was blocked on in order to know which actions to + * take. For example, if the task was blocked on a queue the interrupt handler + * would then need to know if the queue was locked. + * + * @param xTask The handle of the task to remove from the Blocked state. + * + * @return If the task referenced by xTask was not in the Blocked state then + * pdFAIL is returned. Otherwise pdPASS is returned. + * + * \defgroup xTaskAbortDelay xTaskAbortDelay + * \ingroup TaskCtrl + */ +BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task. h + *UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask );+ * + * INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Obtain the priority of any task. + * + * @param xTask Handle of the task to be queried. Passing a NULL + * handle results in the priority of the calling task being returned. + * + * @return The priority of xTask. + * + * Example usage: ++ void vAFunction( void ) + { + TaskHandle_t xHandle; + + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + + // ... + + // Use the handle to obtain the priority of the created task. + // It was created with tskIDLE_PRIORITY, but may have changed + // it itself. + if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY ) + { + // The task has changed it's priority. + } + + // ... + + // Is our priority higher than the created task? + if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) ) + { + // Our priority (obtained using NULL handle) is higher. + } + } ++ * \defgroup uxTaskPriorityGet uxTaskPriorityGet + * \ingroup TaskCtrl + */ +UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task. h + *UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask );+ * + * A version of uxTaskPriorityGet() that can be used from an ISR. + */ +UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task. h + *eTaskState eTaskGetState( TaskHandle_t xTask );+ * + * INCLUDE_eTaskGetState must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Obtain the state of any task. States are encoded by the eTaskState + * enumerated type. + * + * @param xTask Handle of the task to be queried. + * + * @return The state of xTask at the time the function was called. Note the + * state of the task might change between the function being called, and the + * functions return value being tested by the calling task. + */ +eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState );+ * + * configUSE_TRACE_FACILITY must be defined as 1 for this function to be + * available. See the configuration section for more information. + * + * Populates a TaskStatus_t structure with information about a task. + * + * @param xTask Handle of the task being queried. If xTask is NULL then + * information will be returned about the calling task. + * + * @param pxTaskStatus A pointer to the TaskStatus_t structure that will be + * filled with information about the task referenced by the handle passed using + * the xTask parameter. + * + * @xGetFreeStackSpace The TaskStatus_t structure contains a member to report + * the stack high water mark of the task being queried. Calculating the stack + * high water mark takes a relatively long time, and can make the system + * temporarily unresponsive - so the xGetFreeStackSpace parameter is provided to + * allow the high water mark checking to be skipped. The high watermark value + * will only be written to the TaskStatus_t structure if xGetFreeStackSpace is + * not set to pdFALSE; + * + * @param eState The TaskStatus_t structure contains a member to report the + * state of the task being queried. Obtaining the task state is not as fast as + * a simple assignment - so the eState parameter is provided to allow the state + * information to be omitted from the TaskStatus_t structure. To obtain state + * information then set eState to eInvalid - otherwise the value passed in + * eState will be reported as the task state in the TaskStatus_t structure. + * + * Example usage: ++ void vAFunction( void ) + { + TaskHandle_t xHandle; + TaskStatus_t xTaskDetails; + + // Obtain the handle of a task from its name. + xHandle = xTaskGetHandle( "Task_Name" ); + + // Check the handle is not NULL. + configASSERT( xHandle ); + + // Use the handle to obtain further information about the task. + vTaskGetInfo( xHandle, + &xTaskDetails, + pdTRUE, // Include the high water mark in xTaskDetails. + eInvalid ); // Include the task state in xTaskDetails. + } ++ * \defgroup vTaskGetInfo vTaskGetInfo + * \ingroup TaskCtrl + */ +void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority );+ * + * INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Set the priority of any task. + * + * A context switch will occur before the function returns if the priority + * being set is higher than the currently executing task. + * + * @param xTask Handle to the task for which the priority is being set. + * Passing a NULL handle results in the priority of the calling task being set. + * + * @param uxNewPriority The priority to which the task will be set. + * + * Example usage: ++ void vAFunction( void ) + { + TaskHandle_t xHandle; + + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + + // ... + + // Use the handle to raise the priority of the created task. + vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 ); + + // ... + + // Use a NULL handle to raise our priority to the same value. + vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 ); + } ++ * \defgroup vTaskPrioritySet vTaskPrioritySet + * \ingroup TaskCtrl + */ +void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void vTaskSuspend( TaskHandle_t xTaskToSuspend );+ * + * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Suspend any task. When suspended a task will never get any microcontroller + * processing time, no matter what its priority. + * + * Calls to vTaskSuspend are not accumulative - + * i.e. calling vTaskSuspend () twice on the same task still only requires one + * call to vTaskResume () to ready the suspended task. + * + * @param xTaskToSuspend Handle to the task being suspended. Passing a NULL + * handle will cause the calling task to be suspended. + * + * Example usage: ++ void vAFunction( void ) + { + TaskHandle_t xHandle; + + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + + // ... + + // Use the handle to suspend the created task. + vTaskSuspend( xHandle ); + + // ... + + // The created task will not run during this period, unless + // another task calls vTaskResume( xHandle ). + + //... + + + // Suspend ourselves. + vTaskSuspend( NULL ); + + // We cannot get here unless another task calls vTaskResume + // with our handle as the parameter. + } ++ * \defgroup vTaskSuspend vTaskSuspend + * \ingroup TaskCtrl + */ +void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void vTaskResume( TaskHandle_t xTaskToResume );+ * + * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available. + * See the configuration section for more information. + * + * Resumes a suspended task. + * + * A task that has been suspended by one or more calls to vTaskSuspend () + * will be made available for running again by a single call to + * vTaskResume (). + * + * @param xTaskToResume Handle to the task being readied. + * + * Example usage: ++ void vAFunction( void ) + { + TaskHandle_t xHandle; + + // Create a task, storing the handle. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle ); + + // ... + + // Use the handle to suspend the created task. + vTaskSuspend( xHandle ); + + // ... + + // The created task will not run during this period, unless + // another task calls vTaskResume( xHandle ). + + //... + + + // Resume the suspended task ourselves. + vTaskResume( xHandle ); + + // The created task will once again get microcontroller processing + // time in accordance with its priority within the system. + } ++ * \defgroup vTaskResume vTaskResume + * \ingroup TaskCtrl + */ +void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void xTaskResumeFromISR( TaskHandle_t xTaskToResume );+ * + * INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be + * available. See the configuration section for more information. + * + * An implementation of vTaskResume() that can be called from within an ISR. + * + * A task that has been suspended by one or more calls to vTaskSuspend () + * will be made available for running again by a single call to + * xTaskResumeFromISR (). + * + * xTaskResumeFromISR() should not be used to synchronise a task with an + * interrupt if there is a chance that the interrupt could arrive prior to the + * task being suspended - as this can lead to interrupts being missed. Use of a + * semaphore as a synchronisation mechanism would avoid this eventuality. + * + * @param xTaskToResume Handle to the task being readied. + * + * @return pdTRUE if resuming the task should result in a context switch, + * otherwise pdFALSE. This is used by the ISR to determine if a context switch + * may be required following the ISR. + * + * \defgroup vTaskResumeFromISR vTaskResumeFromISR + * \ingroup TaskCtrl + */ +BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- + * SCHEDULER CONTROL + *----------------------------------------------------------*/ + +/** + * task. h + *void vTaskStartScheduler( void );+ * + * Starts the real time kernel tick processing. After calling the kernel + * has control over which tasks are executed and when. + * + * See the demo application file main.c for an example of creating + * tasks and starting the kernel. + * + * Example usage: ++ void vAFunction( void ) + { + // Create at least one task before starting the kernel. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + + // Start the real time kernel with preemption. + vTaskStartScheduler (); + + // Will not get here unless a task calls vTaskEndScheduler () + } ++ * + * \defgroup vTaskStartScheduler vTaskStartScheduler + * \ingroup SchedulerControl + */ +void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void vTaskEndScheduler( void );+ * + * NOTE: At the time of writing only the x86 real mode port, which runs on a PC + * in place of DOS, implements this function. + * + * Stops the real time kernel tick. All created tasks will be automatically + * deleted and multitasking (either preemptive or cooperative) will + * stop. Execution then resumes from the point where vTaskStartScheduler () + * was called, as if vTaskStartScheduler () had just returned. + * + * See the demo application file main. c in the demo/PC directory for an + * example that uses vTaskEndScheduler (). + * + * vTaskEndScheduler () requires an exit function to be defined within the + * portable layer (see vPortEndScheduler () in port. c for the PC port). This + * performs hardware specific operations such as stopping the kernel tick. + * + * vTaskEndScheduler () will cause all of the resources allocated by the + * kernel to be freed - but will not free resources allocated by application + * tasks. + * + * Example usage: ++ void vTaskCode( void * pvParameters ) + { + for( ;; ) + { + // Task code goes here. + + // At some point we want to end the real time kernel processing + // so call ... + vTaskEndScheduler (); + } + } + + void vAFunction( void ) + { + // Create at least one task before starting the kernel. + xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL ); + + // Start the real time kernel with preemption. + vTaskStartScheduler (); + + // Will only get here when the vTaskCode () task has called + // vTaskEndScheduler (). When we get here we are back to single task + // execution. + } ++ * + * \defgroup vTaskEndScheduler vTaskEndScheduler + * \ingroup SchedulerControl + */ +void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void vTaskSuspendAll( void );+ * + * Suspends the scheduler without disabling interrupts. Context switches will + * not occur while the scheduler is suspended. + * + * After calling vTaskSuspendAll () the calling task will continue to execute + * without risk of being swapped out until a call to xTaskResumeAll () has been + * made. + * + * API functions that have the potential to cause a context switch (for example, + * vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler + * is suspended. + * + * Example usage: ++ void vTask1( void * pvParameters ) + { + for( ;; ) + { + // Task code goes here. + + // ... + + // At some point the task wants to perform a long operation during + // which it does not want to get swapped out. It cannot use + // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the + // operation may cause interrupts to be missed - including the + // ticks. + + // Prevent the real time kernel swapping out the task. + vTaskSuspendAll (); + + // Perform the operation here. There is no need to use critical + // sections as we have all the microcontroller processing time. + // During this time interrupts will still operate and the kernel + // tick count will be maintained. + + // ... + + // The operation is complete. Restart the kernel. + xTaskResumeAll (); + } + } ++ * \defgroup vTaskSuspendAll vTaskSuspendAll + * \ingroup SchedulerControl + */ +void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + *BaseType_t xTaskResumeAll( void );+ * + * Resumes scheduler activity after it was suspended by a call to + * vTaskSuspendAll(). + * + * xTaskResumeAll() only resumes the scheduler. It does not unsuspend tasks + * that were previously suspended by a call to vTaskSuspend(). + * + * @return If resuming the scheduler caused a context switch then pdTRUE is + * returned, otherwise pdFALSE is returned. + * + * Example usage: ++ void vTask1( void * pvParameters ) + { + for( ;; ) + { + // Task code goes here. + + // ... + + // At some point the task wants to perform a long operation during + // which it does not want to get swapped out. It cannot use + // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the + // operation may cause interrupts to be missed - including the + // ticks. + + // Prevent the real time kernel swapping out the task. + vTaskSuspendAll (); + + // Perform the operation here. There is no need to use critical + // sections as we have all the microcontroller processing time. + // During this time interrupts will still operate and the real + // time kernel tick count will be maintained. + + // ... + + // The operation is complete. Restart the kernel. We want to force + // a context switch - but there is no point if resuming the scheduler + // caused a context switch already. + if( !xTaskResumeAll () ) + { + taskYIELD (); + } + } + } ++ * \defgroup xTaskResumeAll xTaskResumeAll + * \ingroup SchedulerControl + */ +BaseType_t xTaskResumeAll( void ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- + * TASK UTILITIES + *----------------------------------------------------------*/ + +/** + * task. h + *TickType_t xTaskGetTickCount( void );+ * + * @return The count of ticks since vTaskStartScheduler was called. + * + * \defgroup xTaskGetTickCount xTaskGetTickCount + * \ingroup TaskUtils + */ +TickType_t xTaskGetTickCount( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + *TickType_t xTaskGetTickCountFromISR( void );+ * + * @return The count of ticks since vTaskStartScheduler was called. + * + * This is a version of xTaskGetTickCount() that is safe to be called from an + * ISR - provided that TickType_t is the natural word size of the + * microcontroller being used or interrupt nesting is either not supported or + * not being used. + * + * \defgroup xTaskGetTickCountFromISR xTaskGetTickCountFromISR + * \ingroup TaskUtils + */ +TickType_t xTaskGetTickCountFromISR( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + *uint16_t uxTaskGetNumberOfTasks( void );+ * + * @return The number of tasks that the real time kernel is currently managing. + * This includes all ready, blocked and suspended tasks. A task that + * has been deleted but not yet freed by the idle task will also be + * included in the count. + * + * \defgroup uxTaskGetNumberOfTasks uxTaskGetNumberOfTasks + * \ingroup TaskUtils + */ +UBaseType_t uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + *char *pcTaskGetName( TaskHandle_t xTaskToQuery );+ * + * @return The text (human readable) name of the task referenced by the handle + * xTaskToQuery. A task can query its own name by either passing in its own + * handle, or by setting xTaskToQuery to NULL. + * + * \defgroup pcTaskGetName pcTaskGetName + * \ingroup TaskUtils + */ +char *pcTaskGetName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * task. h + *TaskHandle_t xTaskGetHandle( const char *pcNameToQuery );+ * + * NOTE: This function takes a relatively long time to complete and should be + * used sparingly. + * + * @return The handle of the task that has the human readable name pcNameToQuery. + * NULL is returned if no matching name is found. INCLUDE_xTaskGetHandle + * must be set to 1 in FreeRTOSConfig.h for pcTaskGetHandle() to be available. + * + * \defgroup pcTaskGetHandle pcTaskGetHandle + * \ingroup TaskUtils + */ +TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * task.h + *UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask );+ * + * INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for + * this function to be available. + * + * Returns the high water mark of the stack associated with xTask. That is, + * the minimum free stack space there has been (in words, so on a 32 bit machine + * a value of 1 means 4 bytes) since the task started. The smaller the returned + * number the closer the task has come to overflowing its stack. + * + * uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + * same except for their return type. Using configSTACK_DEPTH_TYPE allows the + * user to determine the return type. It gets around the problem of the value + * overflowing on 8-bit types without breaking backward compatibility for + * applications that expect an 8-bit return type. + * + * @param xTask Handle of the task associated with the stack to be checked. + * Set xTask to NULL to check the stack of the calling task. + * + * @return The smallest amount of free stack space there has been (in words, so + * actual spaces on the stack rather than bytes) since the task referenced by + * xTask was created. + */ +UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/** + * task.h + *configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask );+ * + * INCLUDE_uxTaskGetStackHighWaterMark2 must be set to 1 in FreeRTOSConfig.h for + * this function to be available. + * + * Returns the high water mark of the stack associated with xTask. That is, + * the minimum free stack space there has been (in words, so on a 32 bit machine + * a value of 1 means 4 bytes) since the task started. The smaller the returned + * number the closer the task has come to overflowing its stack. + * + * uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + * same except for their return type. Using configSTACK_DEPTH_TYPE allows the + * user to determine the return type. It gets around the problem of the value + * overflowing on 8-bit types without breaking backward compatibility for + * applications that expect an 8-bit return type. + * + * @param xTask Handle of the task associated with the stack to be checked. + * Set xTask to NULL to check the stack of the calling task. + * + * @return The smallest amount of free stack space there has been (in words, so + * actual spaces on the stack rather than bytes) since the task referenced by + * xTask was created. + */ +configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/* When using trace macros it is sometimes necessary to include task.h before +FreeRTOS.h. When this is done TaskHookFunction_t will not yet have been defined, +so the following two prototypes will cause a compilation error. This can be +fixed by simply guarding against the inclusion of these two prototypes unless +they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration +constant. */ +#ifdef configUSE_APPLICATION_TASK_TAG + #if configUSE_APPLICATION_TASK_TAG == 1 + /** + * task.h + *void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );+ * + * Sets pxHookFunction to be the task hook function used by the task xTask. + * Passing xTask as NULL has the effect of setting the calling tasks hook + * function. + */ + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION; + + /** + * task.h + *void xTaskGetApplicationTaskTag( TaskHandle_t xTask );+ * + * Returns the pxHookFunction value assigned to the task xTask. Do not + * call from an interrupt service routine - call + * xTaskGetApplicationTaskTagFromISR() instead. + */ + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + + /** + * task.h + *void xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask );+ * + * Returns the pxHookFunction value assigned to the task xTask. Can + * be called from an interrupt service routine. + */ + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + #endif /* configUSE_APPLICATION_TASK_TAG ==1 */ +#endif /* ifdef configUSE_APPLICATION_TASK_TAG */ + +#if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + + /* Each task contains an array of pointers that is dimensioned by the + configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h. The + kernel does not use the pointers itself, so the application writer can use + the pointers for any purpose they wish. The following two functions are + used to set and query a pointer respectively. */ + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) PRIVILEGED_FUNCTION; + void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) PRIVILEGED_FUNCTION; + +#endif + +/** + * task.h + *BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter );+ * + * Calls the hook function associated with xTask. Passing xTask as NULL has + * the effect of calling the Running tasks (the calling task) hook function. + * + * pvParameter is passed to the hook function for the task to interpret as it + * wants. The return value is the value returned by the task hook function + * registered by the user. + */ +BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) PRIVILEGED_FUNCTION; + +/** + * xTaskGetIdleTaskHandle() is only available if + * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h. + * + * Simply returns the handle of the idle task. It is not valid to call + * xTaskGetIdleTaskHandle() before the scheduler has been started. + */ +TaskHandle_t xTaskGetIdleTaskHandle( void ) PRIVILEGED_FUNCTION; + +/** + * configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for + * uxTaskGetSystemState() to be available. + * + * uxTaskGetSystemState() populates an TaskStatus_t structure for each task in + * the system. TaskStatus_t structures contain, among other things, members + * for the task handle, task name, task priority, task state, and total amount + * of run time consumed by the task. See the TaskStatus_t structure + * definition in this file for the full member list. + * + * NOTE: This function is intended for debugging use only as its use results in + * the scheduler remaining suspended for an extended period. + * + * @param pxTaskStatusArray A pointer to an array of TaskStatus_t structures. + * The array must contain at least one TaskStatus_t structure for each task + * that is under the control of the RTOS. The number of tasks under the control + * of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function. + * + * @param uxArraySize The size of the array pointed to by the pxTaskStatusArray + * parameter. The size is specified as the number of indexes in the array, or + * the number of TaskStatus_t structures contained in the array, not by the + * number of bytes in the array. + * + * @param pulTotalRunTime If configGENERATE_RUN_TIME_STATS is set to 1 in + * FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the + * total run time (as defined by the run time stats clock, see + * http://www.freertos.org/rtos-run-time-stats.html) since the target booted. + * pulTotalRunTime can be set to NULL to omit the total run time information. + * + * @return The number of TaskStatus_t structures that were populated by + * uxTaskGetSystemState(). This should equal the number returned by the + * uxTaskGetNumberOfTasks() API function, but will be zero if the value passed + * in the uxArraySize parameter was too small. + * + * Example usage: ++ // This example demonstrates how a human readable table of run time stats + // information is generated from raw data provided by uxTaskGetSystemState(). + // The human readable table is written to pcWriteBuffer + void vTaskGetRunTimeStats( char *pcWriteBuffer ) + { + TaskStatus_t *pxTaskStatusArray; + volatile UBaseType_t uxArraySize, x; + uint32_t ulTotalRunTime, ulStatsAsPercentage; + + // Make sure the write buffer does not contain a string. + *pcWriteBuffer = 0x00; + + // Take a snapshot of the number of tasks in case it changes while this + // function is executing. + uxArraySize = uxTaskGetNumberOfTasks(); + + // Allocate a TaskStatus_t structure for each task. An array could be + // allocated statically at compile time. + pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) ); + + if( pxTaskStatusArray != NULL ) + { + // Generate raw status information about each task. + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime ); + + // For percentage calculations. + ulTotalRunTime /= 100UL; + + // Avoid divide by zero errors. + if( ulTotalRunTime > 0 ) + { + // For each populated position in the pxTaskStatusArray array, + // format the raw data as human readable ASCII data + for( x = 0; x < uxArraySize; x++ ) + { + // What percentage of the total run time has the task used? + // This will always be rounded down to the nearest integer. + // ulTotalRunTimeDiv100 has already been divided by 100. + ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime; + + if( ulStatsAsPercentage > 0UL ) + { + sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); + } + else + { + // If the percentage is zero here then the task has + // consumed less than 1% of the total run time. + sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter ); + } + + pcWriteBuffer += strlen( ( char * ) pcWriteBuffer ); + } + } + + // The array is no longer needed, free the memory it consumes. + vPortFree( pxTaskStatusArray ); + } + } ++ */ +UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) PRIVILEGED_FUNCTION; + +/** + * task. h + *void vTaskList( char *pcWriteBuffer );+ * + * configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must + * both be defined as 1 for this function to be available. See the + * configuration section of the FreeRTOS.org website for more information. + * + * NOTE 1: This function will disable interrupts for its duration. It is + * not intended for normal application runtime use but as a debug aid. + * + * Lists all the current tasks, along with their current state and stack + * usage high water mark. + * + * Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or + * suspended ('S'). + * + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many of the + * demo applications. Do not consider it to be part of the scheduler. + * + * vTaskList() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that displays task + * names, states and stack usage. + * + * vTaskList() has a dependency on the sprintf() C library function that might + * bloat the code size, use a lot of stack, and provide different results on + * different platforms. An alternative, tiny, third party, and limited + * functionality implementation of sprintf() is provided in many of the + * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note + * printf-stdarg.c does not provide a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly through a + * call to vTaskList(). + * + * @param pcWriteBuffer A buffer into which the above mentioned details + * will be written, in ASCII form. This buffer is assumed to be large + * enough to contain the generated report. Approximately 40 bytes per + * task should be sufficient. + * + * \defgroup vTaskList vTaskList + * \ingroup TaskUtils + */ +void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * task. h + *void vTaskGetRunTimeStats( char *pcWriteBuffer );+ * + * configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS + * must both be defined as 1 for this function to be available. The application + * must also then provide definitions for + * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() + * to configure a peripheral timer/counter and return the timers current count + * value respectively. The counter should be at least 10 times the frequency of + * the tick count. + * + * NOTE 1: This function will disable interrupts for its duration. It is + * not intended for normal application runtime use but as a debug aid. + * + * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total + * accumulated execution time being stored for each task. The resolution + * of the accumulated time value depends on the frequency of the timer + * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. + * Calling vTaskGetRunTimeStats() writes the total execution time of each + * task into a buffer, both as an absolute count value and as a percentage + * of the total system execution time. + * + * NOTE 2: + * + * This function is provided for convenience only, and is used by many of the + * demo applications. Do not consider it to be part of the scheduler. + * + * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that displays the + * amount of time each task has spent in the Running state in both absolute and + * percentage terms. + * + * vTaskGetRunTimeStats() has a dependency on the sprintf() C library function + * that might bloat the code size, use a lot of stack, and provide different + * results on different platforms. An alternative, tiny, third party, and + * limited functionality implementation of sprintf() is provided in many of the + * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note + * printf-stdarg.c does not provide a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() directly + * to get access to raw stats data, rather than indirectly through a call to + * vTaskGetRunTimeStats(). + * + * @param pcWriteBuffer A buffer into which the execution times will be + * written, in ASCII form. This buffer is assumed to be large enough to + * contain the generated report. Approximately 40 bytes per task should + * be sufficient. + * + * \defgroup vTaskGetRunTimeStats vTaskGetRunTimeStats + * \ingroup TaskUtils + */ +void vTaskGetRunTimeStats( char *pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** +* task. h +*uint32_t ulTaskGetIdleRunTimeCounter( void );+* +* configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS +* must both be defined as 1 for this function to be available. The application +* must also then provide definitions for +* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE() +* to configure a peripheral timer/counter and return the timers current count +* value respectively. The counter should be at least 10 times the frequency of +* the tick count. +* +* Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total +* accumulated execution time being stored for each task. The resolution +* of the accumulated time value depends on the frequency of the timer +* configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro. +* While uxTaskGetSystemState() and vTaskGetRunTimeStats() writes the total +* execution time of each task into a buffer, ulTaskGetIdleRunTimeCounter() +* returns the total execution time of just the idle task. +* +* @return The total run time of the idle task. This is the amount of time the +* idle task has actually been executing. The unit of time is dependent on the +* frequency configured using the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and +* portGET_RUN_TIME_COUNTER_VALUE() macros. +* +* \defgroup ulTaskGetIdleRunTimeCounter ulTaskGetIdleRunTimeCounter +* \ingroup TaskUtils +*/ +uint32_t ulTaskGetIdleRunTimeCounter( void ) PRIVILEGED_FUNCTION; + +/** + * task. h + *BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction );+ * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was + * already in the Blocked state to wait for a notification when the notification + * arrives then the task will automatically be removed from the Blocked state + * (unblocked) and the notification cleared. + * + * A task can use xTaskNotifyWait() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTake() to [optionally] block + * to wait for its notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param ulValue Data that can be sent with the notification. How the data is + * used depends on the value of the eAction parameter. + * + * @param eAction Specifies how the notification updates the task's notification + * value, if at all. Valid values for eAction are as follows: + * + * eSetBits - + * The task's notification value is bitwise ORed with ulValue. xTaskNofify() + * always returns pdPASS in this case. + * + * eIncrement - + * The task's notification value is incremented. ulValue is not used and + * xTaskNotify() always returns pdPASS in this case. + * + * eSetValueWithOverwrite - + * The task's notification value is set to the value of ulValue, even if the + * task being notified had not yet processed the previous notification (the + * task already had a notification pending). xTaskNotify() always returns + * pdPASS in this case. + * + * eSetValueWithoutOverwrite - + * If the task being notified did not already have a notification pending then + * the task's notification value is set to ulValue and xTaskNotify() will + * return pdPASS. If the task being notified already had a notification + * pending then no action is performed and pdFAIL is returned. + * + * eNoAction - + * The task receives a notification without its notification value being + * updated. ulValue is not used and xTaskNotify() always returns pdPASS in + * this case. + * + * pulPreviousNotificationValue - + * Can be used to pass out the subject task's notification value before any + * bits are modified by the notify function. + * + * @return Dependent on the value of eAction. See the description of the + * eAction parameter. + * + * \defgroup xTaskNotify xTaskNotify + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) PRIVILEGED_FUNCTION; +#define xTaskNotify( xTaskToNotify, ulValue, eAction ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL ) +#define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) ) + +/** + * task. h + *BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );+ * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * A version of xTaskNotify() that can be used from an interrupt service routine + * (ISR). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was + * already in the Blocked state to wait for a notification when the notification + * arrives then the task will automatically be removed from the Blocked state + * (unblocked) and the notification cleared. + * + * A task can use xTaskNotifyWait() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTake() to [optionally] block + * to wait for its notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param ulValue Data that can be sent with the notification. How the data is + * used depends on the value of the eAction parameter. + * + * @param eAction Specifies how the notification updates the task's notification + * value, if at all. Valid values for eAction are as follows: + * + * eSetBits - + * The task's notification value is bitwise ORed with ulValue. xTaskNofify() + * always returns pdPASS in this case. + * + * eIncrement - + * The task's notification value is incremented. ulValue is not used and + * xTaskNotify() always returns pdPASS in this case. + * + * eSetValueWithOverwrite - + * The task's notification value is set to the value of ulValue, even if the + * task being notified had not yet processed the previous notification (the + * task already had a notification pending). xTaskNotify() always returns + * pdPASS in this case. + * + * eSetValueWithoutOverwrite - + * If the task being notified did not already have a notification pending then + * the task's notification value is set to ulValue and xTaskNotify() will + * return pdPASS. If the task being notified already had a notification + * pending then no action is performed and pdFAIL is returned. + * + * eNoAction - + * The task receives a notification without its notification value being + * updated. ulValue is not used and xTaskNotify() always returns pdPASS in + * this case. + * + * @param pxHigherPriorityTaskWoken xTaskNotifyFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the + * task to which the notification was sent to leave the Blocked state, and the + * unblocked task has a priority higher than the currently running task. If + * xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should + * be requested before the interrupt is exited. How a context switch is + * requested from an ISR is dependent on the port - see the documentation page + * for the port in use. + * + * @return Dependent on the value of eAction. See the description of the + * eAction parameter. + * + * \defgroup xTaskNotify xTaskNotify + * \ingroup TaskNotifications + */ +BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; +#define xTaskNotifyFromISR( xTaskToNotify, ulValue, eAction, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL, ( pxHigherPriorityTaskWoken ) ) +#define xTaskNotifyAndQueryFromISR( xTaskToNotify, ulValue, eAction, pulPreviousNotificationValue, pxHigherPriorityTaskWoken ) xTaskGenericNotifyFromISR( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotificationValue ), ( pxHigherPriorityTaskWoken ) ) + +/** + * task. h + *BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );+ * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * A notification sent to a task will remain pending until it is cleared by the + * task calling xTaskNotifyWait() or ulTaskNotifyTake(). If the task was + * already in the Blocked state to wait for a notification when the notification + * arrives then the task will automatically be removed from the Blocked state + * (unblocked) and the notification cleared. + * + * A task can use xTaskNotifyWait() to [optionally] block to wait for a + * notification to be pending, or ulTaskNotifyTake() to [optionally] block + * to wait for its notification value to have a non-zero value. The task does + * not consume any CPU time while it is in the Blocked state. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * @param ulBitsToClearOnEntry Bits that are set in ulBitsToClearOnEntry value + * will be cleared in the calling task's notification value before the task + * checks to see if any notifications are pending, and optionally blocks if no + * notifications are pending. Setting ulBitsToClearOnEntry to ULONG_MAX (if + * limits.h is included) or 0xffffffffUL (if limits.h is not included) will have + * the effect of resetting the task's notification value to 0. Setting + * ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged. + * + * @param ulBitsToClearOnExit If a notification is pending or received before + * the calling task exits the xTaskNotifyWait() function then the task's + * notification value (see the xTaskNotify() API function) is passed out using + * the pulNotificationValue parameter. Then any bits that are set in + * ulBitsToClearOnExit will be cleared in the task's notification value (note + * *pulNotificationValue is set before any bits are cleared). Setting + * ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL + * (if limits.h is not included) will have the effect of resetting the task's + * notification value to 0 before the function exits. Setting + * ulBitsToClearOnExit to 0 will leave the task's notification value unchanged + * when the function exits (in which case the value passed out in + * pulNotificationValue will match the task's notification value). + * + * @param pulNotificationValue Used to pass the task's notification value out + * of the function. Note the value passed out will not be effected by the + * clearing of any bits caused by ulBitsToClearOnExit being non-zero. + * + * @param xTicksToWait The maximum amount of time that the task should wait in + * the Blocked state for a notification to be received, should a notification + * not already be pending when xTaskNotifyWait() was called. The task + * will not consume any processing time while it is in the Blocked state. This + * is specified in kernel ticks, the macro pdMS_TO_TICSK( value_in_ms ) can be + * used to convert a time specified in milliseconds to a time specified in + * ticks. + * + * @return If a notification was received (including notifications that were + * already pending when xTaskNotifyWait was called) then pdPASS is + * returned. Otherwise pdFAIL is returned. + * + * \defgroup xTaskNotifyWait xTaskNotifyWait + * \ingroup TaskNotifications + */ +BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * task. h + *BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify );+ * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro + * to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * xTaskNotifyGive() is a helper macro intended for use when task notifications + * are used as light weight and faster binary or counting semaphore equivalents. + * Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function, + * the equivalent action that instead uses a task notification is + * xTaskNotifyGive(). + * + * When task notifications are being used as a binary or counting semaphore + * equivalent then the task being notified should wait for the notification + * using the ulTaskNotificationTake() API function rather than the + * xTaskNotifyWait() API function. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the + * eAction parameter set to eIncrement - so pdPASS is always returned. + * + * \defgroup xTaskNotifyGive xTaskNotifyGive + * \ingroup TaskNotifications + */ +#define xTaskNotifyGive( xTaskToNotify ) xTaskGenericNotify( ( xTaskToNotify ), ( 0 ), eIncrement, NULL ) + +/** + * task. h + *void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken ); + * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro + * to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * A version of xTaskNotifyGive() that can be called from an interrupt service + * routine (ISR). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * vTaskNotifyGiveFromISR() is intended for use when task notifications are + * used as light weight and faster binary or counting semaphore equivalents. + * Actual FreeRTOS semaphores are given from an ISR using the + * xSemaphoreGiveFromISR() API function, the equivalent action that instead uses + * a task notification is vTaskNotifyGiveFromISR(). + * + * When task notifications are being used as a binary or counting semaphore + * equivalent then the task being notified should wait for the notification + * using the ulTaskNotificationTake() API function rather than the + * xTaskNotifyWait() API function. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details. + * + * @param xTaskToNotify The handle of the task being notified. The handle to a + * task can be returned from the xTaskCreate() API function used to create the + * task, and the handle of the currently running task can be obtained by calling + * xTaskGetCurrentTaskHandle(). + * + * @param pxHigherPriorityTaskWoken vTaskNotifyGiveFromISR() will set + * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the + * task to which the notification was sent to leave the Blocked state, and the + * unblocked task has a priority higher than the currently running task. If + * vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch + * should be requested before the interrupt is exited. How a context switch is + * requested from an ISR is dependent on the port - see the documentation page + * for the port in use. + * + * \defgroup xTaskNotifyWait xTaskNotifyWait + * \ingroup TaskNotifications + */ +void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + +/** + * task. h + *uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );+ * + * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this + * function to be available. + * + * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private + * "notification value", which is a 32-bit unsigned integer (uint32_t). + * + * Events can be sent to a task using an intermediary object. Examples of such + * objects are queues, semaphores, mutexes and event groups. Task notifications + * are a method of sending an event directly to a task without the need for such + * an intermediary object. + * + * A notification sent to a task can optionally perform an action, such as + * update, overwrite or increment the task's notification value. In that way + * task notifications can be used to send data to a task, or be used as light + * weight and fast binary or counting semaphores. + * + * ulTaskNotifyTake() is intended for use when a task notification is used as a + * faster and lighter weight binary or counting semaphore alternative. Actual + * FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the + * equivalent action that instead uses a task notification is + * ulTaskNotifyTake(). + * + * When a task is using its notification value as a binary or counting semaphore + * other tasks should send notifications to it using the xTaskNotifyGive() + * macro, or xTaskNotify() function with the eAction parameter set to + * eIncrement. + * + * ulTaskNotifyTake() can either clear the task's notification value to + * zero on exit, in which case the notification value acts like a binary + * semaphore, or decrement the task's notification value on exit, in which case + * the notification value acts like a counting semaphore. + * + * A task can use ulTaskNotifyTake() to [optionally] block to wait for a + * the task's notification value to be non-zero. The task does not consume any + * CPU time while it is in the Blocked state. + * + * Where as xTaskNotifyWait() will return when a notification is pending, + * ulTaskNotifyTake() will return when the task's notification value is + * not zero. + * + * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details. + * + * @param xClearCountOnExit if xClearCountOnExit is pdFALSE then the task's + * notification value is decremented when the function exits. In this way the + * notification value acts like a counting semaphore. If xClearCountOnExit is + * not pdFALSE then the task's notification value is cleared to zero when the + * function exits. In this way the notification value acts like a binary + * semaphore. + * + * @param xTicksToWait The maximum amount of time that the task should wait in + * the Blocked state for the task's notification value to be greater than zero, + * should the count not already be greater than zero when + * ulTaskNotifyTake() was called. The task will not consume any processing + * time while it is in the Blocked state. This is specified in kernel ticks, + * the macro pdMS_TO_TICSK( value_in_ms ) can be used to convert a time + * specified in milliseconds to a time specified in ticks. + * + * @return The task's notification count before it is either cleared to zero or + * decremented (see the xClearCountOnExit parameter). + * + * \defgroup ulTaskNotifyTake ulTaskNotifyTake + * \ingroup TaskNotifications + */ +uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * task. h + *BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask );+ * + * If the notification state of the task referenced by the handle xTask is + * eNotified, then set the task's notification state to eNotWaitingNotification. + * The task's notification value is not altered. Set xTask to NULL to clear the + * notification state of the calling task. + * + * @return pdTRUE if the task's notification state was set to + * eNotWaitingNotification, otherwise pdFALSE. + * \defgroup xTaskNotifyStateClear xTaskNotifyStateClear + * \ingroup TaskNotifications + */ +BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ); + +/** +* task. h +*uint32_t ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear );+* +* Clears the bits specified by the ulBitsToClear bit mask in the notification +* value of the task referenced by xTask. +* +* Set ulBitsToClear to 0xffffffff (UINT_MAX on 32-bit architectures) to clear +* the notification value to 0. Set ulBitsToClear to 0 to query the task's +* notification value without clearing any bits. +* +* @return The value of the target task's notification value before the bits +* specified by ulBitsToClear were cleared. +* \defgroup ulTaskNotifyValueClear ulTaskNotifyValueClear +* \ingroup TaskNotifications +*/ +uint32_t ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear ) PRIVILEGED_FUNCTION; + +/** + * task.h + *void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut )+ * + * Capture the current time for future use with xTaskCheckForTimeOut(). + * + * @param pxTimeOut Pointer to a timeout object into which the current time + * is to be captured. The captured time includes the tick count and the number + * of times the tick count has overflowed since the system first booted. + * \defgroup vTaskSetTimeOutState vTaskSetTimeOutState + * \ingroup TaskCtrl + */ +void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; + +/** + * task.h + *BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait );+ * + * Determines if pxTicksToWait ticks has passed since a time was captured + * using a call to vTaskSetTimeOutState(). The captured time includes the tick + * count and the number of times the tick count has overflowed. + * + * @param pxTimeOut The time status as captured previously using + * vTaskSetTimeOutState. If the timeout has not yet occurred, it is updated + * to reflect the current time status. + * @param pxTicksToWait The number of ticks to check for timeout i.e. if + * pxTicksToWait ticks have passed since pxTimeOut was last updated (either by + * vTaskSetTimeOutState() or xTaskCheckForTimeOut()), the timeout has occurred. + * If the timeout has not occurred, pxTIcksToWait is updated to reflect the + * number of remaining ticks. + * + * @return If timeout has occurred, pdTRUE is returned. Otherwise pdFALSE is + * returned and pxTicksToWait is updated to reflect the number of remaining + * ticks. + * + * @see https://www.freertos.org/xTaskCheckForTimeOut.html + * + * Example Usage: + *+ // Driver library function used to receive uxWantedBytes from an Rx buffer + // that is filled by a UART interrupt. If there are not enough bytes in the + // Rx buffer then the task enters the Blocked state until it is notified that + // more data has been placed into the buffer. If there is still not enough + // data then the task re-enters the Blocked state, and xTaskCheckForTimeOut() + // is used to re-calculate the Block time to ensure the total amount of time + // spent in the Blocked state does not exceed MAX_TIME_TO_WAIT. This + // continues until either the buffer contains at least uxWantedBytes bytes, + // or the total amount of time spent in the Blocked state reaches + // MAX_TIME_TO_WAIT – at which point the task reads however many bytes are + // available up to a maximum of uxWantedBytes. + + size_t xUART_Receive( uint8_t *pucBuffer, size_t uxWantedBytes ) + { + size_t uxReceived = 0; + TickType_t xTicksToWait = MAX_TIME_TO_WAIT; + TimeOut_t xTimeOut; + + // Initialize xTimeOut. This records the time at which this function + // was entered. + vTaskSetTimeOutState( &xTimeOut ); + + // Loop until the buffer contains the wanted number of bytes, or a + // timeout occurs. + while( UART_bytes_in_rx_buffer( pxUARTInstance ) < uxWantedBytes ) + { + // The buffer didn't contain enough data so this task is going to + // enter the Blocked state. Adjusting xTicksToWait to account for + // any time that has been spent in the Blocked state within this + // function so far to ensure the total amount of time spent in the + // Blocked state does not exceed MAX_TIME_TO_WAIT. + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) != pdFALSE ) + { + //Timed out before the wanted number of bytes were available, + // exit the loop. + break; + } + + // Wait for a maximum of xTicksToWait ticks to be notified that the + // receive interrupt has placed more data into the buffer. + ulTaskNotifyTake( pdTRUE, xTicksToWait ); + } + + // Attempt to read uxWantedBytes from the receive buffer into pucBuffer. + // The actual number of bytes read (which might be less than + // uxWantedBytes) is returned. + uxReceived = UART_read_from_receive_buffer( pxUARTInstance, + pucBuffer, + uxWantedBytes ); + + return uxReceived; + } ++ * \defgroup xTaskCheckForTimeOut xTaskCheckForTimeOut + * \ingroup TaskCtrl + */ +BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) PRIVILEGED_FUNCTION; + +/*----------------------------------------------------------- + * SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES + *----------------------------------------------------------*/ + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY + * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS + * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * Called from the real time kernel tick (either preemptive or cooperative), + * this increments the tick count and checks if any tasks that are blocked + * for a finite period required removing from a blocked list and placing on + * a ready list. If a non-zero value is returned then a context switch is + * required because either: + * + A task was removed from a blocked list because its timeout had expired, + * or + * + Time slicing is in use and there is a task of equal priority to the + * currently running task. + */ +BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * Removes the calling task from the ready list and places it both + * on the list of tasks waiting for a particular event, and the + * list of delayed tasks. The task will be removed from both lists + * and replaced on the ready list should either the event occur (and + * there be no higher priority tasks waiting on the same event) or + * the delay period expires. + * + * The 'unordered' version replaces the event list item value with the + * xItemValue value, and inserts the list item at the end of the list. + * + * The 'ordered' version uses the existing event list item value (which is the + * owning tasks priority) to insert the list item into the event list is task + * priority order. + * + * @param pxEventList The list containing tasks that are blocked waiting + * for the event to occur. + * + * @param xItemValue The item value to use for the event list item when the + * event list is not ordered by task priority. + * + * @param xTicksToWait The maximum amount of time that the task should wait + * for the event to occur. This is specified in kernel ticks,the constant + * portTICK_PERIOD_MS can be used to convert kernel ticks into a real time + * period. + */ +void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; +void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * This function performs nearly the same function as vTaskPlaceOnEventList(). + * The difference being that this function does not permit tasks to block + * indefinitely, whereas vTaskPlaceOnEventList() does. + * + */ +void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS AN + * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED. + * + * Removes a task from both the specified event list and the list of blocked + * tasks, and places it on a ready queue. + * + * xTaskRemoveFromEventList()/vTaskRemoveFromUnorderedEventList() will be called + * if either an event occurs to unblock a task, or the block timeout period + * expires. + * + * xTaskRemoveFromEventList() is used when the event list is in task priority + * order. It removes the list item from the head of the event list as that will + * have the highest priority owning task of all the tasks on the event list. + * vTaskRemoveFromUnorderedEventList() is used when the event list is not + * ordered and the event list items hold something other than the owning tasks + * priority. In this case the event list item value is updated to the value + * passed in the xItemValue parameter. + * + * @return pdTRUE if the task being removed has a higher priority than the task + * making the call, otherwise pdFALSE. + */ +BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) PRIVILEGED_FUNCTION; +void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue ) PRIVILEGED_FUNCTION; + +/* + * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE. IT IS ONLY + * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS + * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER. + * + * Sets the pointer to the current TCB to the TCB of the highest priority task + * that is ready to run. + */ +portDONT_DISCARD void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION; + +/* + * THESE FUNCTIONS MUST NOT BE USED FROM APPLICATION CODE. THEY ARE USED BY + * THE EVENT BITS MODULE. + */ +TickType_t uxTaskResetEventItemValue( void ) PRIVILEGED_FUNCTION; + +/* + * Return the handle of the calling task. + */ +TaskHandle_t xTaskGetCurrentTaskHandle( void ) PRIVILEGED_FUNCTION; + +/* + * Shortcut used by the queue implementation to prevent unnecessary call to + * taskYIELD(); + */ +void vTaskMissedYield( void ) PRIVILEGED_FUNCTION; + +/* + * Returns the scheduler state as taskSCHEDULER_RUNNING, + * taskSCHEDULER_NOT_STARTED or taskSCHEDULER_SUSPENDED. + */ +BaseType_t xTaskGetSchedulerState( void ) PRIVILEGED_FUNCTION; + +/* + * Raises the priority of the mutex holder to that of the calling task should + * the mutex holder have a priority less than the calling task. + */ +BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION; + +/* + * Set the priority of a task back to its proper priority in the case that it + * inherited a higher priority while it was holding a semaphore. + */ +BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION; + +/* + * If a higher priority task attempting to obtain a mutex caused a lower + * priority task to inherit the higher priority task's priority - but the higher + * priority task then timed out without obtaining the mutex, then the lower + * priority task will disinherit the priority again - but only down as far as + * the highest priority task that is still waiting for the mutex (if there were + * more than one task waiting for the mutex). + */ +void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) PRIVILEGED_FUNCTION; + +/* + * Get the uxTCBNumber assigned to the task referenced by the xTask parameter. + */ +UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +/* + * Set the uxTaskNumber of the task referenced by the xTask parameter to + * uxHandle. + */ +void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) PRIVILEGED_FUNCTION; + +/* + * Only available when configUSE_TICKLESS_IDLE is set to 1. + * If tickless mode is being used, or a low power mode is implemented, then + * the tick interrupt will not execute during idle periods. When this is the + * case, the tick count value maintained by the scheduler needs to be kept up + * to date with the actual execution time by being skipped forward by a time + * equal to the idle period. + */ +void vTaskStepTick( const TickType_t xTicksToJump ) PRIVILEGED_FUNCTION; + +/* Correct the tick count value after the application code has held +interrupts disabled for an extended period. xTicksToCatchUp is the number +of tick interrupts that have been missed due to interrupts being disabled. +Its value is not computed automatically, so must be computed by the +application writer. + +This function is similar to vTaskStepTick(), however, unlike +vTaskStepTick(), xTaskCatchUpTicks() may move the tick count forward past a +time at which a task should be removed from the blocked state. That means +tasks may have to be removed from the blocked state as the tick count is +moved. */ +BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) PRIVILEGED_FUNCTION; + +/* + * Only available when configUSE_TICKLESS_IDLE is set to 1. + * Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port + * specific sleep function to determine if it is ok to proceed with the sleep, + * and if it is ok to proceed, if it is ok to sleep indefinitely. + * + * This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only + * called with the scheduler suspended, not from within a critical section. It + * is therefore possible for an interrupt to request a context switch between + * portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being + * entered. eTaskConfirmSleepModeStatus() should be called from a short + * critical section between the timer being stopped and the sleep mode being + * entered to ensure it is ok to proceed into the sleep mode. + */ +eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Increment the mutex held count when a mutex is + * taken and return the handle of the task that has taken the mutex. + */ +TaskHandle_t pvTaskIncrementMutexHeldCount( void ) PRIVILEGED_FUNCTION; + +/* + * For internal use only. Same as vTaskSetTimeOutState(), but without a critial + * section. + */ +void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION; + + +#ifdef __cplusplus +} +#endif +#endif /* INC_TASK_H */ + + + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h b/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h new file mode 100644 index 0000000..307ea1f --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/include/timers.h @@ -0,0 +1,1309 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +#ifndef TIMERS_H +#define TIMERS_H + +#ifndef INC_FREERTOS_H + #error "include FreeRTOS.h must appear in source files before include timers.h" +#endif + +/*lint -save -e537 This headers are only multiply included if the application code +happens to also be including task.h. */ +#include "task.h" +/*lint -restore */ + +#ifdef __cplusplus +extern "C" { +#endif + +/*----------------------------------------------------------- + * MACROS AND DEFINITIONS + *----------------------------------------------------------*/ + +/* IDs for commands that can be sent/received on the timer queue. These are to +be used solely through the macros that make up the public software timer API, +as defined below. The commands that are sent from interrupts must use the +highest numbers as tmrFIRST_FROM_ISR_COMMAND is used to determine if the task +or interrupt version of the queue send function should be used. */ +#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR ( ( BaseType_t ) -2 ) +#define tmrCOMMAND_EXECUTE_CALLBACK ( ( BaseType_t ) -1 ) +#define tmrCOMMAND_START_DONT_TRACE ( ( BaseType_t ) 0 ) +#define tmrCOMMAND_START ( ( BaseType_t ) 1 ) +#define tmrCOMMAND_RESET ( ( BaseType_t ) 2 ) +#define tmrCOMMAND_STOP ( ( BaseType_t ) 3 ) +#define tmrCOMMAND_CHANGE_PERIOD ( ( BaseType_t ) 4 ) +#define tmrCOMMAND_DELETE ( ( BaseType_t ) 5 ) + +#define tmrFIRST_FROM_ISR_COMMAND ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_START_FROM_ISR ( ( BaseType_t ) 6 ) +#define tmrCOMMAND_RESET_FROM_ISR ( ( BaseType_t ) 7 ) +#define tmrCOMMAND_STOP_FROM_ISR ( ( BaseType_t ) 8 ) +#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR ( ( BaseType_t ) 9 ) + + +/** + * Type by which software timers are referenced. For example, a call to + * xTimerCreate() returns an TimerHandle_t variable that can then be used to + * reference the subject timer in calls to other software timer API functions + * (for example, xTimerStart(), xTimerReset(), etc.). + */ +struct tmrTimerControl; /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +typedef struct tmrTimerControl * TimerHandle_t; + +/* + * Defines the prototype to which timer callback functions must conform. + */ +typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer ); + +/* + * Defines the prototype to which functions used with the + * xTimerPendFunctionCallFromISR() function must conform. + */ +typedef void (*PendedFunction_t)( void *, uint32_t ); + +/** + * TimerHandle_t xTimerCreate( const char * const pcTimerName, + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction ); + * + * Creates a new software timer instance, and returns a handle by which the + * created software timer can be referenced. + * + * Internally, within the FreeRTOS implementation, software timers use a block + * of memory, in which the timer data structure is stored. If a software timer + * is created using xTimerCreate() then the required memory is automatically + * dynamically allocated inside the xTimerCreate() function. (see + * http://www.freertos.org/a00111.html). If a software timer is created using + * xTimerCreateStatic() then the application writer must provide the memory that + * will get used by the software timer. xTimerCreateStatic() therefore allows a + * software timer to be created without using any dynamic memory allocation. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a + * timer into the active state. + * + * @param pcTimerName A text name that is assigned to the timer. This is done + * purely to assist debugging. The kernel itself only ever references a timer + * by its handle, and never by its name. + * + * @param xTimerPeriodInTicks The timer period. The time is defined in tick + * periods so the constant portTICK_PERIOD_MS can be used to convert a time that + * has been specified in milliseconds. For example, if the timer must expire + * after 100 ticks, then xTimerPeriodInTicks should be set to 100. + * Alternatively, if the timer must expire after 500ms, then xPeriod can be set + * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or + * equal to 1000. Time timer period must be greater than 0. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. + * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + * + * @param pvTimerID An identifier that is assigned to the timer being created. + * Typically this would be used in the timer callback function to identify which + * timer expired when the same callback function is assigned to more than one + * timer. + * + * @param pxCallbackFunction The function to call when the timer expires. + * Callback functions must have the prototype defined by TimerCallbackFunction_t, + * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * + * @return If the timer is successfully created then a handle to the newly + * created timer is returned. If the timer cannot be created because there is + * insufficient FreeRTOS heap remaining to allocate the timer + * structures then NULL is returned. + * + * Example usage: + * @verbatim + * #define NUM_TIMERS 5 + * + * // An array to hold handles to the created timers. + * TimerHandle_t xTimers[ NUM_TIMERS ]; + * + * // An array to hold a count of the number of times each timer expires. + * int32_t lExpireCounters[ NUM_TIMERS ] = { 0 }; + * + * // Define a callback function that will be used by multiple timer instances. + * // The callback function does nothing but count the number of times the + * // associated timer expires, and stop the timer once the timer has expired + * // 10 times. + * void vTimerCallback( TimerHandle_t pxTimer ) + * { + * int32_t lArrayIndex; + * const int32_t xMaxExpiryCountBeforeStopping = 10; + * + * // Optionally do something if the pxTimer parameter is NULL. + * configASSERT( pxTimer ); + * + * // Which timer expired? + * lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer ); + * + * // Increment the number of times that pxTimer has expired. + * lExpireCounters[ lArrayIndex ] += 1; + * + * // If the timer has expired 10 times then stop it from running. + * if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping ) + * { + * // Do not use a block time if calling a timer API function from a + * // timer callback function, as doing so could cause a deadlock! + * xTimerStop( pxTimer, 0 ); + * } + * } + * + * void main( void ) + * { + * int32_t x; + * + * // Create then start some timers. Starting the timers before the scheduler + * // has been started means the timers will start running immediately that + * // the scheduler starts. + * for( x = 0; x < NUM_TIMERS; x++ ) + * { + * xTimers[ x ] = xTimerCreate( "Timer", // Just a text name, not used by the kernel. + * ( 100 * x ), // The timer period in ticks. + * pdTRUE, // The timers will auto-reload themselves when they expire. + * ( void * ) x, // Assign each timer a unique id equal to its array index. + * vTimerCallback // Each timer calls the same callback when it expires. + * ); + * + * if( xTimers[ x ] == NULL ) + * { + * // The timer was not created. + * } + * else + * { + * // Start the timer. No block time is specified, and even if one was + * // it would be ignored because the scheduler has not yet been + * // started. + * if( xTimerStart( xTimers[ x ], 0 ) != pdPASS ) + * { + * // The timer could not be set into the Active state. + * } + * } + * } + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timers running as they have already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endverbatim + */ +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; +#endif + +/** + * TimerHandle_t xTimerCreateStatic(const char * const pcTimerName, + * TickType_t xTimerPeriodInTicks, + * UBaseType_t uxAutoReload, + * void * pvTimerID, + * TimerCallbackFunction_t pxCallbackFunction, + * StaticTimer_t *pxTimerBuffer ); + * + * Creates a new software timer instance, and returns a handle by which the + * created software timer can be referenced. + * + * Internally, within the FreeRTOS implementation, software timers use a block + * of memory, in which the timer data structure is stored. If a software timer + * is created using xTimerCreate() then the required memory is automatically + * dynamically allocated inside the xTimerCreate() function. (see + * http://www.freertos.org/a00111.html). If a software timer is created using + * xTimerCreateStatic() then the application writer must provide the memory that + * will get used by the software timer. xTimerCreateStatic() therefore allows a + * software timer to be created without using any dynamic memory allocation. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a + * timer into the active state. + * + * @param pcTimerName A text name that is assigned to the timer. This is done + * purely to assist debugging. The kernel itself only ever references a timer + * by its handle, and never by its name. + * + * @param xTimerPeriodInTicks The timer period. The time is defined in tick + * periods so the constant portTICK_PERIOD_MS can be used to convert a time that + * has been specified in milliseconds. For example, if the timer must expire + * after 100 ticks, then xTimerPeriodInTicks should be set to 100. + * Alternatively, if the timer must expire after 500ms, then xPeriod can be set + * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or + * equal to 1000. The timer period must be greater than 0. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter. + * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + * + * @param pvTimerID An identifier that is assigned to the timer being created. + * Typically this would be used in the timer callback function to identify which + * timer expired when the same callback function is assigned to more than one + * timer. + * + * @param pxCallbackFunction The function to call when the timer expires. + * Callback functions must have the prototype defined by TimerCallbackFunction_t, + * which is "void vCallbackFunction( TimerHandle_t xTimer );". + * + * @param pxTimerBuffer Must point to a variable of type StaticTimer_t, which + * will be then be used to hold the software timer's data structures, removing + * the need for the memory to be allocated dynamically. + * + * @return If the timer is created then a handle to the created timer is + * returned. If pxTimerBuffer was NULL then NULL is returned. + * + * Example usage: + * @verbatim + * + * // The buffer used to hold the software timer's data structure. + * static StaticTimer_t xTimerBuffer; + * + * // A variable that will be incremented by the software timer's callback + * // function. + * UBaseType_t uxVariableToIncrement = 0; + * + * // A software timer callback function that increments a variable passed to + * // it when the software timer was created. After the 5th increment the + * // callback function stops the software timer. + * static void prvTimerCallback( TimerHandle_t xExpiredTimer ) + * { + * UBaseType_t *puxVariableToIncrement; + * BaseType_t xReturned; + * + * // Obtain the address of the variable to increment from the timer ID. + * puxVariableToIncrement = ( UBaseType_t * ) pvTimerGetTimerID( xExpiredTimer ); + * + * // Increment the variable to show the timer callback has executed. + * ( *puxVariableToIncrement )++; + * + * // If this callback has executed the required number of times, stop the + * // timer. + * if( *puxVariableToIncrement == 5 ) + * { + * // This is called from a timer callback so must not block. + * xTimerStop( xExpiredTimer, staticDONT_BLOCK ); + * } + * } + * + * + * void main( void ) + * { + * // Create the software time. xTimerCreateStatic() has an extra parameter + * // than the normal xTimerCreate() API function. The parameter is a pointer + * // to the StaticTimer_t structure that will hold the software timer + * // structure. If the parameter is passed as NULL then the structure will be + * // allocated dynamically, just as if xTimerCreate() had been called. + * xTimer = xTimerCreateStatic( "T1", // Text name for the task. Helps debugging only. Not used by FreeRTOS. + * xTimerPeriod, // The period of the timer in ticks. + * pdTRUE, // This is an auto-reload timer. + * ( void * ) &uxVariableToIncrement, // A variable incremented by the software timer's callback function + * prvTimerCallback, // The function to execute when the timer expires. + * &xTimerBuffer ); // The buffer that will hold the software timer structure. + * + * // The scheduler has not started yet so a block time is not used. + * xReturned = xTimerStart( xTimer, 0 ); + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timers running as they have already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endverbatim + */ +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t *pxTimerBuffer ) PRIVILEGED_FUNCTION; +#endif /* configSUPPORT_STATIC_ALLOCATION */ + +/** + * void *pvTimerGetTimerID( TimerHandle_t xTimer ); + * + * Returns the ID assigned to the timer. + * + * IDs are assigned to timers using the pvTimerID parameter of the call to + * xTimerCreated() that was used to create the timer, and by calling the + * vTimerSetTimerID() API function. + * + * If the same callback function is assigned to multiple timers then the timer + * ID can be used as time specific (timer local) storage. + * + * @param xTimer The timer being queried. + * + * @return The ID assigned to the timer being queried. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + */ +void *pvTimerGetTimerID( const TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ); + * + * Sets the ID assigned to the timer. + * + * IDs are assigned to timers using the pvTimerID parameter of the call to + * xTimerCreated() that was used to create the timer. + * + * If the same callback function is assigned to multiple timers then the timer + * ID can be used as time specific (timer local) storage. + * + * @param xTimer The timer being updated. + * + * @param pvNewID The ID to assign to the timer. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + */ +void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ); + * + * Queries a timer to see if it is active or dormant. + * + * A timer will be dormant if: + * 1) It has been created but not started, or + * 2) It is an expired one-shot timer that has not been restarted. + * + * Timers are created in the dormant state. The xTimerStart(), xTimerReset(), + * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and + * xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the + * active state. + * + * @param xTimer The timer being queried. + * + * @return pdFALSE will be returned if the timer is dormant. A value other than + * pdFALSE will be returned if the timer is active. + * + * Example usage: + * @verbatim + * // This function assumes xTimer has already been created. + * void vAFunction( TimerHandle_t xTimer ) + * { + * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" + * { + * // xTimer is active, do something. + * } + * else + * { + * // xTimer is not active, do something else. + * } + * } + * @endverbatim + */ +BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ); + * + * Simply returns the handle of the timer service/daemon task. It it not valid + * to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started. + */ +TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) PRIVILEGED_FUNCTION; + +/** + * BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerStart() starts a timer that was previously created using the + * xTimerCreate() API function. If the timer had already been started and was + * already in the active state, then xTimerStart() has equivalent functionality + * to the xTimerReset() API function. + * + * Starting a timer ensures the timer is in the active state. If the timer + * is not stopped, deleted, or reset in the mean time, the callback function + * associated with the timer will get called 'n' ticks after xTimerStart() was + * called, where 'n' is the timers defined period. + * + * It is valid to call xTimerStart() before the scheduler has been started, but + * when this is done the timer will not actually start until the scheduler is + * started, and the timers expiry time will be relative to when the scheduler is + * started, not relative to when xTimerStart() was called. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart() + * to be available. + * + * @param xTimer The handle of the timer being started/restarted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the start command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerStart() was called. xTicksToWait is ignored if xTimerStart() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the start command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system, although the + * timers expiry time is relative to when xTimerStart() is actually called. The + * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + * + */ +#define xTimerStart( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerStop( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerStop() stops a timer that was previously started using either of the + * The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(), + * xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions. + * + * Stopping a timer ensures the timer is not in the active state. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop() + * to be available. + * + * @param xTimer The handle of the timer being stopped. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the stop command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerStop() was called. xTicksToWait is ignored if xTimerStop() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the stop command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerCreate() API function example usage scenario. + * + */ +#define xTimerStop( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerChangePeriod( TimerHandle_t xTimer, + * TickType_t xNewPeriod, + * TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerChangePeriod() changes the period of a timer that was previously + * created using the xTimerCreate() API function. + * + * xTimerChangePeriod() can be called to change the period of an active or + * dormant state timer. + * + * The configUSE_TIMERS configuration constant must be set to 1 for + * xTimerChangePeriod() to be available. + * + * @param xTimer The handle of the timer that is having its period changed. + * + * @param xNewPeriod The new period for xTimer. Timer periods are specified in + * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time + * that has been specified in milliseconds. For example, if the timer must + * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, + * if the timer must expire after 500ms, then xNewPeriod can be set to + * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than + * or equal to 1000. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the change period command to be + * successfully sent to the timer command queue, should the queue already be + * full when xTimerChangePeriod() was called. xTicksToWait is ignored if + * xTimerChangePeriod() is called before the scheduler is started. + * + * @return pdFAIL will be returned if the change period command could not be + * sent to the timer command queue even after xTicksToWait ticks had passed. + * pdPASS will be returned if the command was successfully sent to the timer + * command queue. When the command is actually processed will depend on the + * priority of the timer service/daemon task relative to other tasks in the + * system. The timer service/daemon task priority is set by the + * configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This function assumes xTimer has already been created. If the timer + * // referenced by xTimer is already active when it is called, then the timer + * // is deleted. If the timer referenced by xTimer is not active when it is + * // called, then the period of the timer is set to 500ms and the timer is + * // started. + * void vAFunction( TimerHandle_t xTimer ) + * { + * if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )" + * { + * // xTimer is already active - delete it. + * xTimerDelete( xTimer ); + * } + * else + * { + * // xTimer is not active, change its period to 500ms. This will also + * // cause the timer to start. Block for a maximum of 100 ticks if the + * // change period command cannot immediately be sent to the timer + * // command queue. + * if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS ) + * { + * // The command was successfully sent. + * } + * else + * { + * // The command could not be sent, even after waiting for 100 ticks + * // to pass. Take appropriate action here. + * } + * } + * } + * @endverbatim + */ + #define xTimerChangePeriod( xTimer, xNewPeriod, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD, ( xNewPeriod ), NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerDelete( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerDelete() deletes a timer that was previously created using the + * xTimerCreate() API function. + * + * The configUSE_TIMERS configuration constant must be set to 1 for + * xTimerDelete() to be available. + * + * @param xTimer The handle of the timer being deleted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the delete command to be + * successfully sent to the timer command queue, should the queue already be + * full when xTimerDelete() was called. xTicksToWait is ignored if xTimerDelete() + * is called before the scheduler is started. + * + * @return pdFAIL will be returned if the delete command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * + * See the xTimerChangePeriod() API function example usage scenario. + */ +#define xTimerDelete( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_DELETE, 0U, NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerReset( TimerHandle_t xTimer, TickType_t xTicksToWait ); + * + * Timer functionality is provided by a timer service/daemon task. Many of the + * public FreeRTOS timer API functions send commands to the timer service task + * through a queue called the timer command queue. The timer command queue is + * private to the kernel itself and is not directly accessible to application + * code. The length of the timer command queue is set by the + * configTIMER_QUEUE_LENGTH configuration constant. + * + * xTimerReset() re-starts a timer that was previously created using the + * xTimerCreate() API function. If the timer had already been started and was + * already in the active state, then xTimerReset() will cause the timer to + * re-evaluate its expiry time so that it is relative to when xTimerReset() was + * called. If the timer was in the dormant state then xTimerReset() has + * equivalent functionality to the xTimerStart() API function. + * + * Resetting a timer ensures the timer is in the active state. If the timer + * is not stopped, deleted, or reset in the mean time, the callback function + * associated with the timer will get called 'n' ticks after xTimerReset() was + * called, where 'n' is the timers defined period. + * + * It is valid to call xTimerReset() before the scheduler has been started, but + * when this is done the timer will not actually start until the scheduler is + * started, and the timers expiry time will be relative to when the scheduler is + * started, not relative to when xTimerReset() was called. + * + * The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset() + * to be available. + * + * @param xTimer The handle of the timer being reset/started/restarted. + * + * @param xTicksToWait Specifies the time, in ticks, that the calling task should + * be held in the Blocked state to wait for the reset command to be successfully + * sent to the timer command queue, should the queue already be full when + * xTimerReset() was called. xTicksToWait is ignored if xTimerReset() is called + * before the scheduler is started. + * + * @return pdFAIL will be returned if the reset command could not be sent to + * the timer command queue even after xTicksToWait ticks had passed. pdPASS will + * be returned if the command was successfully sent to the timer command queue. + * When the command is actually processed will depend on the priority of the + * timer service/daemon task relative to other tasks in the system, although the + * timers expiry time is relative to when xTimerStart() is actually called. The + * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * @verbatim + * // When a key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer. + * + * TimerHandle_t xBacklightTimer = NULL; + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press event handler. + * void vKeyPressEventHandler( char cKey ) + * { + * // Ensure the LCD back-light is on, then reset the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. Wait 10 ticks for the command to be successfully sent + * // if it cannot be sent immediately. + * vSetBacklightState( BACKLIGHT_ON ); + * if( xTimerReset( xBacklightTimer, 100 ) != pdPASS ) + * { + * // The reset command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * } + * + * void main( void ) + * { + * int32_t x; + * + * // Create then start the one-shot timer that is responsible for turning + * // the back-light off if no keys are pressed within a 5 second period. + * xBacklightTimer = xTimerCreate( "BacklightTimer", // Just a text name, not used by the kernel. + * ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks. + * pdFALSE, // The timer is a one-shot timer. + * 0, // The id is not used by the callback so can take any value. + * vBacklightTimerCallback // The callback function that switches the LCD back-light off. + * ); + * + * if( xBacklightTimer == NULL ) + * { + * // The timer was not created. + * } + * else + * { + * // Start the timer. No block time is specified, and even if one was + * // it would be ignored because the scheduler has not yet been + * // started. + * if( xTimerStart( xBacklightTimer, 0 ) != pdPASS ) + * { + * // The timer could not be set into the Active state. + * } + * } + * + * // ... + * // Create tasks here. + * // ... + * + * // Starting the scheduler will start the timer running as it has already + * // been set into the active state. + * vTaskStartScheduler(); + * + * // Should not reach here. + * for( ;; ); + * } + * @endverbatim + */ +#define xTimerReset( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) ) + +/** + * BaseType_t xTimerStartFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerStart() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer being started/restarted. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerStartFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerStartFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerStartFromISR() function. If + * xTimerStartFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the start command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system, although the timers expiry time is + * relative to when xTimerStartFromISR() is actually called. The timer + * service/daemon task priority is set by the configTIMER_TASK_PRIORITY + * configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xBacklightTimer has already been created. When a + * // key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer, and unlike the example given for + * // the xTimerReset() function, the key press event handler is an interrupt + * // service routine. + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press interrupt service routine. + * void vKeyPressEventInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // Ensure the LCD back-light is on, then restart the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. This is an interrupt service routine so can only + * // call FreeRTOS API functions that end in "FromISR". + * vSetBacklightState( BACKLIGHT_ON ); + * + * // xTimerStartFromISR() or xTimerResetFromISR() could be called here + * // as both cause the timer to re-calculate its expiry time. + * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was + * // declared (in this function). + * if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The start command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * BaseType_t xTimerStopFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerStop() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer being stopped. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerStopFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerStopFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerStopFromISR() function. If + * xTimerStopFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the stop command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system. The timer service/daemon task + * priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xTimer has already been created and started. When + * // an interrupt occurs, the timer should be simply stopped. + * + * // The interrupt service routine that stops the timer. + * void vAnExampleInterruptServiceRoutine( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // The interrupt has occurred - simply stop the timer. + * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined + * // (within this function). As this is an interrupt service routine, only + * // FreeRTOS API functions that end in "FromISR" can be used. + * if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The stop command was not executed successfully. Take appropriate + * // action here. + * } + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerStopFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP_FROM_ISR, 0, ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * BaseType_t xTimerChangePeriodFromISR( TimerHandle_t xTimer, + * TickType_t xNewPeriod, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerChangePeriod() that can be called from an interrupt + * service routine. + * + * @param xTimer The handle of the timer that is having its period changed. + * + * @param xNewPeriod The new period for xTimer. Timer periods are specified in + * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time + * that has been specified in milliseconds. For example, if the timer must + * expire after 100 ticks, then xNewPeriod should be set to 100. Alternatively, + * if the timer must expire after 500ms, then xNewPeriod can be set to + * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than + * or equal to 1000. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerChangePeriodFromISR() writes a message to the + * timer command queue, so has the potential to transition the timer service/ + * daemon task out of the Blocked state. If calling xTimerChangePeriodFromISR() + * causes the timer service/daemon task to leave the Blocked state, and the + * timer service/daemon task has a priority equal to or greater than the + * currently executing task (the task that was interrupted), then + * *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the + * xTimerChangePeriodFromISR() function. If xTimerChangePeriodFromISR() sets + * this value to pdTRUE then a context switch should be performed before the + * interrupt exits. + * + * @return pdFAIL will be returned if the command to change the timers period + * could not be sent to the timer command queue. pdPASS will be returned if the + * command was successfully sent to the timer command queue. When the command + * is actually processed will depend on the priority of the timer service/daemon + * task relative to other tasks in the system. The timer service/daemon task + * priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xTimer has already been created and started. When + * // an interrupt occurs, the period of xTimer should be changed to 500ms. + * + * // The interrupt service routine that changes the period of xTimer. + * void vAnExampleInterruptServiceRoutine( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // The interrupt has occurred - change the period of xTimer to 500ms. + * // xHigherPriorityTaskWoken was set to pdFALSE where it was defined + * // (within this function). As this is an interrupt service routine, only + * // FreeRTOS API functions that end in "FromISR" can be used. + * if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The command to change the timers period was not executed + * // successfully. Take appropriate action here. + * } + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD_FROM_ISR, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U ) + +/** + * BaseType_t xTimerResetFromISR( TimerHandle_t xTimer, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * A version of xTimerReset() that can be called from an interrupt service + * routine. + * + * @param xTimer The handle of the timer that is to be started, reset, or + * restarted. + * + * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most + * of its time in the Blocked state, waiting for messages to arrive on the timer + * command queue. Calling xTimerResetFromISR() writes a message to the timer + * command queue, so has the potential to transition the timer service/daemon + * task out of the Blocked state. If calling xTimerResetFromISR() causes the + * timer service/daemon task to leave the Blocked state, and the timer service/ + * daemon task has a priority equal to or greater than the currently executing + * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will + * get set to pdTRUE internally within the xTimerResetFromISR() function. If + * xTimerResetFromISR() sets this value to pdTRUE then a context switch should + * be performed before the interrupt exits. + * + * @return pdFAIL will be returned if the reset command could not be sent to + * the timer command queue. pdPASS will be returned if the command was + * successfully sent to the timer command queue. When the command is actually + * processed will depend on the priority of the timer service/daemon task + * relative to other tasks in the system, although the timers expiry time is + * relative to when xTimerResetFromISR() is actually called. The timer service/daemon + * task priority is set by the configTIMER_TASK_PRIORITY configuration constant. + * + * Example usage: + * @verbatim + * // This scenario assumes xBacklightTimer has already been created. When a + * // key is pressed, an LCD back-light is switched on. If 5 seconds pass + * // without a key being pressed, then the LCD back-light is switched off. In + * // this case, the timer is a one-shot timer, and unlike the example given for + * // the xTimerReset() function, the key press event handler is an interrupt + * // service routine. + * + * // The callback function assigned to the one-shot timer. In this case the + * // parameter is not used. + * void vBacklightTimerCallback( TimerHandle_t pxTimer ) + * { + * // The timer expired, therefore 5 seconds must have passed since a key + * // was pressed. Switch off the LCD back-light. + * vSetBacklightState( BACKLIGHT_OFF ); + * } + * + * // The key press interrupt service routine. + * void vKeyPressEventInterruptHandler( void ) + * { + * BaseType_t xHigherPriorityTaskWoken = pdFALSE; + * + * // Ensure the LCD back-light is on, then reset the timer that is + * // responsible for turning the back-light off after 5 seconds of + * // key inactivity. This is an interrupt service routine so can only + * // call FreeRTOS API functions that end in "FromISR". + * vSetBacklightState( BACKLIGHT_ON ); + * + * // xTimerStartFromISR() or xTimerResetFromISR() could be called here + * // as both cause the timer to re-calculate its expiry time. + * // xHigherPriorityTaskWoken was initialised to pdFALSE when it was + * // declared (in this function). + * if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS ) + * { + * // The reset command was not executed successfully. Take appropriate + * // action here. + * } + * + * // Perform the rest of the key processing here. + * + * // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch + * // should be performed. The syntax required to perform a context switch + * // from inside an ISR varies from port to port, and from compiler to + * // compiler. Inspect the demos for the port you are using to find the + * // actual syntax required. + * if( xHigherPriorityTaskWoken != pdFALSE ) + * { + * // Call the interrupt safe yield function here (actual function + * // depends on the FreeRTOS port being used). + * } + * } + * @endverbatim + */ +#define xTimerResetFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U ) + + +/** + * BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, + * void *pvParameter1, + * uint32_t ulParameter2, + * BaseType_t *pxHigherPriorityTaskWoken ); + * + * + * Used from application interrupt service routines to defer the execution of a + * function to the RTOS daemon task (the timer service task, hence this function + * is implemented in timers.c and is prefixed with 'Timer'). + * + * Ideally an interrupt service routine (ISR) is kept as short as possible, but + * sometimes an ISR either has a lot of processing to do, or needs to perform + * processing that is not deterministic. In these cases + * xTimerPendFunctionCallFromISR() can be used to defer processing of a function + * to the RTOS daemon task. + * + * A mechanism is provided that allows the interrupt to return directly to the + * task that will subsequently execute the pended callback function. This + * allows the callback function to execute contiguously in time with the + * interrupt - just as if the callback had executed in the interrupt itself. + * + * @param xFunctionToPend The function to execute from the timer service/ + * daemon task. The function must conform to the PendedFunction_t + * prototype. + * + * @param pvParameter1 The value of the callback function's first parameter. + * The parameter has a void * type to allow it to be used to pass any type. + * For example, unsigned longs can be cast to a void *, or the void * can be + * used to point to a structure. + * + * @param ulParameter2 The value of the callback function's second parameter. + * + * @param pxHigherPriorityTaskWoken As mentioned above, calling this function + * will result in a message being sent to the timer daemon task. If the + * priority of the timer daemon task (which is set using + * configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of + * the currently running task (the task the interrupt interrupted) then + * *pxHigherPriorityTaskWoken will be set to pdTRUE within + * xTimerPendFunctionCallFromISR(), indicating that a context switch should be + * requested before the interrupt exits. For that reason + * *pxHigherPriorityTaskWoken must be initialised to pdFALSE. See the + * example code below. + * + * @return pdPASS is returned if the message was successfully sent to the + * timer daemon task, otherwise pdFALSE is returned. + * + * Example usage: + * @verbatim + * + * // The callback function that will execute in the context of the daemon task. + * // Note callback functions must all use this same prototype. + * void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 ) + * { + * BaseType_t xInterfaceToService; + * + * // The interface that requires servicing is passed in the second + * // parameter. The first parameter is not used in this case. + * xInterfaceToService = ( BaseType_t ) ulParameter2; + * + * // ...Perform the processing here... + * } + * + * // An ISR that receives data packets from multiple interfaces + * void vAnISR( void ) + * { + * BaseType_t xInterfaceToService, xHigherPriorityTaskWoken; + * + * // Query the hardware to determine which interface needs processing. + * xInterfaceToService = prvCheckInterfaces(); + * + * // The actual processing is to be deferred to a task. Request the + * // vProcessInterface() callback function is executed, passing in the + * // number of the interface that needs processing. The interface to + * // service is passed in the second parameter. The first parameter is + * // not used in this case. + * xHigherPriorityTaskWoken = pdFALSE; + * xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken ); + * + * // If xHigherPriorityTaskWoken is now set to pdTRUE then a context + * // switch should be requested. The macro used is port specific and will + * // be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to + * // the documentation page for the port being used. + * portYIELD_FROM_ISR( xHigherPriorityTaskWoken ); + * + * } + * @endverbatim + */ +BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION; + + /** + * BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, + * void *pvParameter1, + * uint32_t ulParameter2, + * TickType_t xTicksToWait ); + * + * + * Used to defer the execution of a function to the RTOS daemon task (the timer + * service task, hence this function is implemented in timers.c and is prefixed + * with 'Timer'). + * + * @param xFunctionToPend The function to execute from the timer service/ + * daemon task. The function must conform to the PendedFunction_t + * prototype. + * + * @param pvParameter1 The value of the callback function's first parameter. + * The parameter has a void * type to allow it to be used to pass any type. + * For example, unsigned longs can be cast to a void *, or the void * can be + * used to point to a structure. + * + * @param ulParameter2 The value of the callback function's second parameter. + * + * @param xTicksToWait Calling this function will result in a message being + * sent to the timer daemon task on a queue. xTicksToWait is the amount of + * time the calling task should remain in the Blocked state (so not using any + * processing time) for space to become available on the timer queue if the + * queue is found to be full. + * + * @return pdPASS is returned if the message was successfully sent to the + * timer daemon task, otherwise pdFALSE is returned. + * + */ +BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +/** + * const char * const pcTimerGetName( TimerHandle_t xTimer ); + * + * Returns the name that was assigned to a timer when the timer was created. + * + * @param xTimer The handle of the timer being queried. + * + * @return The name assigned to the timer specified by the xTimer parameter. + */ +const char * pcTimerGetName( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + +/** + * void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ); + * + * Updates a timer to be either an auto-reload timer, in which case the timer + * automatically resets itself each time it expires, or a one-shot timer, in + * which case the timer will only expire once unless it is manually restarted. + * + * @param xTimer The handle of the timer being updated. + * + * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will + * expire repeatedly with a frequency set by the timer's period (see the + * xTimerPeriodInTicks parameter of the xTimerCreate() API function). If + * uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and + * enter the dormant state after it expires. + */ +void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ) PRIVILEGED_FUNCTION; + +/** +* UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ); +* +* Queries a timer to determine if it is an auto-reload timer, in which case the timer +* automatically resets itself each time it expires, or a one-shot timer, in +* which case the timer will only expire once unless it is manually restarted. +* +* @param xTimer The handle of the timer being queried. +* +* @return If the timer is an auto-reload timer then pdTRUE is returned, otherwise +* pdFALSE is returned. +*/ +UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** + * TickType_t xTimerGetPeriod( TimerHandle_t xTimer ); + * + * Returns the period of a timer. + * + * @param xTimer The handle of the timer being queried. + * + * @return The period of the timer in ticks. + */ +TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/** +* TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ); +* +* Returns the time in ticks at which the timer will expire. If this is less +* than the current tick count then the expiry time has overflowed from the +* current time. +* +* @param xTimer The handle of the timer being queried. +* +* @return If the timer is running then the time in ticks at which the timer +* will next expire is returned. If the timer is not running then the return +* value is undefined. +*/ +TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; + +/* + * Functions beyond this part are not part of the public API and are intended + * for use by the kernel only. + */ +BaseType_t xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION; +BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION; + +#if( configUSE_TRACE_FACILITY == 1 ) + void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) PRIVILEGED_FUNCTION; + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION; +#endif + +#ifdef __cplusplus +} +#endif +#endif /* TIMERS_H */ + + + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/list.c b/Middlewares/Third_Party/FreeRTOS/Source/list.c new file mode 100644 index 0000000..7618ee8 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/list.c @@ -0,0 +1,198 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +#include+#include "FreeRTOS.h" +#include "list.h" + +/*----------------------------------------------------------- + * PUBLIC LIST API documented in list.h + *----------------------------------------------------------*/ + +void vListInitialise( List_t * const pxList ) +{ + /* The list structure contains a list item which is used to mark the + end of the list. To initialise the list the list end is inserted + as the only list entry. */ + pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + + /* The list end value is the highest possible value in the list to + ensure it remains at the end of the list. */ + pxList->xListEnd.xItemValue = portMAX_DELAY; + + /* The list end next and previous pointers point to itself so we know + when the list is empty. */ + pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd );/*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ + + pxList->uxNumberOfItems = ( UBaseType_t ) 0U; + + /* Write known values into the list if + configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList ); + listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList ); +} +/*-----------------------------------------------------------*/ + +void vListInitialiseItem( ListItem_t * const pxItem ) +{ + /* Make sure the list item is not recorded as being on a list. */ + pxItem->pxContainer = NULL; + + /* Write known values into the list item if + configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */ + listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); + listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem ); +} +/*-----------------------------------------------------------*/ + +void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem ) +{ +ListItem_t * const pxIndex = pxList->pxIndex; + + /* Only effective when configASSERT() is also defined, these tests may catch + the list data structures being overwritten in memory. They will not catch + data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + + /* Insert a new list item into pxList, but rather than sort the list, + makes the new list item the last item to be removed by a call to + listGET_OWNER_OF_NEXT_ENTRY(). */ + pxNewListItem->pxNext = pxIndex; + pxNewListItem->pxPrevious = pxIndex->pxPrevious; + + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); + + pxIndex->pxPrevious->pxNext = pxNewListItem; + pxIndex->pxPrevious = pxNewListItem; + + /* Remember which list the item is in. */ + pxNewListItem->pxContainer = pxList; + + ( pxList->uxNumberOfItems )++; +} +/*-----------------------------------------------------------*/ + +void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem ) +{ +ListItem_t *pxIterator; +const TickType_t xValueOfInsertion = pxNewListItem->xItemValue; + + /* Only effective when configASSERT() is also defined, these tests may catch + the list data structures being overwritten in memory. They will not catch + data errors caused by incorrect configuration or use of FreeRTOS. */ + listTEST_LIST_INTEGRITY( pxList ); + listTEST_LIST_ITEM_INTEGRITY( pxNewListItem ); + + /* Insert the new list item into the list, sorted in xItemValue order. + + If the list already contains a list item with the same item value then the + new list item should be placed after it. This ensures that TCBs which are + stored in ready lists (all of which have the same xItemValue value) get a + share of the CPU. However, if the xItemValue is the same as the back marker + the iteration loop below will not end. Therefore the value is checked + first, and the algorithm slightly modified if necessary. */ + if( xValueOfInsertion == portMAX_DELAY ) + { + pxIterator = pxList->xListEnd.pxPrevious; + } + else + { + /* *** NOTE *********************************************************** + If you find your application is crashing here then likely causes are + listed below. In addition see https://www.freertos.org/FAQHelp.html for + more tips, and ensure configASSERT() is defined! + https://www.freertos.org/a00110.html#configASSERT + + 1) Stack overflow - + see https://www.freertos.org/Stacks-and-stack-overflow-checking.html + 2) Incorrect interrupt priority assignment, especially on Cortex-M + parts where numerically high priority values denote low actual + interrupt priorities, which can seem counter intuitive. See + https://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition + of configMAX_SYSCALL_INTERRUPT_PRIORITY on + https://www.freertos.org/a00110.html + 3) Calling an API function from within a critical section or when + the scheduler is suspended, or calling an API function that does + not end in "FromISR" from an interrupt. + 4) Using a queue or semaphore before it has been initialised or + before the scheduler has been started (are interrupts firing + before vTaskStartScheduler() has been called?). + **********************************************************************/ + + for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. *//*lint !e440 The iterator moves to a different value, not xValueOfInsertion. */ + { + /* There is nothing to do here, just iterating to the wanted + insertion position. */ + } + } + + pxNewListItem->pxNext = pxIterator->pxNext; + pxNewListItem->pxNext->pxPrevious = pxNewListItem; + pxNewListItem->pxPrevious = pxIterator; + pxIterator->pxNext = pxNewListItem; + + /* Remember which list the item is in. This allows fast removal of the + item later. */ + pxNewListItem->pxContainer = pxList; + + ( pxList->uxNumberOfItems )++; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove ) +{ +/* The list item knows which list it is in. Obtain the list from the list +item. */ +List_t * const pxList = pxItemToRemove->pxContainer; + + pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious; + pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext; + + /* Only used during decision coverage testing. */ + mtCOVERAGE_TEST_DELAY(); + + /* Make sure the index is left pointing to a valid item. */ + if( pxList->pxIndex == pxItemToRemove ) + { + pxList->pxIndex = pxItemToRemove->pxPrevious; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxItemToRemove->pxContainer = NULL; + ( pxList->uxNumberOfItems )--; + + return pxList->uxNumberOfItems; +} +/*-----------------------------------------------------------*/ + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c b/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c new file mode 100644 index 0000000..89a912c --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/port.c @@ -0,0 +1,775 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/*----------------------------------------------------------- + * Implementation of functions defined in portable.h for the ARM CM4F port. + *----------------------------------------------------------*/ + +/* Scheduler includes. */ +#include "FreeRTOS.h" +#include "task.h" + +#ifndef __VFP_FP__ + #error This port can only be used when the project options are configured to enable hardware floating point support. +#endif + +#ifndef configSYSTICK_CLOCK_HZ + #define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ + /* Ensure the SysTick is clocked at the same frequency as the core. */ + #define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL ) +#else + /* The way the SysTick is clocked is not modified in case it is not the same + as the core. */ + #define portNVIC_SYSTICK_CLK_BIT ( 0 ) +#endif + +/* Constants required to manipulate the core. Registers first... */ +#define portNVIC_SYSTICK_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000e010 ) ) +#define portNVIC_SYSTICK_LOAD_REG ( * ( ( volatile uint32_t * ) 0xe000e014 ) ) +#define portNVIC_SYSTICK_CURRENT_VALUE_REG ( * ( ( volatile uint32_t * ) 0xe000e018 ) ) +#define portNVIC_SYSPRI2_REG ( * ( ( volatile uint32_t * ) 0xe000ed20 ) ) +/* ...then bits in the registers. */ +#define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL ) +#define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL ) +#define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL ) +#define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL ) +#define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL ) + +/* Constants used to detect a Cortex-M7 r0p1 core, which should use the ARM_CM7 +r0p1 port. */ +#define portCPUID ( * ( ( volatile uint32_t * ) 0xE000ed00 ) ) +#define portCORTEX_M7_r0p1_ID ( 0x410FC271UL ) +#define portCORTEX_M7_r0p0_ID ( 0x410FC270UL ) + +#define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL ) +#define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL ) + +/* Constants required to check the validity of an interrupt priority. */ +#define portFIRST_USER_INTERRUPT_NUMBER ( 16 ) +#define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 ) +#define portAIRCR_REG ( * ( ( volatile uint32_t * ) 0xE000ED0C ) ) +#define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff ) +#define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 ) +#define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 ) +#define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL ) +#define portPRIGROUP_SHIFT ( 8UL ) + +/* Masks off all bits but the VECTACTIVE bits in the ICSR register. */ +#define portVECTACTIVE_MASK ( 0xFFUL ) + +/* Constants required to manipulate the VFP. */ +#define portFPCCR ( ( volatile uint32_t * ) 0xe000ef34 ) /* Floating point context control register. */ +#define portASPEN_AND_LSPEN_BITS ( 0x3UL << 30UL ) + +/* Constants required to set up the initial stack. */ +#define portINITIAL_XPSR ( 0x01000000 ) +#define portINITIAL_EXC_RETURN ( 0xfffffffd ) + +/* The systick is a 24-bit counter. */ +#define portMAX_24_BIT_NUMBER ( 0xffffffUL ) + +/* For strict compliance with the Cortex-M spec the task start address should +have bit-0 clear, as it is loaded into the PC on exit from an ISR. */ +#define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL ) + +/* A fiddle factor to estimate the number of SysTick counts that would have +occurred while the SysTick counter is stopped during tickless idle +calculations. */ +#define portMISSED_COUNTS_FACTOR ( 45UL ) + +/* Let the user override the pre-loading of the initial LR with the address of +prvTaskExitError() in case it messes up unwinding of the stack in the +debugger. */ +#ifdef configTASK_RETURN_ADDRESS + #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS +#else + #define portTASK_RETURN_ADDRESS prvTaskExitError +#endif + +/* + * Setup the timer to generate the tick interrupts. The implementation in this + * file is weak to allow application writers to change the timer used to + * generate the tick interrupt. + */ +void vPortSetupTimerInterrupt( void ); + +/* + * Exception handlers. + */ +void xPortPendSVHandler( void ) __attribute__ (( naked )); +void xPortSysTickHandler( void ); +void vPortSVCHandler( void ) __attribute__ (( naked )); + +/* + * Start first task is a separate function so it can be tested in isolation. + */ +static void prvPortStartFirstTask( void ) __attribute__ (( naked )); + +/* + * Function to enable the VFP. + */ +static void vPortEnableVFP( void ) __attribute__ (( naked )); + +/* + * Used to catch tasks that attempt to return from their implementing function. + */ +static void prvTaskExitError( void ); + +/*-----------------------------------------------------------*/ + +/* Each task maintains its own interrupt status in the critical nesting +variable. */ +static UBaseType_t uxCriticalNesting = 0xaaaaaaaa; + +/* + * The number of SysTick increments that make up one tick period. + */ +#if( configUSE_TICKLESS_IDLE == 1 ) + static uint32_t ulTimerCountsForOneTick = 0; +#endif /* configUSE_TICKLESS_IDLE */ + +/* + * The maximum number of tick periods that can be suppressed is limited by the + * 24 bit resolution of the SysTick timer. + */ +#if( configUSE_TICKLESS_IDLE == 1 ) + static uint32_t xMaximumPossibleSuppressedTicks = 0; +#endif /* configUSE_TICKLESS_IDLE */ + +/* + * Compensate for the CPU cycles that pass while the SysTick is stopped (low + * power functionality only. + */ +#if( configUSE_TICKLESS_IDLE == 1 ) + static uint32_t ulStoppedTimerCompensation = 0; +#endif /* configUSE_TICKLESS_IDLE */ + +/* + * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure + * FreeRTOS API functions are not called from interrupts that have been assigned + * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY. + */ +#if( configASSERT_DEFINED == 1 ) + static uint8_t ucMaxSysCallPriority = 0; + static uint32_t ulMaxPRIGROUPValue = 0; + static const volatile uint8_t * const pcInterruptPriorityRegisters = ( const volatile uint8_t * const ) portNVIC_IP_REGISTERS_OFFSET_16; +#endif /* configASSERT_DEFINED */ + +/*-----------------------------------------------------------*/ + +/* + * See header file for description. + */ +StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) +{ + /* Simulate the stack frame as it would be created by a context switch + interrupt. */ + + /* Offset added to account for the way the MCU uses the stack on entry/exit + of interrupts, and to ensure alignment. */ + pxTopOfStack--; + + *pxTopOfStack = portINITIAL_XPSR; /* xPSR */ + pxTopOfStack--; + *pxTopOfStack = ( ( StackType_t ) pxCode ) & portSTART_ADDRESS_MASK; /* PC */ + pxTopOfStack--; + *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */ + + /* Save code space by skipping register initialisation. */ + pxTopOfStack -= 5; /* R12, R3, R2 and R1. */ + *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */ + + /* A save method is being used that requires each task to maintain its + own exec return value. */ + pxTopOfStack--; + *pxTopOfStack = portINITIAL_EXC_RETURN; + + pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */ + + return pxTopOfStack; +} +/*-----------------------------------------------------------*/ + +static void prvTaskExitError( void ) +{ +volatile uint32_t ulDummy = 0; + + /* A function that implements a task must not exit or attempt to return to + its caller as there is nothing to return to. If a task wants to exit it + should instead call vTaskDelete( NULL ). + + Artificially force an assert() to be triggered if configASSERT() is + defined, then stop here so application writers can catch the error. */ + configASSERT( uxCriticalNesting == ~0UL ); + portDISABLE_INTERRUPTS(); + while( ulDummy == 0 ) + { + /* This file calls prvTaskExitError() after the scheduler has been + started to remove a compiler warning about the function being defined + but never called. ulDummy is used purely to quieten other warnings + about code appearing after this function is called - making ulDummy + volatile makes the compiler think the function could return and + therefore not output an 'unreachable code' warning for code that appears + after it. */ + } +} +/*-----------------------------------------------------------*/ + +void vPortSVCHandler( void ) +{ + __asm volatile ( + " ldr r3, pxCurrentTCBConst2 \n" /* Restore the context. */ + " ldr r1, [r3] \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */ + " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */ + " ldmia r0!, {r4-r11, r14} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */ + " msr psp, r0 \n" /* Restore the task stack pointer. */ + " isb \n" + " mov r0, #0 \n" + " msr basepri, r0 \n" + " bx r14 \n" + " \n" + " .align 4 \n" + "pxCurrentTCBConst2: .word pxCurrentTCB \n" + ); +} +/*-----------------------------------------------------------*/ + +static void prvPortStartFirstTask( void ) +{ + /* Start the first task. This also clears the bit that indicates the FPU is + in use in case the FPU was used before the scheduler was started - which + would otherwise result in the unnecessary leaving of space in the SVC stack + for lazy saving of FPU registers. */ + __asm volatile( + " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */ + " ldr r0, [r0] \n" + " ldr r0, [r0] \n" + " msr msp, r0 \n" /* Set the msp back to the start of the stack. */ + " mov r0, #0 \n" /* Clear the bit that indicates the FPU is in use, see comment above. */ + " msr control, r0 \n" + " cpsie i \n" /* Globally enable interrupts. */ + " cpsie f \n" + " dsb \n" + " isb \n" + " svc 0 \n" /* System call to start first task. */ + " nop \n" + ); +} +/*-----------------------------------------------------------*/ + +/* + * See header file for description. + */ +BaseType_t xPortStartScheduler( void ) +{ + /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0. + See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */ + configASSERT( configMAX_SYSCALL_INTERRUPT_PRIORITY ); + + /* This port can be used on all revisions of the Cortex-M7 core other than + the r0p1 parts. r0p1 parts should use the port from the + /source/portable/GCC/ARM_CM7/r0p1 directory. */ + configASSERT( portCPUID != portCORTEX_M7_r0p1_ID ); + configASSERT( portCPUID != portCORTEX_M7_r0p0_ID ); + + #if( configASSERT_DEFINED == 1 ) + { + volatile uint32_t ulOriginalPriority; + volatile uint8_t * const pucFirstUserPriorityRegister = ( volatile uint8_t * const ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER ); + volatile uint8_t ucMaxPriorityValue; + + /* Determine the maximum priority from which ISR safe FreeRTOS API + functions can be called. ISR safe functions are those that end in + "FromISR". FreeRTOS maintains separate thread and ISR API functions to + ensure interrupt entry is as fast and simple as possible. + + Save the interrupt priority value that is about to be clobbered. */ + ulOriginalPriority = *pucFirstUserPriorityRegister; + + /* Determine the number of priority bits available. First write to all + possible bits. */ + *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE; + + /* Read the value back to see how many bits stuck. */ + ucMaxPriorityValue = *pucFirstUserPriorityRegister; + + /* Use the same mask on the maximum system call priority. */ + ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue; + + /* Calculate the maximum acceptable priority group value for the number + of bits read back. */ + ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS; + while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE ) + { + ulMaxPRIGROUPValue--; + ucMaxPriorityValue <<= ( uint8_t ) 0x01; + } + + #ifdef __NVIC_PRIO_BITS + { + /* Check the CMSIS configuration that defines the number of + priority bits matches the number of priority bits actually queried + from the hardware. */ + configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS ); + } + #endif + + #ifdef configPRIO_BITS + { + /* Check the FreeRTOS configuration that defines the number of + priority bits matches the number of priority bits actually queried + from the hardware. */ + configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS ); + } + #endif + + /* Shift the priority group value back to its position within the AIRCR + register. */ + ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT; + ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK; + + /* Restore the clobbered interrupt priority register to its original + value. */ + *pucFirstUserPriorityRegister = ulOriginalPriority; + } + #endif /* conifgASSERT_DEFINED */ + + /* Make PendSV and SysTick the lowest priority interrupts. */ + portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI; + portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI; + + /* Start the timer that generates the tick ISR. Interrupts are disabled + here already. */ + vPortSetupTimerInterrupt(); + + /* Initialise the critical nesting count ready for the first task. */ + uxCriticalNesting = 0; + + /* Ensure the VFP is enabled - it should be anyway. */ + vPortEnableVFP(); + + /* Lazy save always. */ + *( portFPCCR ) |= portASPEN_AND_LSPEN_BITS; + + /* Start the first task. */ + prvPortStartFirstTask(); + + /* Should never get here as the tasks will now be executing! Call the task + exit error function to prevent compiler warnings about a static function + not being called in the case that the application writer overrides this + functionality by defining configTASK_RETURN_ADDRESS. Call + vTaskSwitchContext() so link time optimisation does not remove the + symbol. */ + vTaskSwitchContext(); + prvTaskExitError(); + + /* Should not get here! */ + return 0; +} +/*-----------------------------------------------------------*/ + +void vPortEndScheduler( void ) +{ + /* Not implemented in ports where there is nothing to return to. + Artificially force an assert. */ + configASSERT( uxCriticalNesting == 1000UL ); +} +/*-----------------------------------------------------------*/ + +void vPortEnterCritical( void ) +{ + portDISABLE_INTERRUPTS(); + uxCriticalNesting++; + + /* This is not the interrupt safe version of the enter critical function so + assert() if it is being called from an interrupt context. Only API + functions that end in "FromISR" can be used in an interrupt. Only assert if + the critical nesting count is 1 to protect against recursive calls if the + assert function also uses a critical section. */ + if( uxCriticalNesting == 1 ) + { + configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 ); + } +} +/*-----------------------------------------------------------*/ + +void vPortExitCritical( void ) +{ + configASSERT( uxCriticalNesting ); + uxCriticalNesting--; + if( uxCriticalNesting == 0 ) + { + portENABLE_INTERRUPTS(); + } +} +/*-----------------------------------------------------------*/ + +void xPortPendSVHandler( void ) +{ + /* This is a naked function. */ + + __asm volatile + ( + " mrs r0, psp \n" + " isb \n" + " \n" + " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */ + " ldr r2, [r3] \n" + " \n" + " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, push high vfp registers. */ + " it eq \n" + " vstmdbeq r0!, {s16-s31} \n" + " \n" + " stmdb r0!, {r4-r11, r14} \n" /* Save the core registers. */ + " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */ + " \n" + " stmdb sp!, {r0, r3} \n" + " mov r0, %0 \n" + " msr basepri, r0 \n" + " dsb \n" + " isb \n" + " bl vTaskSwitchContext \n" + " mov r0, #0 \n" + " msr basepri, r0 \n" + " ldmia sp!, {r0, r3} \n" + " \n" + " ldr r1, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */ + " ldr r0, [r1] \n" + " \n" + " ldmia r0!, {r4-r11, r14} \n" /* Pop the core registers. */ + " \n" + " tst r14, #0x10 \n" /* Is the task using the FPU context? If so, pop the high vfp registers too. */ + " it eq \n" + " vldmiaeq r0!, {s16-s31} \n" + " \n" + " msr psp, r0 \n" + " isb \n" + " \n" + #ifdef WORKAROUND_PMU_CM001 /* XMC4000 specific errata workaround. */ + #if WORKAROUND_PMU_CM001 == 1 + " push { r14 } \n" + " pop { pc } \n" + #endif + #endif + " \n" + " bx r14 \n" + " \n" + " .align 4 \n" + "pxCurrentTCBConst: .word pxCurrentTCB \n" + ::"i"(configMAX_SYSCALL_INTERRUPT_PRIORITY) + ); +} +/*-----------------------------------------------------------*/ + +void xPortSysTickHandler( void ) +{ + /* The SysTick runs at the lowest interrupt priority, so when this interrupt + executes all interrupts must be unmasked. There is therefore no need to + save and then restore the interrupt mask value as its value is already + known. */ + portDISABLE_INTERRUPTS(); + { + /* Increment the RTOS tick. */ + if( xTaskIncrementTick() != pdFALSE ) + { + /* A context switch is required. Context switching is performed in + the PendSV interrupt. Pend the PendSV interrupt. */ + portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; + } + } + portENABLE_INTERRUPTS(); +} +/*-----------------------------------------------------------*/ + +#if( configUSE_TICKLESS_IDLE == 1 ) + + __attribute__((weak)) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ) + { + uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements; + TickType_t xModifiableIdleTime; + + /* Make sure the SysTick reload value does not overflow the counter. */ + if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks ) + { + xExpectedIdleTime = xMaximumPossibleSuppressedTicks; + } + + /* Stop the SysTick momentarily. The time the SysTick is stopped for + is accounted for as best it can be, but using the tickless mode will + inevitably result in some tiny drift of the time maintained by the + kernel with respect to calendar time. */ + portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT; + + /* Calculate the reload value required to wait xExpectedIdleTime + tick periods. -1 is used because this code will execute part way + through one of the tick periods. */ + ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) ); + if( ulReloadValue > ulStoppedTimerCompensation ) + { + ulReloadValue -= ulStoppedTimerCompensation; + } + + /* Enter a critical section but don't use the taskENTER_CRITICAL() + method as that will mask interrupts that should exit sleep mode. */ + __asm volatile( "cpsid i" ::: "memory" ); + __asm volatile( "dsb" ); + __asm volatile( "isb" ); + + /* If a context switch is pending or a task is waiting for the scheduler + to be unsuspended then abandon the low power entry. */ + if( eTaskConfirmSleepModeStatus() == eAbortSleep ) + { + /* Restart from whatever is left in the count register to complete + this tick period. */ + portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG; + + /* Restart SysTick. */ + portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; + + /* Reset the reload register to the value required for normal tick + periods. */ + portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; + + /* Re-enable interrupts - see comments above the cpsid instruction() + above. */ + __asm volatile( "cpsie i" ::: "memory" ); + } + else + { + /* Set the new reload value. */ + portNVIC_SYSTICK_LOAD_REG = ulReloadValue; + + /* Clear the SysTick count flag and set the count value back to + zero. */ + portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; + + /* Restart SysTick. */ + portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; + + /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can + set its parameter to 0 to indicate that its implementation contains + its own wait for interrupt or wait for event instruction, and so wfi + should not be executed again. However, the original expected idle + time variable must remain unmodified, so a copy is taken. */ + xModifiableIdleTime = xExpectedIdleTime; + configPRE_SLEEP_PROCESSING( xModifiableIdleTime ); + if( xModifiableIdleTime > 0 ) + { + __asm volatile( "dsb" ::: "memory" ); + __asm volatile( "wfi" ); + __asm volatile( "isb" ); + } + configPOST_SLEEP_PROCESSING( xExpectedIdleTime ); + + /* Re-enable interrupts to allow the interrupt that brought the MCU + out of sleep mode to execute immediately. see comments above + __disable_interrupt() call above. */ + __asm volatile( "cpsie i" ::: "memory" ); + __asm volatile( "dsb" ); + __asm volatile( "isb" ); + + /* Disable interrupts again because the clock is about to be stopped + and interrupts that execute while the clock is stopped will increase + any slippage between the time maintained by the RTOS and calendar + time. */ + __asm volatile( "cpsid i" ::: "memory" ); + __asm volatile( "dsb" ); + __asm volatile( "isb" ); + + /* Disable the SysTick clock without reading the + portNVIC_SYSTICK_CTRL_REG register to ensure the + portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again, + the time the SysTick is stopped for is accounted for as best it can + be, but using the tickless mode will inevitably result in some tiny + drift of the time maintained by the kernel with respect to calendar + time*/ + portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT ); + + /* Determine if the SysTick clock has already counted to zero and + been set back to the current reload value (the reload back being + correct for the entire expected idle time) or if the SysTick is yet + to count to zero (in which case an interrupt other than the SysTick + must have brought the system out of sleep mode). */ + if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 ) + { + uint32_t ulCalculatedLoadValue; + + /* The tick interrupt is already pending, and the SysTick count + reloaded with ulReloadValue. Reset the + portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick + period. */ + ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG ); + + /* Don't allow a tiny value, or values that have somehow + underflowed because the post sleep hook did something + that took too long. */ + if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) ) + { + ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ); + } + + portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue; + + /* As the pending tick will be processed as soon as this + function exits, the tick value maintained by the tick is stepped + forward by one less than the time spent waiting. */ + ulCompleteTickPeriods = xExpectedIdleTime - 1UL; + } + else + { + /* Something other than the tick interrupt ended the sleep. + Work out how long the sleep lasted rounded to complete tick + periods (not the ulReload value which accounted for part + ticks). */ + ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG; + + /* How many complete tick periods passed while the processor + was waiting? */ + ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick; + + /* The reload value is set to whatever fraction of a single tick + period remains. */ + portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements; + } + + /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG + again, then set portNVIC_SYSTICK_LOAD_REG back to its standard + value. */ + portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; + portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT; + vTaskStepTick( ulCompleteTickPeriods ); + portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL; + + /* Exit with interrupts enabled. */ + __asm volatile( "cpsie i" ::: "memory" ); + } + } + +#endif /* #if configUSE_TICKLESS_IDLE */ +/*-----------------------------------------------------------*/ + +/* + * Setup the systick timer to generate the tick interrupts at the required + * frequency. + */ +__attribute__(( weak )) void vPortSetupTimerInterrupt( void ) +{ + /* Calculate the constants required to configure the tick interrupt. */ + #if( configUSE_TICKLESS_IDLE == 1 ) + { + ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ); + xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick; + ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ ); + } + #endif /* configUSE_TICKLESS_IDLE */ + + /* Stop and clear the SysTick. */ + portNVIC_SYSTICK_CTRL_REG = 0UL; + portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL; + + /* Configure SysTick to interrupt at the requested rate. */ + portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL; + portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT ); +} +/*-----------------------------------------------------------*/ + +/* This is a naked function. */ +static void vPortEnableVFP( void ) +{ + __asm volatile + ( + " ldr.w r0, =0xE000ED88 \n" /* The FPU enable bits are in the CPACR. */ + " ldr r1, [r0] \n" + " \n" + " orr r1, r1, #( 0xf << 20 ) \n" /* Enable CP10 and CP11 coprocessors, then save back. */ + " str r1, [r0] \n" + " bx r14 " + ); +} +/*-----------------------------------------------------------*/ + +#if( configASSERT_DEFINED == 1 ) + + void vPortValidateInterruptPriority( void ) + { + uint32_t ulCurrentInterrupt; + uint8_t ucCurrentPriority; + + /* Obtain the number of the currently executing interrupt. */ + __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" ); + + /* Is the interrupt number a user defined interrupt? */ + if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER ) + { + /* Look up the interrupt's priority. */ + ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ]; + + /* The following assertion will fail if a service routine (ISR) for + an interrupt that has been assigned a priority above + configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API + function. ISR safe FreeRTOS API functions must *only* be called + from interrupts that have been assigned a priority at or below + configMAX_SYSCALL_INTERRUPT_PRIORITY. + + Numerically low interrupt priority numbers represent logically high + interrupt priorities, therefore the priority of the interrupt must + be set to a value equal to or numerically *higher* than + configMAX_SYSCALL_INTERRUPT_PRIORITY. + + Interrupts that use the FreeRTOS API must not be left at their + default priority of zero as that is the highest possible priority, + which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY, + and therefore also guaranteed to be invalid. + + FreeRTOS maintains separate thread and ISR API functions to ensure + interrupt entry is as fast and simple as possible. + + The following links provide detailed information: + http://www.freertos.org/RTOS-Cortex-M3-M4.html + http://www.freertos.org/FAQHelp.html */ + configASSERT( ucCurrentPriority >= ucMaxSysCallPriority ); + } + + /* Priority grouping: The interrupt controller (NVIC) allows the bits + that define each interrupt's priority to be split between bits that + define the interrupt's pre-emption priority bits and bits that define + the interrupt's sub-priority. For simplicity all bits must be defined + to be pre-emption priority bits. The following assertion will fail if + this is not the case (if some bits represent a sub-priority). + + If the application only uses CMSIS libraries for interrupt + configuration then the correct setting can be achieved on all Cortex-M + devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the + scheduler. Note however that some vendor specific peripheral libraries + assume a non-zero priority group setting, in which cases using a value + of zero will result in unpredictable behaviour. */ + configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue ); + } + +#endif /* configASSERT_DEFINED */ + + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h b/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h new file mode 100644 index 0000000..d0a566a --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/portable/GCC/ARM_CM4F/portmacro.h @@ -0,0 +1,243 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + + +#ifndef PORTMACRO_H +#define PORTMACRO_H + +#ifdef __cplusplus +extern "C" { +#endif + +/*----------------------------------------------------------- + * Port specific definitions. + * + * The settings in this file configure FreeRTOS correctly for the + * given hardware and compiler. + * + * These settings should not be altered. + *----------------------------------------------------------- + */ + +/* Type definitions. */ +#define portCHAR char +#define portFLOAT float +#define portDOUBLE double +#define portLONG long +#define portSHORT short +#define portSTACK_TYPE uint32_t +#define portBASE_TYPE long + +typedef portSTACK_TYPE StackType_t; +typedef long BaseType_t; +typedef unsigned long UBaseType_t; + +#if( configUSE_16_BIT_TICKS == 1 ) + typedef uint16_t TickType_t; + #define portMAX_DELAY ( TickType_t ) 0xffff +#else + typedef uint32_t TickType_t; + #define portMAX_DELAY ( TickType_t ) 0xffffffffUL + + /* 32-bit tick type on a 32-bit architecture, so reads of the tick count do + not need to be guarded with a critical section. */ + #define portTICK_TYPE_IS_ATOMIC 1 +#endif +/*-----------------------------------------------------------*/ + +/* Architecture specifics. */ +#define portSTACK_GROWTH ( -1 ) +#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ ) +#define portBYTE_ALIGNMENT 8 +/*-----------------------------------------------------------*/ + +/* Scheduler utilities. */ +#define portYIELD() \ +{ \ + /* Set a PendSV to request a context switch. */ \ + portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT; \ + \ + /* Barriers are normally not required but do ensure the code is completely \ + within the specified behaviour for the architecture. */ \ + __asm volatile( "dsb" ::: "memory" ); \ + __asm volatile( "isb" ); \ +} + +#define portNVIC_INT_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000ed04 ) ) +#define portNVIC_PENDSVSET_BIT ( 1UL << 28UL ) +#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired != pdFALSE ) portYIELD() +#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x ) +/*-----------------------------------------------------------*/ + +/* Critical section management. */ +extern void vPortEnterCritical( void ); +extern void vPortExitCritical( void ); +#define portSET_INTERRUPT_MASK_FROM_ISR() ulPortRaiseBASEPRI() +#define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vPortSetBASEPRI(x) +#define portDISABLE_INTERRUPTS() vPortRaiseBASEPRI() +#define portENABLE_INTERRUPTS() vPortSetBASEPRI(0) +#define portENTER_CRITICAL() vPortEnterCritical() +#define portEXIT_CRITICAL() vPortExitCritical() + +/*-----------------------------------------------------------*/ + +/* Task function macros as described on the FreeRTOS.org WEB site. These are +not necessary for to use this port. They are defined so the common demo files +(which build with all the ports) will build. */ +#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters ) +#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters ) +/*-----------------------------------------------------------*/ + +/* Tickless idle/low power functionality. */ +#ifndef portSUPPRESS_TICKS_AND_SLEEP + extern void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime ); + #define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) vPortSuppressTicksAndSleep( xExpectedIdleTime ) +#endif +/*-----------------------------------------------------------*/ + +/* Architecture specific optimisations. */ +#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION + #define configUSE_PORT_OPTIMISED_TASK_SELECTION 1 +#endif + +#if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1 + + /* Generic helper function. */ + __attribute__( ( always_inline ) ) static inline uint8_t ucPortCountLeadingZeros( uint32_t ulBitmap ) + { + uint8_t ucReturn; + + __asm volatile ( "clz %0, %1" : "=r" ( ucReturn ) : "r" ( ulBitmap ) : "memory" ); + return ucReturn; + } + + /* Check the configuration. */ + #if( configMAX_PRIORITIES > 32 ) + #error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32. It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice. + #endif + + /* Store/clear the ready priorities in a bit map. */ + #define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) ) + #define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) ) + + /*-----------------------------------------------------------*/ + + #define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31UL - ( uint32_t ) ucPortCountLeadingZeros( ( uxReadyPriorities ) ) ) + +#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ + +/*-----------------------------------------------------------*/ + +#ifdef configASSERT + void vPortValidateInterruptPriority( void ); + #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() vPortValidateInterruptPriority() +#endif + +/* portNOP() is not required by this port. */ +#define portNOP() + +#define portINLINE __inline + +#ifndef portFORCE_INLINE + #define portFORCE_INLINE inline __attribute__(( always_inline)) +#endif + +portFORCE_INLINE static BaseType_t xPortIsInsideInterrupt( void ) +{ +uint32_t ulCurrentInterrupt; +BaseType_t xReturn; + + /* Obtain the number of the currently executing interrupt. */ + __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" ); + + if( ulCurrentInterrupt == 0 ) + { + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + + return xReturn; +} + +/*-----------------------------------------------------------*/ + +portFORCE_INLINE static void vPortRaiseBASEPRI( void ) +{ +uint32_t ulNewBASEPRI; + + __asm volatile + ( + " mov %0, %1 \n" \ + " msr basepri, %0 \n" \ + " isb \n" \ + " dsb \n" \ + :"=r" (ulNewBASEPRI) : "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "memory" + ); +} + +/*-----------------------------------------------------------*/ + +portFORCE_INLINE static uint32_t ulPortRaiseBASEPRI( void ) +{ +uint32_t ulOriginalBASEPRI, ulNewBASEPRI; + + __asm volatile + ( + " mrs %0, basepri \n" \ + " mov %1, %2 \n" \ + " msr basepri, %1 \n" \ + " isb \n" \ + " dsb \n" \ + :"=r" (ulOriginalBASEPRI), "=r" (ulNewBASEPRI) : "i" ( configMAX_SYSCALL_INTERRUPT_PRIORITY ) : "memory" + ); + + /* This return will not be reached but is necessary to prevent compiler + warnings. */ + return ulOriginalBASEPRI; +} +/*-----------------------------------------------------------*/ + +portFORCE_INLINE static void vPortSetBASEPRI( uint32_t ulNewMaskValue ) +{ + __asm volatile + ( + " msr basepri, %0 " :: "r" ( ulNewMaskValue ) : "memory" + ); +} +/*-----------------------------------------------------------*/ + +#define portMEMORY_BARRIER() __asm volatile( "" ::: "memory" ) + +#ifdef __cplusplus +} +#endif + +#endif /* PORTMACRO_H */ + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/portable/MemMang/heap_4.c b/Middlewares/Third_Party/FreeRTOS/Source/portable/MemMang/heap_4.c new file mode 100644 index 0000000..eaf443f --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/portable/MemMang/heap_4.c @@ -0,0 +1,492 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* + * A sample implementation of pvPortMalloc() and vPortFree() that combines + * (coalescences) adjacent memory blocks as they are freed, and in so doing + * limits memory fragmentation. + * + * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the + * memory management pages of http://www.FreeRTOS.org for more information. + */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining +all the API functions to use the MPU wrappers. That should only be done when +task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" + +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#if( configSUPPORT_DYNAMIC_ALLOCATION == 0 ) + #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0 +#endif + +/* Block sizes must not get too small. */ +#define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) ) + +/* Assumes 8bit bytes! */ +#define heapBITS_PER_BYTE ( ( size_t ) 8 ) + +/* Allocate the memory for the heap. */ +#if( configAPPLICATION_ALLOCATED_HEAP == 1 ) + /* The application writer has already defined the array used for the RTOS + heap - probably so it can be placed in a special segment or address. */ + extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; +#else + static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ]; +#endif /* configAPPLICATION_ALLOCATED_HEAP */ + +/* Define the linked list structure. This is used to link free blocks in order +of their memory address. */ +typedef struct A_BLOCK_LINK +{ + struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */ + size_t xBlockSize; /*<< The size of the free block. */ +} BlockLink_t; + +/*-----------------------------------------------------------*/ + +/* + * Inserts a block of memory that is being freed into the correct position in + * the list of free memory blocks. The block being freed will be merged with + * the block in front it and/or the block behind it if the memory blocks are + * adjacent to each other. + */ +static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ); + +/* + * Called automatically to setup the required heap structures the first time + * pvPortMalloc() is called. + */ +static void prvHeapInit( void ); + +/*-----------------------------------------------------------*/ + +/* The size of the structure placed at the beginning of each allocated memory +block must by correctly byte aligned. */ +static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + +/* Create a couple of list links to mark the start and end of the list. */ +static BlockLink_t xStart, *pxEnd = NULL; + +/* Keeps track of the number of calls to allocate and free memory as well as the +number of free bytes remaining, but says nothing about fragmentation. */ +static size_t xFreeBytesRemaining = 0U; +static size_t xMinimumEverFreeBytesRemaining = 0U; +static size_t xNumberOfSuccessfulAllocations = 0; +static size_t xNumberOfSuccessfulFrees = 0; + +/* Gets set to the top bit of an size_t type. When this bit in the xBlockSize +member of an BlockLink_t structure is set then the block belongs to the +application. When the bit is free the block is still part of the free heap +space. */ +static size_t xBlockAllocatedBit = 0; + +/*-----------------------------------------------------------*/ + +void *pvPortMalloc( size_t xWantedSize ) +{ +BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink; +void *pvReturn = NULL; + + vTaskSuspendAll(); + { + /* If this is the first call to malloc then the heap will require + initialisation to setup the list of free blocks. */ + if( pxEnd == NULL ) + { + prvHeapInit(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Check the requested block size is not so large that the top bit is + set. The top bit of the block size member of the BlockLink_t structure + is used to determine who owns the block - the application or the + kernel, so it must be free. */ + if( ( xWantedSize & xBlockAllocatedBit ) == 0 ) + { + /* The wanted size is increased so it can contain a BlockLink_t + structure in addition to the requested amount of bytes. */ + if( xWantedSize > 0 ) + { + xWantedSize += xHeapStructSize; + + /* Ensure that blocks are always aligned to the required number + of bytes. */ + if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 ) + { + /* Byte alignment required. */ + xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ); + configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) ) + { + /* Traverse the list from the start (lowest address) block until + one of adequate size is found. */ + pxPreviousBlock = &xStart; + pxBlock = xStart.pxNextFreeBlock; + while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) ) + { + pxPreviousBlock = pxBlock; + pxBlock = pxBlock->pxNextFreeBlock; + } + + /* If the end marker was reached then a block of adequate size + was not found. */ + if( pxBlock != pxEnd ) + { + /* Return the memory space pointed to - jumping over the + BlockLink_t structure at its start. */ + pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize ); + + /* This block is being returned for use so must be taken out + of the list of free blocks. */ + pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock; + + /* If the block is larger than required it can be split into + two. */ + if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE ) + { + /* This block is to be split into two. Create a new + block following the number of bytes requested. The void + cast is used to prevent byte alignment warnings from the + compiler. */ + pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize ); + configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 ); + + /* Calculate the sizes of two blocks split from the + single block. */ + pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize; + pxBlock->xBlockSize = xWantedSize; + + /* Insert the new block into the list of free blocks. */ + prvInsertBlockIntoFreeList( pxNewBlockLink ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xFreeBytesRemaining -= pxBlock->xBlockSize; + + if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining ) + { + xMinimumEverFreeBytesRemaining = xFreeBytesRemaining; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The block is being returned - it is allocated and owned + by the application and has no "next" block. */ + pxBlock->xBlockSize |= xBlockAllocatedBit; + pxBlock->pxNextFreeBlock = NULL; + xNumberOfSuccessfulAllocations++; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceMALLOC( pvReturn, xWantedSize ); + } + ( void ) xTaskResumeAll(); + + #if( configUSE_MALLOC_FAILED_HOOK == 1 ) + { + if( pvReturn == NULL ) + { + extern void vApplicationMallocFailedHook( void ); + vApplicationMallocFailedHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif + + configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 ); + return pvReturn; +} +/*-----------------------------------------------------------*/ + +void vPortFree( void *pv ) +{ +uint8_t *puc = ( uint8_t * ) pv; +BlockLink_t *pxLink; + + if( pv != NULL ) + { + /* The memory being freed will have an BlockLink_t structure immediately + before it. */ + puc -= xHeapStructSize; + + /* This casting is to keep the compiler from issuing warnings. */ + pxLink = ( void * ) puc; + + /* Check the block is actually allocated. */ + configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ); + configASSERT( pxLink->pxNextFreeBlock == NULL ); + + if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 ) + { + if( pxLink->pxNextFreeBlock == NULL ) + { + /* The block is being returned to the heap - it is no longer + allocated. */ + pxLink->xBlockSize &= ~xBlockAllocatedBit; + + vTaskSuspendAll(); + { + /* Add this block to the list of free blocks. */ + xFreeBytesRemaining += pxLink->xBlockSize; + traceFREE( pv, pxLink->xBlockSize ); + prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) ); + xNumberOfSuccessfulFrees++; + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } +} +/*-----------------------------------------------------------*/ + +size_t xPortGetFreeHeapSize( void ) +{ + return xFreeBytesRemaining; +} +/*-----------------------------------------------------------*/ + +size_t xPortGetMinimumEverFreeHeapSize( void ) +{ + return xMinimumEverFreeBytesRemaining; +} +/*-----------------------------------------------------------*/ + +void vPortInitialiseBlocks( void ) +{ + /* This just exists to keep the linker quiet. */ +} +/*-----------------------------------------------------------*/ + +static void prvHeapInit( void ) +{ +BlockLink_t *pxFirstFreeBlock; +uint8_t *pucAlignedHeap; +size_t uxAddress; +size_t xTotalHeapSize = configTOTAL_HEAP_SIZE; + + /* Ensure the heap starts on a correctly aligned boundary. */ + uxAddress = ( size_t ) ucHeap; + + if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 ) + { + uxAddress += ( portBYTE_ALIGNMENT - 1 ); + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + xTotalHeapSize -= uxAddress - ( size_t ) ucHeap; + } + + pucAlignedHeap = ( uint8_t * ) uxAddress; + + /* xStart is used to hold a pointer to the first item in the list of free + blocks. The void cast is used to prevent compiler warnings. */ + xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap; + xStart.xBlockSize = ( size_t ) 0; + + /* pxEnd is used to mark the end of the list of free blocks and is inserted + at the end of the heap space. */ + uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize; + uxAddress -= xHeapStructSize; + uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK ); + pxEnd = ( void * ) uxAddress; + pxEnd->xBlockSize = 0; + pxEnd->pxNextFreeBlock = NULL; + + /* To start with there is a single free block that is sized to take up the + entire heap space, minus the space taken by pxEnd. */ + pxFirstFreeBlock = ( void * ) pucAlignedHeap; + pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock; + pxFirstFreeBlock->pxNextFreeBlock = pxEnd; + + /* Only one block exists - and it covers the entire usable heap space. */ + xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize; + + /* Work out the position of the top bit in a size_t variable. */ + xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ); +} +/*-----------------------------------------------------------*/ + +static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert ) +{ +BlockLink_t *pxIterator; +uint8_t *puc; + + /* Iterate through the list until a block is found that has a higher address + than the block being inserted. */ + for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock ) + { + /* Nothing to do here, just iterate to the right position. */ + } + + /* Do the block being inserted, and the block it is being inserted after + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxIterator; + if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert ) + { + pxIterator->xBlockSize += pxBlockToInsert->xBlockSize; + pxBlockToInsert = pxIterator; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Do the block being inserted, and the block it is being inserted before + make a contiguous block of memory? */ + puc = ( uint8_t * ) pxBlockToInsert; + if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock ) + { + if( pxIterator->pxNextFreeBlock != pxEnd ) + { + /* Form one big block from the two blocks. */ + pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize; + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock; + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxEnd; + } + } + else + { + pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; + } + + /* If the block being inserted plugged a gab, so was merged with the block + before and the block after, then it's pxNextFreeBlock pointer will have + already been set, and should not be set here as that would make it point + to itself. */ + if( pxIterator != pxBlockToInsert ) + { + pxIterator->pxNextFreeBlock = pxBlockToInsert; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +void vPortGetHeapStats( HeapStats_t *pxHeapStats ) +{ +BlockLink_t *pxBlock; +size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */ + + vTaskSuspendAll(); + { + pxBlock = xStart.pxNextFreeBlock; + + /* pxBlock will be NULL if the heap has not been initialised. The heap + is initialised automatically when the first allocation is made. */ + if( pxBlock != NULL ) + { + do + { + /* Increment the number of blocks and record the largest block seen + so far. */ + xBlocks++; + + if( pxBlock->xBlockSize > xMaxSize ) + { + xMaxSize = pxBlock->xBlockSize; + } + + if( pxBlock->xBlockSize < xMinSize ) + { + xMinSize = pxBlock->xBlockSize; + } + + /* Move to the next block in the chain until the last block is + reached. */ + pxBlock = pxBlock->pxNextFreeBlock; + } while( pxBlock != pxEnd ); + } + } + xTaskResumeAll(); + + pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize; + pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize; + pxHeapStats->xNumberOfFreeBlocks = xBlocks; + + taskENTER_CRITICAL(); + { + pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining; + pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations; + pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees; + pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining; + } + taskEXIT_CRITICAL(); +} + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/queue.c b/Middlewares/Third_Party/FreeRTOS/Source/queue.c new file mode 100644 index 0000000..b3203b8 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/queue.c @@ -0,0 +1,2945 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining +all the API functions to use the MPU wrappers. That should only be done when +task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" + +#if ( configUSE_CO_ROUTINES == 1 ) + #include "croutine.h" +#endif + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified +because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined +for the header files above, but not in this file, in order to generate the +correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + + +/* Constants used with the cRxLock and cTxLock structure members. */ +#define queueUNLOCKED ( ( int8_t ) -1 ) +#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 ) + +/* When the Queue_t structure is used to represent a base queue its pcHead and +pcTail members are used as pointers into the queue storage area. When the +Queue_t structure is used to represent a mutex pcHead and pcTail pointers are +not necessary, and the pcHead pointer is set to NULL to indicate that the +structure instead holds a pointer to the mutex holder (if any). Map alternative +names to the pcHead and structure member to ensure the readability of the code +is maintained. The QueuePointers_t and SemaphoreData_t types are used to form +a union as their usage is mutually exclusive dependent on what the queue is +being used for. */ +#define uxQueueType pcHead +#define queueQUEUE_IS_MUTEX NULL + +typedef struct QueuePointers +{ + int8_t *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */ + int8_t *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */ +} QueuePointers_t; + +typedef struct SemaphoreData +{ + TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */ + UBaseType_t uxRecursiveCallCount;/*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */ +} SemaphoreData_t; + +/* Semaphores do not actually store or copy data, so have an item size of +zero. */ +#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 ) +#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U ) + +#if( configUSE_PREEMPTION == 0 ) + /* If the cooperative scheduler is being used then a yield should not be + performed just because a higher priority task has been woken. */ + #define queueYIELD_IF_USING_PREEMPTION() +#else + #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() +#endif + +/* + * Definition of the queue used by the scheduler. + * Items are queued by copy, not reference. See the following link for the + * rationale: https://www.freertos.org/Embedded-RTOS-Queues.html + */ +typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +{ + int8_t *pcHead; /*< Points to the beginning of the queue storage area. */ + int8_t *pcWriteTo; /*< Points to the free next place in the storage area. */ + + union + { + QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */ + SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */ + } u; + + List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */ + List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */ + + volatile UBaseType_t uxMessagesWaiting;/*< The number of items currently in the queue. */ + UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */ + UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */ + + volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */ + + #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */ + #endif + + #if ( configUSE_QUEUE_SETS == 1 ) + struct QueueDefinition *pxQueueSetContainer; + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxQueueNumber; + uint8_t ucQueueType; + #endif + +} xQUEUE; + +/* The old xQUEUE name is maintained above then typedefed to the new Queue_t +name below to enable the use of older kernel aware debuggers. */ +typedef xQUEUE Queue_t; + +/*-----------------------------------------------------------*/ + +/* + * The queue registry is just a means for kernel aware debuggers to locate + * queue structures. It has no other purpose so is an optional component. + */ +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + /* The type stored within the queue registry array. This allows a name + to be assigned to each queue making kernel aware debugging a little + more user friendly. */ + typedef struct QUEUE_REGISTRY_ITEM + { + const char *pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + QueueHandle_t xHandle; + } xQueueRegistryItem; + + /* The old xQueueRegistryItem name is maintained above then typedefed to the + new xQueueRegistryItem name below to enable the use of older kernel aware + debuggers. */ + typedef xQueueRegistryItem QueueRegistryItem_t; + + /* The queue registry is simply an array of QueueRegistryItem_t structures. + The pcQueueName member of a structure being NULL is indicative of the + array position being vacant. */ + PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ]; + +#endif /* configQUEUE_REGISTRY_SIZE */ + +/* + * Unlocks a queue locked by a call to prvLockQueue. Locking a queue does not + * prevent an ISR from adding or removing items to the queue, but does prevent + * an ISR from removing tasks from the queue event lists. If an ISR finds a + * queue is locked it will instead increment the appropriate queue lock count + * to indicate that a task may require unblocking. When the queue in unlocked + * these lock counts are inspected, and the appropriate action taken. + */ +static void prvUnlockQueue( Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Uses a critical section to determine if there is any data in a queue. + * + * @return pdTRUE if the queue contains no items, otherwise pdFALSE. + */ +static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Uses a critical section to determine if there is any space in a queue. + * + * @return pdTRUE if there is no space, otherwise pdFALSE; + */ +static BaseType_t prvIsQueueFull( const Queue_t *pxQueue ) PRIVILEGED_FUNCTION; + +/* + * Copies an item into the queue, either at the front of the queue or the + * back of the queue. + */ +static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition ) PRIVILEGED_FUNCTION; + +/* + * Copies an item out of a queue. + */ +static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION; + +#if ( configUSE_QUEUE_SETS == 1 ) + /* + * Checks to see if a queue is a member of a queue set, and if so, notifies + * the queue set that the queue contains data. + */ + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; +#endif + +/* + * Called after a Queue_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ +static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION; + +/* + * Mutexes are a special type of queue. When a mutex is created, first the + * queue is created, then prvInitialiseMutex() is called to configure the queue + * as a mutex. + */ +#if( configUSE_MUTEXES == 1 ) + static void prvInitialiseMutex( Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION; +#endif + +#if( configUSE_MUTEXES == 1 ) + /* + * If a task waiting for a mutex causes the mutex holder to inherit a + * priority, but the waiting task times out, then the holder should + * disinherit the priority - but only down to the highest priority of any + * other tasks that are waiting for the same mutex. This function returns + * that priority. + */ + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION; +#endif +/*-----------------------------------------------------------*/ + +/* + * Macro to mark a queue as locked. Locking a queue prevents an ISR from + * accessing the queue event lists. + */ +#define prvLockQueue( pxQueue ) \ + taskENTER_CRITICAL(); \ + { \ + if( ( pxQueue )->cRxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \ + } \ + if( ( pxQueue )->cTxLock == queueUNLOCKED ) \ + { \ + ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \ + } \ + } \ + taskEXIT_CRITICAL() +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) +{ +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + + taskENTER_CRITICAL(); + { + pxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U; + pxQueue->pcWriteTo = pxQueue->pcHead; + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + pxQueue->cRxLock = queueUNLOCKED; + pxQueue->cTxLock = queueUNLOCKED; + + if( xNewQueue == pdFALSE ) + { + /* If there are tasks blocked waiting to read from the queue, then + the tasks will remain blocked as after this function exits the queue + will still be empty. If there are tasks blocked waiting to write to + the queue, then one should be unblocked as after this function exits + it will be possible to write to it. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Ensure the event queues start in the correct state. */ + vListInitialise( &( pxQueue->xTasksWaitingToSend ) ); + vListInitialise( &( pxQueue->xTasksWaitingToReceive ) ); + } + } + taskEXIT_CRITICAL(); + + /* A value is returned for calling semantic consistency with previous + versions. */ + return pdPASS; +} +/*-----------------------------------------------------------*/ + +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + + QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType ) + { + Queue_t *pxNewQueue; + + configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); + + /* The StaticQueue_t structure and the queue storage area must be + supplied. */ + configASSERT( pxStaticQueue != NULL ); + + /* A queue storage area should be provided if the item size is not 0, and + should not be provided if the item size is 0. */ + configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) ); + configASSERT( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) ); + + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticQueue_t or StaticSemaphore_t equals the size of + the real queue and semaphore structures. */ + volatile size_t xSize = sizeof( StaticQueue_t ); + configASSERT( xSize == sizeof( Queue_t ) ); + ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ + + /* The address of a statically allocated queue was passed in, use it. + The address of a statically allocated storage area was also passed in + but is already set. */ + pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ + + if( pxNewQueue != NULL ) + { + #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Queues can be allocated wither statically or dynamically, so + note this queue was allocated statically in case the queue is + later deleted. */ + pxNewQueue->ucStaticallyAllocated = pdTRUE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + traceQUEUE_CREATE_FAILED( ucQueueType ); + mtCOVERAGE_TEST_MARKER(); + } + + return pxNewQueue; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) + { + Queue_t *pxNewQueue; + size_t xQueueSizeInBytes; + uint8_t *pucQueueStorage; + + configASSERT( uxQueueLength > ( UBaseType_t ) 0 ); + + /* Allocate enough space to hold the maximum number of items that + can be in the queue at any time. It is valid for uxItemSize to be + zero in the case the queue is used as a semaphore. */ + xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + /* Allocate the queue and storage area. Justification for MISRA + deviation as follows: pvPortMalloc() always ensures returned memory + blocks are aligned per the requirements of the MCU stack. In this case + pvPortMalloc() must return a pointer that is guaranteed to meet the + alignment requirements of the Queue_t structure - which in this case + is an int8_t *. Therefore, whenever the stack alignment requirements + are greater than or equal to the pointer to char requirements the cast + is safe. In other cases alignment requirements are not strict (one or + two bytes). */ + pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */ + + if( pxNewQueue != NULL ) + { + /* Jump past the queue structure to find the location of the queue + storage area. */ + pucQueueStorage = ( uint8_t * ) pxNewQueue; + pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */ + + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* Queues can be created either statically or dynamically, so + note this task was created dynamically in case it is later + deleted. */ + pxNewQueue->ucStaticallyAllocated = pdFALSE; + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue ); + } + else + { + traceQUEUE_CREATE_FAILED( ucQueueType ); + mtCOVERAGE_TEST_MARKER(); + } + + return pxNewQueue; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) +{ + /* Remove compiler warnings about unused parameters should + configUSE_TRACE_FACILITY not be set to 1. */ + ( void ) ucQueueType; + + if( uxItemSize == ( UBaseType_t ) 0 ) + { + /* No RAM was allocated for the queue storage area, but PC head cannot + be set to NULL because NULL is used as a key to say the queue is used as + a mutex. Therefore just set pcHead to point to the queue as a benign + value that is known to be within the memory map. */ + pxNewQueue->pcHead = ( int8_t * ) pxNewQueue; + } + else + { + /* Set the head to the start of the queue storage area. */ + pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage; + } + + /* Initialise the queue members as described where the queue type is + defined. */ + pxNewQueue->uxLength = uxQueueLength; + pxNewQueue->uxItemSize = uxItemSize; + ( void ) xQueueGenericReset( pxNewQueue, pdTRUE ); + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + pxNewQueue->ucQueueType = ucQueueType; + } + #endif /* configUSE_TRACE_FACILITY */ + + #if( configUSE_QUEUE_SETS == 1 ) + { + pxNewQueue->pxQueueSetContainer = NULL; + } + #endif /* configUSE_QUEUE_SETS */ + + traceQUEUE_CREATE( pxNewQueue ); +} +/*-----------------------------------------------------------*/ + +#if( configUSE_MUTEXES == 1 ) + + static void prvInitialiseMutex( Queue_t *pxNewQueue ) + { + if( pxNewQueue != NULL ) + { + /* The queue create function will set all the queue structure members + correctly for a generic queue, but this function is creating a + mutex. Overwrite those members that need to be set differently - + in particular the information required for priority inheritance. */ + pxNewQueue->u.xSemaphore.xMutexHolder = NULL; + pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX; + + /* In case this is a recursive mutex. */ + pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0; + + traceCREATE_MUTEX( pxNewQueue ); + + /* Start with the semaphore in the expected state. */ + ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK ); + } + else + { + traceCREATE_MUTEX_FAILED(); + } + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + + xNewQueue = xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + + return xNewQueue; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue ) + { + QueueHandle_t xNewQueue; + const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0; + + /* Prevent compiler warnings about unused parameters if + configUSE_TRACE_FACILITY does not equal 1. */ + ( void ) ucQueueType; + + xNewQueue = xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType ); + prvInitialiseMutex( ( Queue_t * ) xNewQueue ); + + return xNewQueue; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + + TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; + Queue_t * const pxSemaphore = ( Queue_t * ) xSemaphore; + + /* This function is called by xSemaphoreGetMutexHolder(), and should not + be called directly. Note: This is a good way of determining if the + calling task is the mutex holder, but not a good way of determining the + identity of the mutex holder, as the holder may change between the + following critical section exiting and the function returning. */ + taskENTER_CRITICAL(); + { + if( pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } + } + taskEXIT_CRITICAL(); + + return pxReturn; + } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ + +#endif +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) ) + + TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore ) + { + TaskHandle_t pxReturn; + + configASSERT( xSemaphore ); + + /* Mutexes cannot be used in interrupt service routines, so the mutex + holder should not change in an ISR, and therefore a critical section is + not required here. */ + if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX ) + { + pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder; + } + else + { + pxReturn = NULL; + } + + return pxReturn; + } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */ + +#endif +/*-----------------------------------------------------------*/ + +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + + BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; + + configASSERT( pxMutex ); + + /* If this is the task that holds the mutex then xMutexHolder will not + change outside of this task. If this task does not hold the mutex then + pxMutexHolder can never coincidentally equal the tasks handle, and as + this is the only condition we are interested in it does not matter if + pxMutexHolder is accessed simultaneously by another task. Therefore no + mutual exclusion is required to test the pxMutexHolder variable. */ + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + traceGIVE_MUTEX_RECURSIVE( pxMutex ); + + /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to + the task handle, therefore no underflow check is required. Also, + uxRecursiveCallCount is only modified by the mutex holder, and as + there can only be one, no mutual exclusion is required to modify the + uxRecursiveCallCount member. */ + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--; + + /* Has the recursive call count unwound to 0? */ + if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 ) + { + /* Return the mutex. This will automatically unblock any other + task that might be waiting to access the mutex. */ + ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = pdPASS; + } + else + { + /* The mutex cannot be given because the calling task is not the + holder. */ + xReturn = pdFAIL; + + traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + + return xReturn; + } + +#endif /* configUSE_RECURSIVE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_RECURSIVE_MUTEXES == 1 ) + + BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxMutex = ( Queue_t * ) xMutex; + + configASSERT( pxMutex ); + + /* Comments regarding mutual exclusion as per those within + xQueueGiveMutexRecursive(). */ + + traceTAKE_MUTEX_RECURSIVE( pxMutex ); + + if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + xReturn = pdPASS; + } + else + { + xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait ); + + /* pdPASS will only be returned if the mutex was successfully + obtained. The calling task may have entered the Blocked state + before reaching here. */ + if( xReturn != pdFAIL ) + { + ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++; + } + else + { + traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex ); + } + } + + return xReturn; + } + +#endif /* configUSE_RECURSIVE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue ) + { + QueueHandle_t xHandle; + + configASSERT( uxMaxCount != 0 ); + configASSERT( uxInitialCount <= uxMaxCount ); + + xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } + + return xHandle; + } + +#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) + { + QueueHandle_t xHandle; + + configASSERT( uxMaxCount != 0 ); + configASSERT( uxInitialCount <= uxMaxCount ); + + xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE ); + + if( xHandle != NULL ) + { + ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount; + + traceCREATE_COUNTING_SEMAPHORE(); + } + else + { + traceCREATE_COUNTING_SEMAPHORE_FAILED(); + } + + return xHandle; + } + +#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition ) +{ +BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired; +TimeOut_t xTimeOut; +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + + /*lint -save -e904 This function relaxes the coding standard somewhat to + allow return statements within the function itself. This is done in the + interest of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + /* Is there room on the queue now? The running task must be the + highest priority task wanting to access the queue. If the head item + in the queue is to be overwritten then it does not matter if the + queue is full. */ + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + traceQUEUE_SEND( pxQueue ); + + #if ( configUSE_QUEUE_SETS == 1 ) + { + const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; + + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) + { + /* Do not notify the queue set as an existing item + was overwritten in the queue so the number of items + in the queue has not changed. */ + mtCOVERAGE_TEST_MARKER(); + } + else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + to the queue set caused a higher priority task to + unblock. A context switch is required. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If there was a task waiting for data to arrive on the + queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + our own so yield immediately. Yes it is ok to + do this from within the critical section - the + kernel takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + executed if the task was holding multiple mutexes + and the mutexes were given back in an order that is + different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + /* If there was a task waiting for data to arrive on the + queue then unblock it now. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The unblocked task has a priority higher than + our own so yield immediately. Yes it is ok to do + this from within the critical section - the kernel + takes care of that. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else if( xYieldRequired != pdFALSE ) + { + /* This path is a special case that will only get + executed if the task was holding multiple mutexes and + the mutexes were given back in an order that is + different to that in which they were taken. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was full and no block time is specified (or + the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + + /* Return to the original privilege level before exiting + the function. */ + traceQUEUE_SEND_FAILED( pxQueue ); + return errQUEUE_FULL; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was full and a block time was specified so + configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_SEND( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait ); + + /* Unlocking the queue means queue events can effect the + event list. It is possible that interrupts occurring now + remove this task from the event list again - but as the + scheduler is suspended the task will go onto the pending + ready last instead of the actual ready list. */ + prvUnlockQueue( pxQueue ); + + /* Resuming the scheduler will move tasks from the pending + ready list into the ready list - so it is feasible that this + task is already in a ready list before it yields - in which + case the yield will not cause a context switch unless there + is also a higher priority task in the pending ready list. */ + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + } + else + { + /* Try again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + traceQUEUE_SEND_FAILED( pxQueue ); + return errQUEUE_FULL; + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, const void * const pvItemToQueue, BaseType_t * const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition ) +{ +BaseType_t xReturn; +UBaseType_t uxSavedInterruptStatus; +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + /* Similar to xQueueGenericSend, except without blocking if there is no room + in the queue. Also don't directly wake a task that was blocked on a queue + read, instead return a flag to say whether a context switch is required or + not (i.e. has a task with a higher priority than us been woken by this + post). */ + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) ) + { + const int8_t cTxLock = pxQueue->cTxLock; + const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting; + + traceQUEUE_SEND_FROM_ISR( pxQueue ); + + /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a + semaphore or mutex. That means prvCopyDataToQueue() cannot result + in a task disinheriting a priority and prvCopyDataToQueue() can be + called here even though the disinherit function does not check if + the scheduler is suspended before accessing the ready lists. */ + ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition ); + + /* The event list is not altered if the queue is locked. This will + be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) ) + { + /* Do not notify the queue set as an existing item + was overwritten in the queue so the number of items + in the queue has not changed. */ + mtCOVERAGE_TEST_MARKER(); + } + else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting + to the queue set caused a higher priority task to + unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Not used in this path. */ + ( void ) uxPreviousMessagesWaiting; + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + knows that data was posted while it was locked. */ + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherPriorityTaskWoken ) +{ +BaseType_t xReturn; +UBaseType_t uxSavedInterruptStatus; +Queue_t * const pxQueue = xQueue; + + /* Similar to xQueueGenericSendFromISR() but used with semaphores where the + item size is 0. Don't directly wake a task that was blocked on a queue + read, instead return a flag to say whether a context switch is required or + not (i.e. has a task with a higher priority than us been woken by this + post). */ + + configASSERT( pxQueue ); + + /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR() + if the item size is not 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); + + /* Normally a mutex would not be given from an interrupt, especially if + there is a mutex holder, as priority inheritance makes no sense for an + interrupts, only tasks. */ + configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* When the queue is used to implement a semaphore no data is ever + moved through the queue but it is still valid to see if the queue 'has + space'. */ + if( uxMessagesWaiting < pxQueue->uxLength ) + { + const int8_t cTxLock = pxQueue->cTxLock; + + traceQUEUE_SEND_FROM_ISR( pxQueue ); + + /* A task can only have an inherited priority if it is a mutex + holder - and if there is a mutex holder then the mutex cannot be + given from an ISR. As this is the ISR version of the function it + can be assumed there is no mutex holder and no need to determine if + priority disinheritance is needed. Simply increase the count of + messages (semaphores) available. */ + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + + /* The event list is not altered if the queue is locked. This will + be done when the queue is unlocked later. */ + if( cTxLock == queueUNLOCKED ) + { + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The semaphore is a member of a queue set, and + posting to the queue set caused a higher priority + task to unblock. A context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so + record that a context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + context switch is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_QUEUE_SETS */ + } + else + { + /* Increment the lock count so the task that unlocks the queue + knows that data was posted while it was locked. */ + pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + + xReturn = pdPASS; + } + else + { + traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue ); + xReturn = errQUEUE_FULL; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) +{ +BaseType_t xEntryTimeSet = pdFALSE; +TimeOut_t xTimeOut; +Queue_t * const pxQueue = xQueue; + + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* The buffer into which data is received can only be NULL if the data size + is zero (so no data is copied into the buffer. */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + + /*lint -save -e904 This function relaxes the coding standard somewhat to + allow return statements within the function itself. This is done in the + interest of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data available, remove one item. */ + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_RECEIVE( pxQueue ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + + /* There is now space in the queue, were any tasks waiting to + post to the queue? If so, unblock the highest priority waiting + task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + configure the timeout structure. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* The timeout has not expired. If the queue is still empty place + the task on the list of tasks waiting to receive from the queue. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The queue contains data again. Loop back to try and read the + data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. If there is no data in the queue exit, otherwise loop + back and attempt to read the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait ) +{ +BaseType_t xEntryTimeSet = pdFALSE; +TimeOut_t xTimeOut; +Queue_t * const pxQueue = xQueue; + +#if( configUSE_MUTEXES == 1 ) + BaseType_t xInheritanceOccurred = pdFALSE; +#endif + + /* Check the queue pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* Check this really is a semaphore, in which case the item size will be + 0. */ + configASSERT( pxQueue->uxItemSize == 0 ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + + /*lint -save -e904 This function relaxes the coding standard somewhat to allow return + statements within the function itself. This is done in the interest + of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + /* Semaphores are queues with an item size of 0, and where the + number of messages in the queue is the semaphore's count value. */ + const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + must be the highest priority task wanting to access the queue. */ + if( uxSemaphoreCount > ( UBaseType_t ) 0 ) + { + traceQUEUE_RECEIVE( pxQueue ); + + /* Semaphores are queues with a data size of zero and where the + messages waiting is the semaphore's count. Reduce the count. */ + pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1; + + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* Record the information required to implement + priority inheritance should it become necessary. */ + pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + + /* Check to see if other tasks are blocked waiting to give the + semaphore, and if so, unblock the highest priority such task. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* For inheritance to have occurred there must have been an + initial timeout, and an adjusted timeout cannot become 0, as + if it were 0 the function would have exited. */ + #if( configUSE_MUTEXES == 1 ) + { + configASSERT( xInheritanceOccurred == pdFALSE ); + } + #endif /* configUSE_MUTEXES */ + + /* The semaphore count was 0 and no block time is specified + (or the block time has expired) so exit now. */ + taskEXIT_CRITICAL(); + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The semaphore count was 0 and a block time was specified + so configure the timeout structure ready to block. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can give to and take from the semaphore + now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* A block time is specified and not expired. If the semaphore + count is 0 then enter the Blocked state to wait for a semaphore to + become available. As semaphores are implemented with queues the + queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue ); + + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + taskENTER_CRITICAL(); + { + xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder ); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif + + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There was no timeout and the semaphore count was not 0, so + attempt to take the semaphore again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* Timed out. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + /* If the semaphore count is 0 exit now as the timeout has + expired. Otherwise return to attempt to take the semaphore that is + known to be available. As semaphores are implemented by queues the + queue being empty is equivalent to the semaphore count being 0. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + #if ( configUSE_MUTEXES == 1 ) + { + /* xInheritanceOccurred could only have be set if + pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to + test the mutex type again to check it is actually a mutex. */ + if( xInheritanceOccurred != pdFALSE ) + { + taskENTER_CRITICAL(); + { + UBaseType_t uxHighestWaitingPriority; + + /* This task blocking on the mutex caused another + task to inherit this task's priority. Now this task + has timed out the priority should be disinherited + again, but only as low as the next highest priority + task that is waiting for the same mutex. */ + uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue ); + vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority ); + } + taskEXIT_CRITICAL(); + } + } + #endif /* configUSE_MUTEXES */ + + traceQUEUE_RECEIVE_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait ) +{ +BaseType_t xEntryTimeSet = pdFALSE; +TimeOut_t xTimeOut; +int8_t *pcOriginalReadPosition; +Queue_t * const pxQueue = xQueue; + + /* Check the pointer is not NULL. */ + configASSERT( ( pxQueue ) ); + + /* The buffer into which data is received can only be NULL if the data size + is zero (so no data is copied into the buffer. */ + configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* Cannot block if the scheduler is suspended. */ + #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + { + configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) ); + } + #endif + + + /*lint -save -e904 This function relaxes the coding standard somewhat to + allow return statements within the function itself. This is done in the + interest of execution time efficiency. */ + for( ;; ) + { + taskENTER_CRITICAL(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Is there data in the queue now? To be running the calling task + must be the highest priority task wanting to access the queue. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Remember the read position so it can be reset after the data + is read from the queue as this function is only peeking the + data, not removing it. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + + prvCopyDataFromQueue( pxQueue, pvBuffer ); + traceQUEUE_PEEK( pxQueue ); + + /* The data is not being removed, so reset the read pointer. */ + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + + /* The data is being left in the queue, so see if there are + any other tasks waiting for the data. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than this task. */ + queueYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskEXIT_CRITICAL(); + return pdPASS; + } + else + { + if( xTicksToWait == ( TickType_t ) 0 ) + { + /* The queue was empty and no block time is specified (or + the block time has expired) so leave now. */ + taskEXIT_CRITICAL(); + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else if( xEntryTimeSet == pdFALSE ) + { + /* The queue was empty and a block time was specified so + configure the timeout structure ready to enter the blocked + state. */ + vTaskInternalSetTimeOutState( &xTimeOut ); + xEntryTimeSet = pdTRUE; + } + else + { + /* Entry time was already set. */ + mtCOVERAGE_TEST_MARKER(); + } + } + } + taskEXIT_CRITICAL(); + + /* Interrupts and other tasks can send to and receive from the queue + now the critical section has been exited. */ + + vTaskSuspendAll(); + prvLockQueue( pxQueue ); + + /* Update the timeout state to see if it has expired yet. */ + if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ) + { + /* Timeout has not expired yet, check to see if there is data in the + queue now, and if not enter the Blocked state to wait for data. */ + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceBLOCKING_ON_QUEUE_PEEK( pxQueue ); + vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait ); + prvUnlockQueue( pxQueue ); + if( xTaskResumeAll() == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* There is data in the queue now, so don't enter the blocked + state, instead return to try and obtain the data. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + } + } + else + { + /* The timeout has expired. If there is still no data in the queue + exit, otherwise go back and try to read the data again. */ + prvUnlockQueue( pxQueue ); + ( void ) xTaskResumeAll(); + + if( prvIsQueueEmpty( pxQueue ) != pdFALSE ) + { + traceQUEUE_PEEK_FAILED( pxQueue ); + return errQUEUE_EMPTY; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } /*lint -restore */ +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, void * const pvBuffer, BaseType_t * const pxHigherPriorityTaskWoken ) +{ +BaseType_t xReturn; +UBaseType_t uxSavedInterruptStatus; +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + /* Cannot block in an ISR, so check there is data available. */ + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + const int8_t cRxLock = pxQueue->cRxLock; + + traceQUEUE_RECEIVE_FROM_ISR( pxQueue ); + + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1; + + /* If the queue is locked the event list will not be modified. + Instead update the lock count so the task that unlocks the queue + will know that an ISR has removed data while the queue was + locked. */ + if( cRxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + /* The task waiting has a higher priority than us so + force a context switch. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Increment the lock count so the task that unlocks the queue + knows that data was removed while it was locked. */ + pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 ); + } + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) +{ +BaseType_t xReturn; +UBaseType_t uxSavedInterruptStatus; +int8_t *pcOriginalReadPosition; +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) ); + configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */ + + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* Cannot block in an ISR, so check there is data available. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + traceQUEUE_PEEK_FROM_ISR( pxQueue ); + + /* Remember the read position so it can be reset as nothing is + actually being removed from the queue. */ + pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom; + prvCopyDataFromQueue( pxQueue, pvBuffer ); + pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition; + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue ); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) +{ +UBaseType_t uxReturn; + + configASSERT( xQueue ); + + taskENTER_CRITICAL(); + { + uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); + + return uxReturn; +} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) +{ +UBaseType_t uxReturn; +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + + taskENTER_CRITICAL(); + { + uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; + } + taskEXIT_CRITICAL(); + + return uxReturn; +} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ +/*-----------------------------------------------------------*/ + +UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) +{ +UBaseType_t uxReturn; +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + uxReturn = pxQueue->uxMessagesWaiting; + + return uxReturn; +} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */ +/*-----------------------------------------------------------*/ + +void vQueueDelete( QueueHandle_t xQueue ) +{ +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + traceQUEUE_DELETE( pxQueue ); + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + vQueueUnregisterQueue( pxQueue ); + } + #endif + + #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) ) + { + /* The queue can only have been allocated dynamically - free it + again. */ + vPortFree( pxQueue ); + } + #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + { + /* The queue could have been allocated statically or dynamically, so + check before attempting to free the memory. */ + if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE ) + { + vPortFree( pxQueue ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #else + { + /* The queue must have been statically allocated, so is not going to be + deleted. Avoid compiler warnings about the unused parameter. */ + ( void ) pxQueue; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->uxQueueNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) + { + ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) + { + return ( ( Queue_t * ) xQueue )->ucQueueType; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if( configUSE_MUTEXES == 1 ) + + static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) + { + UBaseType_t uxHighestPriorityOfWaitingTasks; + + /* If a task waiting for a mutex causes the mutex holder to inherit a + priority, but the waiting task times out, then the holder should + disinherit the priority - but only down to the highest priority of any + other tasks that are waiting for the same mutex. For this purpose, + return the priority of the highest priority task that is waiting for the + mutex. */ + if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U ) + { + uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) ); + } + else + { + uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY; + } + + return uxHighestPriorityOfWaitingTasks; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition ) +{ +BaseType_t xReturn = pdFALSE; +UBaseType_t uxMessagesWaiting; + + /* This function is called from a critical section. */ + + uxMessagesWaiting = pxQueue->uxMessagesWaiting; + + if( pxQueue->uxItemSize == ( UBaseType_t ) 0 ) + { + #if ( configUSE_MUTEXES == 1 ) + { + if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) + { + /* The mutex is no longer being held. */ + xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder ); + pxQueue->u.xSemaphore.xMutexHolder = NULL; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_MUTEXES */ + } + else if( xPosition == queueSEND_TO_BACK ) + { + ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->pcWriteTo = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + ( void ) memcpy( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */ + pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize; + if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */ + { + pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xPosition == queueOVERWRITE ) + { + if( uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* An item is not being added but overwritten, so subtract + one from the recorded number of items in the queue so when + one is added again below the number of recorded items remains + correct. */ + --uxMessagesWaiting; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1; + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) +{ + if( pxQueue->uxItemSize != ( UBaseType_t ) 0 ) + { + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */ + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */ + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */ + } +} +/*-----------------------------------------------------------*/ + +static void prvUnlockQueue( Queue_t * const pxQueue ) +{ + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */ + + /* The lock counts contains the number of extra data items placed or + removed from the queue while the queue was locked. When a queue is + locked items can be added or removed, but the event lists cannot be + updated. */ + taskENTER_CRITICAL(); + { + int8_t cTxLock = pxQueue->cTxLock; + + /* See if data was added to the queue while it was locked. */ + while( cTxLock > queueLOCKED_UNMODIFIED ) + { + /* Data was posted while the queue was locked. Are any tasks + blocked waiting for data to become available? */ + #if ( configUSE_QUEUE_SETS == 1 ) + { + if( pxQueue->pxQueueSetContainer != NULL ) + { + if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE ) + { + /* The queue is a member of a queue set, and posting to + the queue set caused a higher priority task to unblock. + A context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* Tasks that are removed from the event list will get + added to the pending ready list as the scheduler is still + suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that a + context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + } + #else /* configUSE_QUEUE_SETS */ + { + /* Tasks that are removed from the event list will get added to + the pending ready list as the scheduler is still suspended. */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority so record that + a context switch is required. */ + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + break; + } + } + #endif /* configUSE_QUEUE_SETS */ + + --cTxLock; + } + + pxQueue->cTxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); + + /* Do the same for the Rx lock. */ + taskENTER_CRITICAL(); + { + int8_t cRxLock = pxQueue->cRxLock; + + while( cRxLock > queueLOCKED_UNMODIFIED ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + vTaskMissedYield(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + --cRxLock; + } + else + { + break; + } + } + + pxQueue->cRxLock = queueUNLOCKED; + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue ) +{ +BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) +{ +BaseType_t xReturn; +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ +/*-----------------------------------------------------------*/ + +static BaseType_t prvIsQueueFull( const Queue_t *pxQueue ) +{ +BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) +{ +BaseType_t xReturn; +Queue_t * const pxQueue = xQueue; + + configASSERT( pxQueue ); + if( pxQueue->uxMessagesWaiting == pxQueue->uxLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + /* If the queue is already full we may have to block. A critical section + is required to prevent an interrupt removing something from the queue + between the check to see if the queue is full and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( prvIsQueueFull( pxQueue ) != pdFALSE ) + { + /* The queue is full - do we want to block or just leave without + posting? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is called from a coroutine we cannot block directly, but + return indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + } + portENABLE_INTERRUPTS(); + + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + /* There is room in the queue, copy the data into the queue. */ + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + xReturn = pdPASS; + + /* Were any co-routines waiting for data to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + into the ready list as we are within a critical section. + Instead the same pending ready list mechanism is used as if + the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The co-routine waiting has a higher priority so record + that a yield might be appropriate. */ + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = errQUEUE_FULL; + } + } + portENABLE_INTERRUPTS(); + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + /* If the queue is already empty we may have to block. A critical section + is required to prevent an interrupt adding something to the queue + between the check to see if the queue is empty and blocking on the queue. */ + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 ) + { + /* There are no messages in the queue, do we want to block or just + leave with nothing? */ + if( xTicksToWait > ( TickType_t ) 0 ) + { + /* As this is a co-routine we cannot block directly, but return + indicating that we need to block. */ + vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) ); + portENABLE_INTERRUPTS(); + return errQUEUE_BLOCKED; + } + else + { + portENABLE_INTERRUPTS(); + return errQUEUE_FULL; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portENABLE_INTERRUPTS(); + + portDISABLE_INTERRUPTS(); + { + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Data is available from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + + xReturn = pdPASS; + + /* Were any co-routines waiting for space to become available? */ + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + /* In this instance the co-routine could be placed directly + into the ready list as we are within a critical section. + Instead the same pending ready list mechanism is used as if + the event were caused from within an interrupt. */ + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + xReturn = errQUEUE_YIELD; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xReturn = pdFAIL; + } + } + portENABLE_INTERRUPTS(); + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken ) + { + Queue_t * const pxQueue = xQueue; + + /* Cannot block within an ISR so if there is no space on the queue then + exit without doing anything. */ + if( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) + { + prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK ); + + /* We only want to wake one co-routine per ISR, so check that a + co-routine has not already been woken. */ + if( xCoRoutinePreviouslyWoken == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE ) + { + return pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xCoRoutinePreviouslyWoken; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_CO_ROUTINES == 1 ) + + BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxCoRoutineWoken ) + { + BaseType_t xReturn; + Queue_t * const pxQueue = xQueue; + + /* We cannot block from an ISR, so check there is data available. If + not then just leave without doing anything. */ + if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 ) + { + /* Copy the data from the queue. */ + pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; + if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) + { + pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + --( pxQueue->uxMessagesWaiting ); + ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize ); + + if( ( *pxCoRoutineWoken ) == pdFALSE ) + { + if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE ) + { + if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE ) + { + *pxCoRoutineWoken = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + + return xReturn; + } + +#endif /* configUSE_CO_ROUTINES */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t ux; + + /* See if there is an empty space in the registry. A NULL name denotes + a free slot. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].pcQueueName == NULL ) + { + /* Store the information on this queue. */ + xQueueRegistry[ ux ].pcQueueName = pcQueueName; + xQueueRegistry[ ux ].xHandle = xQueue; + + traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName ); + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + +#endif /* configQUEUE_REGISTRY_SIZE */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + const char *pcQueueGetName( QueueHandle_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t ux; + const char *pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + + /* Note there is nothing here to protect against another task adding or + removing entries from the registry while it is being searched. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + pcReturn = xQueueRegistry[ ux ].pcQueueName; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + return pcReturn; + } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */ + +#endif /* configQUEUE_REGISTRY_SIZE */ +/*-----------------------------------------------------------*/ + +#if ( configQUEUE_REGISTRY_SIZE > 0 ) + + void vQueueUnregisterQueue( QueueHandle_t xQueue ) + { + UBaseType_t ux; + + /* See if the handle of the queue being unregistered in actually in the + registry. */ + for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ ) + { + if( xQueueRegistry[ ux ].xHandle == xQueue ) + { + /* Set the name to NULL to show that this slot if free again. */ + xQueueRegistry[ ux ].pcQueueName = NULL; + + /* Set the handle to NULL to ensure the same queue handle cannot + appear in the registry twice if it is added, removed, then + added again. */ + xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0; + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */ + +#endif /* configQUEUE_REGISTRY_SIZE */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TIMERS == 1 ) + + void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) + { + Queue_t * const pxQueue = xQueue; + + /* This function should not be called by application code hence the + 'Restricted' in its name. It is not part of the public API. It is + designed for use by kernel code, and has special calling requirements. + It can result in vListInsert() being called on a list that can only + possibly ever have one item in it, so the list will be fast, but even + so it should be called with the scheduler locked and not from a critical + section. */ + + /* Only do anything if there are no messages in the queue. This function + will not actually cause the task to block, just place it on a blocked + list. It will not block until the scheduler is unlocked - at which + time a yield will be performed. If an item is added to the queue while + the queue is locked, and the calling task blocks on the queue, then the + calling task will be immediately unblocked when the queue is unlocked. */ + prvLockQueue( pxQueue ); + if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U ) + { + /* There is nothing in the queue, block for the specified period. */ + vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + prvUnlockQueue( pxQueue ); + } + +#endif /* configUSE_TIMERS */ +/*-----------------------------------------------------------*/ + +#if( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) + { + QueueSetHandle_t pxQueue; + + pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET ); + + return pxQueue; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL ) + { + /* Cannot add a queue/semaphore to more than one queue set. */ + xReturn = pdFAIL; + } + else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* Cannot add a queue/semaphore to a queue set if there are already + items in the queue/semaphore. */ + xReturn = pdFAIL; + } + else + { + ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet; + xReturn = pdPASS; + } + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) + { + BaseType_t xReturn; + Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore; + + if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet ) + { + /* The queue was not a member of the set. */ + xReturn = pdFAIL; + } + else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 ) + { + /* It is dangerous to remove a queue from a set when the queue is + not empty because the queue set will still hold pending events for + the queue. */ + xReturn = pdFAIL; + } + else + { + taskENTER_CRITICAL(); + { + /* The queue is no longer contained in the set. */ + pxQueueOrSemaphore->pxQueueSetContainer = NULL; + } + taskEXIT_CRITICAL(); + xReturn = pdPASS; + } + + return xReturn; + } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */ + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, TickType_t const xTicksToWait ) + { + QueueSetMemberHandle_t xReturn = NULL; + + ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); /*lint !e961 Casting from one typedef to another is not redundant. */ + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) + { + QueueSetMemberHandle_t xReturn = NULL; + + ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */ + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_QUEUE_SETS == 1 ) + + static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) + { + Queue_t *pxQueueSetContainer = pxQueue->pxQueueSetContainer; + BaseType_t xReturn = pdFALSE; + + /* This function must be called form a critical section. */ + + configASSERT( pxQueueSetContainer ); + configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ); + + if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength ) + { + const int8_t cTxLock = pxQueueSetContainer->cTxLock; + + traceQUEUE_SEND( pxQueueSetContainer ); + + /* The data copied is the handle of the queue that contains data. */ + xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, queueSEND_TO_BACK ); + + if( cTxLock == queueUNLOCKED ) + { + if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE ) + { + if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE ) + { + /* The task waiting has a higher priority. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_QUEUE_SETS */ + + + + + + + + + + + + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c b/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c new file mode 100644 index 0000000..7ad5d54 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/stream_buffer.c @@ -0,0 +1,1263 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* Standard includes. */ +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining +all the API functions to use the MPU wrappers. That should only be done when +task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "stream_buffer.h" + +#if( configUSE_TASK_NOTIFICATIONS != 1 ) + #error configUSE_TASK_NOTIFICATIONS must be set to 1 to build stream_buffer.c +#endif + +/* Lint e961, e9021 and e750 are suppressed as a MISRA exception justified +because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined +for the header files above, but not in this file, in order to generate the +correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + +/* If the user has not provided application specific Rx notification macros, +or #defined the notification macros away, them provide default implementations +that uses task notifications. */ +/*lint -save -e9026 Function like macros allowed and needed here so they can be overidden. */ +#ifndef sbRECEIVE_COMPLETED + #define sbRECEIVE_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); +#endif /* sbRECEIVE_COMPLETED */ + +#ifndef sbRECEIVE_COMPLETED_FROM_ISR + #define sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, \ + pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } +#endif /* sbRECEIVE_COMPLETED_FROM_ISR */ + +/* If the user has not provided an application specific Tx notification macro, +or #defined the notification macro away, them provide a default implementation +that uses task notifications. */ +#ifndef sbSEND_COMPLETED + #define sbSEND_COMPLETED( pxStreamBuffer ) \ + vTaskSuspendAll(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotify( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + ( void ) xTaskResumeAll(); +#endif /* sbSEND_COMPLETED */ + +#ifndef sbSEND_COMPLETE_FROM_ISR + #define sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ) \ + { \ + UBaseType_t uxSavedInterruptStatus; \ + \ + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); \ + { \ + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) \ + { \ + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, \ + ( uint32_t ) 0, \ + eNoAction, \ + pxHigherPriorityTaskWoken ); \ + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; \ + } \ + } \ + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); \ + } +#endif /* sbSEND_COMPLETE_FROM_ISR */ +/*lint -restore (9026) */ + +/* The number of bytes used to hold the length of a message in the buffer. */ +#define sbBYTES_TO_STORE_MESSAGE_LENGTH ( sizeof( configMESSAGE_BUFFER_LENGTH_TYPE ) ) + +/* Bits stored in the ucFlags field of the stream buffer. */ +#define sbFLAGS_IS_MESSAGE_BUFFER ( ( uint8_t ) 1 ) /* Set if the stream buffer was created as a message buffer, in which case it holds discrete messages rather than a stream. */ +#define sbFLAGS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 2 ) /* Set if the stream buffer was created using statically allocated memory. */ + +/*-----------------------------------------------------------*/ + +/* Structure that hold state information on the buffer. */ +typedef struct StreamBufferDef_t /*lint !e9058 Style convention uses tag. */ +{ + volatile size_t xTail; /* Index to the next item to read within the buffer. */ + volatile size_t xHead; /* Index to the next item to write within the buffer. */ + size_t xLength; /* The length of the buffer pointed to by pucBuffer. */ + size_t xTriggerLevelBytes; /* The number of bytes that must be in the stream buffer before a task that is waiting for data is unblocked. */ + volatile TaskHandle_t xTaskWaitingToReceive; /* Holds the handle of a task waiting for data, or NULL if no tasks are waiting. */ + volatile TaskHandle_t xTaskWaitingToSend; /* Holds the handle of a task waiting to send data to a message buffer that is full. */ + uint8_t *pucBuffer; /* Points to the buffer itself - that is - the RAM that stores the data passed through the buffer. */ + uint8_t ucFlags; + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; /* Used for tracing purposes. */ + #endif +} StreamBuffer_t; + +/* + * The number of bytes available to be read from the buffer. + */ +static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) PRIVILEGED_FUNCTION; + +/* + * Add xCount bytes from pucData into the pxStreamBuffer message buffer. + * Returns the number of bytes written, which will either equal xCount in the + * success case, or 0 if there was not enough space in the buffer (in which case + * no data is written into the buffer). + */ +static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, const uint8_t *pucData, size_t xCount ) PRIVILEGED_FUNCTION; + +/* + * If the stream buffer is being used as a message buffer, then reads an entire + * message out of the buffer. If the stream buffer is being used as a stream + * buffer then read as many bytes as possible from the buffer. + * prvReadBytesFromBuffer() is called to actually extract the bytes from the + * buffer's data storage area. + */ +static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable, + size_t xBytesToStoreMessageLength ) PRIVILEGED_FUNCTION; + +/* + * If the stream buffer is being used as a message buffer, then writes an entire + * message to the buffer. If the stream buffer is being used as a stream + * buffer then write as many bytes as possible to the buffer. + * prvWriteBytestoBuffer() is called to actually send the bytes to the buffer's + * data storage area. + */ +static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) PRIVILEGED_FUNCTION; + +/* + * Read xMaxCount bytes from the pxStreamBuffer message buffer and write them + * to pucData. + */ +static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, + uint8_t *pucData, + size_t xMaxCount, + size_t xBytesAvailable ) PRIVILEGED_FUNCTION; + +/* + * Called by both pxStreamBufferCreate() and pxStreamBufferCreateStatic() to + * initialise the members of the newly created stream buffer structure. + */ +static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags ) PRIVILEGED_FUNCTION; + +/*-----------------------------------------------------------*/ + +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + StreamBufferHandle_t xStreamBufferGenericCreate( size_t xBufferSizeBytes, size_t xTriggerLevelBytes, BaseType_t xIsMessageBuffer ) + { + uint8_t *pucAllocatedMemory; + uint8_t ucFlags; + + /* In case the stream buffer is going to be used as a message buffer + (that is, it will hold discrete messages with a little meta data that + says how big the next message is) check the buffer will be large enough + to hold at least one message. */ + if( xIsMessageBuffer == pdTRUE ) + { + /* Is a message buffer but not statically allocated. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER; + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + } + else + { + /* Not a message buffer and not statically allocated. */ + ucFlags = 0; + configASSERT( xBufferSizeBytes > 0 ); + } + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + + /* A trigger level of 0 would cause a waiting task to unblock even when + the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } + + /* A stream buffer requires a StreamBuffer_t structure and a buffer. + Both are allocated in a single call to pvPortMalloc(). The + StreamBuffer_t structure is placed at the start of the allocated memory + and the buffer follows immediately after. The requested size is + incremented so the free space is returned as the user would expect - + this is a quirk of the implementation that means otherwise the free + space would be reported as one byte smaller than would be logically + expected. */ + xBufferSizeBytes++; + pucAllocatedMemory = ( uint8_t * ) pvPortMalloc( xBufferSizeBytes + sizeof( StreamBuffer_t ) ); /*lint !e9079 malloc() only returns void*. */ + + if( pucAllocatedMemory != NULL ) + { + prvInitialiseNewStreamBuffer( ( StreamBuffer_t * ) pucAllocatedMemory, /* Structure at the start of the allocated memory. */ /*lint !e9087 Safe cast as allocated memory is aligned. */ /*lint !e826 Area is not too small and alignment is guaranteed provided malloc() behaves as expected and returns aligned buffer. */ + pucAllocatedMemory + sizeof( StreamBuffer_t ), /* Storage area follows. */ /*lint !e9016 Indexing past structure valid for uint8_t pointer, also storage area has no alignment requirement. */ + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); + + traceSTREAM_BUFFER_CREATE( ( ( StreamBuffer_t * ) pucAllocatedMemory ), xIsMessageBuffer ); + } + else + { + traceSTREAM_BUFFER_CREATE_FAILED( xIsMessageBuffer ); + } + + return ( StreamBufferHandle_t ) pucAllocatedMemory; /*lint !e9087 !e826 Safe cast as allocated memory is aligned. */ + } + +#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + + StreamBufferHandle_t xStreamBufferGenericCreateStatic( size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + BaseType_t xIsMessageBuffer, + uint8_t * const pucStreamBufferStorageArea, + StaticStreamBuffer_t * const pxStaticStreamBuffer ) + { + StreamBuffer_t * const pxStreamBuffer = ( StreamBuffer_t * ) pxStaticStreamBuffer; /*lint !e740 !e9087 Safe cast as StaticStreamBuffer_t is opaque Streambuffer_t. */ + StreamBufferHandle_t xReturn; + uint8_t ucFlags; + + configASSERT( pucStreamBufferStorageArea ); + configASSERT( pxStaticStreamBuffer ); + configASSERT( xTriggerLevelBytes <= xBufferSizeBytes ); + + /* A trigger level of 0 would cause a waiting task to unblock even when + the buffer was empty. */ + if( xTriggerLevelBytes == ( size_t ) 0 ) + { + xTriggerLevelBytes = ( size_t ) 1; + } + + if( xIsMessageBuffer != pdFALSE ) + { + /* Statically allocated message buffer. */ + ucFlags = sbFLAGS_IS_MESSAGE_BUFFER | sbFLAGS_IS_STATICALLY_ALLOCATED; + } + else + { + /* Statically allocated stream buffer. */ + ucFlags = sbFLAGS_IS_STATICALLY_ALLOCATED; + } + + /* In case the stream buffer is going to be used as a message buffer + (that is, it will hold discrete messages with a little meta data that + says how big the next message is) check the buffer will be large enough + to hold at least one message. */ + configASSERT( xBufferSizeBytes > sbBYTES_TO_STORE_MESSAGE_LENGTH ); + + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticStreamBuffer_t equals the size of the real + message buffer structure. */ + volatile size_t xSize = sizeof( StaticStreamBuffer_t ); + configASSERT( xSize == sizeof( StreamBuffer_t ) ); + } /*lint !e529 xSize is referenced is configASSERT() is defined. */ + #endif /* configASSERT_DEFINED */ + + if( ( pucStreamBufferStorageArea != NULL ) && ( pxStaticStreamBuffer != NULL ) ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pucStreamBufferStorageArea, + xBufferSizeBytes, + xTriggerLevelBytes, + ucFlags ); + + /* Remember this was statically allocated in case it is ever deleted + again. */ + pxStreamBuffer->ucFlags |= sbFLAGS_IS_STATICALLY_ALLOCATED; + + traceSTREAM_BUFFER_CREATE( pxStreamBuffer, xIsMessageBuffer ); + + xReturn = ( StreamBufferHandle_t ) pxStaticStreamBuffer; /*lint !e9087 Data hiding requires cast to opaque type. */ + } + else + { + xReturn = NULL; + traceSTREAM_BUFFER_CREATE_STATIC_FAILED( xReturn, xIsMessageBuffer ); + } + + return xReturn; + } + +#endif /* ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ +/*-----------------------------------------------------------*/ + +void vStreamBufferDelete( StreamBufferHandle_t xStreamBuffer ) +{ +StreamBuffer_t * pxStreamBuffer = xStreamBuffer; + + configASSERT( pxStreamBuffer ); + + traceSTREAM_BUFFER_DELETE( xStreamBuffer ); + + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) pdFALSE ) + { + #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* Both the structure and the buffer were allocated using a single call + to pvPortMalloc(), hence only one call to vPortFree() is required. */ + vPortFree( ( void * ) pxStreamBuffer ); /*lint !e9087 Standard free() semantics require void *, plus pxStreamBuffer was allocated by pvPortMalloc(). */ + } + #else + { + /* Should not be possible to get here, ucFlags must be corrupt. + Force an assert. */ + configASSERT( xStreamBuffer == ( StreamBufferHandle_t ) ~0 ); + } + #endif + } + else + { + /* The structure and buffer were not allocated dynamically and cannot be + freed - just scrub the structure so future use will assert. */ + ( void ) memset( pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferReset( StreamBufferHandle_t xStreamBuffer ) +{ +StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +BaseType_t xReturn = pdFAIL; + +#if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxStreamBufferNumber; +#endif + + configASSERT( pxStreamBuffer ); + + #if( configUSE_TRACE_FACILITY == 1 ) + { + /* Store the stream buffer number so it can be restored after the + reset. */ + uxStreamBufferNumber = pxStreamBuffer->uxStreamBufferNumber; + } + #endif + + /* Can only reset a message buffer if there are no tasks blocked on it. */ + taskENTER_CRITICAL(); + { + if( pxStreamBuffer->xTaskWaitingToReceive == NULL ) + { + if( pxStreamBuffer->xTaskWaitingToSend == NULL ) + { + prvInitialiseNewStreamBuffer( pxStreamBuffer, + pxStreamBuffer->pucBuffer, + pxStreamBuffer->xLength, + pxStreamBuffer->xTriggerLevelBytes, + pxStreamBuffer->ucFlags ); + xReturn = pdPASS; + + #if( configUSE_TRACE_FACILITY == 1 ) + { + pxStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } + #endif + + traceSTREAM_BUFFER_RESET( xStreamBuffer ); + } + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferSetTriggerLevel( StreamBufferHandle_t xStreamBuffer, size_t xTriggerLevel ) +{ +StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +BaseType_t xReturn; + + configASSERT( pxStreamBuffer ); + + /* It is not valid for the trigger level to be 0. */ + if( xTriggerLevel == ( size_t ) 0 ) + { + xTriggerLevel = ( size_t ) 1; + } + + /* The trigger level is the number of bytes that must be in the stream + buffer before a task that is waiting for data is unblocked. */ + if( xTriggerLevel <= pxStreamBuffer->xLength ) + { + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevel; + xReturn = pdPASS; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSpacesAvailable( StreamBufferHandle_t xStreamBuffer ) +{ +const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +size_t xSpace; + + configASSERT( pxStreamBuffer ); + + xSpace = pxStreamBuffer->xLength + pxStreamBuffer->xTail; + xSpace -= pxStreamBuffer->xHead; + xSpace -= ( size_t ) 1; + + if( xSpace >= pxStreamBuffer->xLength ) + { + xSpace -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xSpace; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferBytesAvailable( StreamBufferHandle_t xStreamBuffer ) +{ +const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +size_t xReturn; + + configASSERT( pxStreamBuffer ); + + xReturn = prvBytesInBuffer( pxStreamBuffer ); + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSend( StreamBufferHandle_t xStreamBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + TickType_t xTicksToWait ) +{ +StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +size_t xReturn, xSpace = 0; +size_t xRequiredSpace = xDataLengthBytes; +TimeOut_t xTimeOut; + + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); + + /* This send function is used to write to both message buffers and stream + buffers. If this is a message buffer then the space needed must be + increased by the amount of bytes needed to store the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + + /* Overflow? */ + configASSERT( xRequiredSpace > xDataLengthBytes ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xTicksToWait != ( TickType_t ) 0 ) + { + vTaskSetTimeOutState( &xTimeOut ); + + do + { + /* Wait until the required number of bytes are free in the message + buffer. */ + taskENTER_CRITICAL(); + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + + if( xSpace < xRequiredSpace ) + { + /* Clear notification state as going to wait for space. */ + ( void ) xTaskNotifyStateClear( NULL ); + + /* Should only be one writer. */ + configASSERT( pxStreamBuffer->xTaskWaitingToSend == NULL ); + pxStreamBuffer->xTaskWaitingToSend = xTaskGetCurrentTaskHandle(); + } + else + { + taskEXIT_CRITICAL(); + break; + } + } + taskEXIT_CRITICAL(); + + traceBLOCKING_ON_STREAM_BUFFER_SEND( xStreamBuffer ); + ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToSend = NULL; + + } while( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xSpace == ( size_t ) 0 ) + { + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + + if( xReturn > ( size_t ) 0 ) + { + traceSTREAM_BUFFER_SEND( xStreamBuffer, xReturn ); + + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + traceSTREAM_BUFFER_SEND_FAILED( xStreamBuffer ); + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferSendFromISR( StreamBufferHandle_t xStreamBuffer, + const void *pvTxData, + size_t xDataLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ +StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +size_t xReturn, xSpace; +size_t xRequiredSpace = xDataLengthBytes; + + configASSERT( pvTxData ); + configASSERT( pxStreamBuffer ); + + /* This send function is used to write to both message buffers and stream + buffers. If this is a message buffer then the space needed must be + increased by the amount of bytes needed to store the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xRequiredSpace += sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xSpace = xStreamBufferSpacesAvailable( pxStreamBuffer ); + xReturn = prvWriteMessageToBuffer( pxStreamBuffer, pvTxData, xDataLengthBytes, xSpace, xRequiredSpace ); + + if( xReturn > ( size_t ) 0 ) + { + /* Was a task waiting for the data? */ + if( prvBytesInBuffer( pxStreamBuffer ) >= pxStreamBuffer->xTriggerLevelBytes ) + { + sbSEND_COMPLETE_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceSTREAM_BUFFER_SEND_FROM_ISR( xStreamBuffer, xReturn ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static size_t prvWriteMessageToBuffer( StreamBuffer_t * const pxStreamBuffer, + const void * pvTxData, + size_t xDataLengthBytes, + size_t xSpace, + size_t xRequiredSpace ) +{ + BaseType_t xShouldWrite; + size_t xReturn; + + if( xSpace == ( size_t ) 0 ) + { + /* Doesn't matter if this is a stream buffer or a message buffer, there + is no space to write. */ + xShouldWrite = pdFALSE; + } + else if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) == ( uint8_t ) 0 ) + { + /* This is a stream buffer, as opposed to a message buffer, so writing a + stream of bytes rather than discrete messages. Write as many bytes as + possible. */ + xShouldWrite = pdTRUE; + xDataLengthBytes = configMIN( xDataLengthBytes, xSpace ); + } + else if( xSpace >= xRequiredSpace ) + { + /* This is a message buffer, as opposed to a stream buffer, and there + is enough space to write both the message length and the message itself + into the buffer. Start by writing the length of the data, the data + itself will be written later in this function. */ + xShouldWrite = pdTRUE; + ( void ) prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) &( xDataLengthBytes ), sbBYTES_TO_STORE_MESSAGE_LENGTH ); + } + else + { + /* There is space available, but not enough space. */ + xShouldWrite = pdFALSE; + } + + if( xShouldWrite != pdFALSE ) + { + /* Writes the data itself. */ + xReturn = prvWriteBytesToBuffer( pxStreamBuffer, ( const uint8_t * ) pvTxData, xDataLengthBytes ); /*lint !e9079 Storage buffer is implemented as uint8_t for ease of sizing, alighment and access. */ + } + else + { + xReturn = 0; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferReceive( StreamBufferHandle_t xStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + TickType_t xTicksToWait ) +{ +StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; + + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); + + /* This receive function is used by both message buffers, which store + discrete messages, and stream buffers, which store a continuous stream of + bytes. Discrete messages include an additional + sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } + + if( xTicksToWait != ( TickType_t ) 0 ) + { + /* Checking if there is data and clearing the notification state must be + performed atomically. */ + taskENTER_CRITICAL(); + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + + /* If this function was invoked by a message buffer read then + xBytesToStoreMessageLength holds the number of bytes used to hold + the length of the next discrete message. If this function was + invoked by a stream buffer read then xBytesToStoreMessageLength will + be 0. */ + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Clear notification state as going to wait for data. */ + ( void ) xTaskNotifyStateClear( NULL ); + + /* Should only be one reader. */ + configASSERT( pxStreamBuffer->xTaskWaitingToReceive == NULL ); + pxStreamBuffer->xTaskWaitingToReceive = xTaskGetCurrentTaskHandle(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + if( xBytesAvailable <= xBytesToStoreMessageLength ) + { + /* Wait for data to be available. */ + traceBLOCKING_ON_STREAM_BUFFER_RECEIVE( xStreamBuffer ); + ( void ) xTaskNotifyWait( ( uint32_t ) 0, ( uint32_t ) 0, NULL, xTicksToWait ); + pxStreamBuffer->xTaskWaitingToReceive = NULL; + + /* Recheck the data available after blocking. */ + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + } + + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + holds the number of bytes used to store the message length) or a stream of + bytes (where xBytesToStoreMessageLength is zero), the number of bytes + available must be greater than xBytesToStoreMessageLength to be able to + read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); + + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + traceSTREAM_BUFFER_RECEIVE( xStreamBuffer, xReceivedLength ); + sbRECEIVE_COMPLETED( pxStreamBuffer ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + traceSTREAM_BUFFER_RECEIVE_FAILED( xStreamBuffer ); + mtCOVERAGE_TEST_MARKER(); + } + + return xReceivedLength; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferNextMessageLengthBytes( StreamBufferHandle_t xStreamBuffer ) +{ +StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +size_t xReturn, xBytesAvailable, xOriginalTail; +configMESSAGE_BUFFER_LENGTH_TYPE xTempReturn; + + configASSERT( pxStreamBuffer ); + + /* Ensure the stream buffer is being used as a message buffer. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + if( xBytesAvailable > sbBYTES_TO_STORE_MESSAGE_LENGTH ) + { + /* The number of bytes available is greater than the number of bytes + required to hold the length of the next message, so another message + is available. Return its length without removing the length bytes + from the buffer. A copy of the tail is stored so the buffer can be + returned to its prior state as the message is not actually being + removed from the buffer. */ + xOriginalTail = pxStreamBuffer->xTail; + ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempReturn, sbBYTES_TO_STORE_MESSAGE_LENGTH, xBytesAvailable ); + xReturn = ( size_t ) xTempReturn; + pxStreamBuffer->xTail = xOriginalTail; + } + else + { + /* The minimum amount of bytes in a message buffer is + ( sbBYTES_TO_STORE_MESSAGE_LENGTH + 1 ), so if xBytesAvailable is + less than sbBYTES_TO_STORE_MESSAGE_LENGTH the only other valid + value is 0. */ + configASSERT( xBytesAvailable == 0 ); + xReturn = 0; + } + } + else + { + xReturn = 0; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +size_t xStreamBufferReceiveFromISR( StreamBufferHandle_t xStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + BaseType_t * const pxHigherPriorityTaskWoken ) +{ +StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +size_t xReceivedLength = 0, xBytesAvailable, xBytesToStoreMessageLength; + + configASSERT( pvRxData ); + configASSERT( pxStreamBuffer ); + + /* This receive function is used by both message buffers, which store + discrete messages, and stream buffers, which store a continuous stream of + bytes. Discrete messages include an additional + sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the + message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } + + xBytesAvailable = prvBytesInBuffer( pxStreamBuffer ); + + /* Whether receiving a discrete message (where xBytesToStoreMessageLength + holds the number of bytes used to store the message length) or a stream of + bytes (where xBytesToStoreMessageLength is zero), the number of bytes + available must be greater than xBytesToStoreMessageLength to be able to + read bytes from the buffer. */ + if( xBytesAvailable > xBytesToStoreMessageLength ) + { + xReceivedLength = prvReadMessageFromBuffer( pxStreamBuffer, pvRxData, xBufferLengthBytes, xBytesAvailable, xBytesToStoreMessageLength ); + + /* Was a task waiting for space in the buffer? */ + if( xReceivedLength != ( size_t ) 0 ) + { + sbRECEIVE_COMPLETED_FROM_ISR( pxStreamBuffer, pxHigherPriorityTaskWoken ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceSTREAM_BUFFER_RECEIVE_FROM_ISR( xStreamBuffer, xReceivedLength ); + + return xReceivedLength; +} +/*-----------------------------------------------------------*/ + +static size_t prvReadMessageFromBuffer( StreamBuffer_t *pxStreamBuffer, + void *pvRxData, + size_t xBufferLengthBytes, + size_t xBytesAvailable, + size_t xBytesToStoreMessageLength ) +{ +size_t xOriginalTail, xReceivedLength, xNextMessageLength; +configMESSAGE_BUFFER_LENGTH_TYPE xTempNextMessageLength; + + if( xBytesToStoreMessageLength != ( size_t ) 0 ) + { + /* A discrete message is being received. First receive the length + of the message. A copy of the tail is stored so the buffer can be + returned to its prior state if the length of the message is too + large for the provided buffer. */ + xOriginalTail = pxStreamBuffer->xTail; + ( void ) prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) &xTempNextMessageLength, xBytesToStoreMessageLength, xBytesAvailable ); + xNextMessageLength = ( size_t ) xTempNextMessageLength; + + /* Reduce the number of bytes available by the number of bytes just + read out. */ + xBytesAvailable -= xBytesToStoreMessageLength; + + /* Check there is enough space in the buffer provided by the + user. */ + if( xNextMessageLength > xBufferLengthBytes ) + { + /* The user has provided insufficient space to read the message + so return the buffer to its previous state (so the length of + the message is in the buffer again). */ + pxStreamBuffer->xTail = xOriginalTail; + xNextMessageLength = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* A stream of bytes is being received (as opposed to a discrete + message), so read as many bytes as possible. */ + xNextMessageLength = xBufferLengthBytes; + } + + /* Read the actual data. */ + xReceivedLength = prvReadBytesFromBuffer( pxStreamBuffer, ( uint8_t * ) pvRxData, xNextMessageLength, xBytesAvailable ); /*lint !e9079 Data storage area is implemented as uint8_t array for ease of sizing, indexing and alignment. */ + + return xReceivedLength; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferIsEmpty( StreamBufferHandle_t xStreamBuffer ) +{ +const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +BaseType_t xReturn; +size_t xTail; + + configASSERT( pxStreamBuffer ); + + /* True if no bytes are available. */ + xTail = pxStreamBuffer->xTail; + if( pxStreamBuffer->xHead == xTail ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferIsFull( StreamBufferHandle_t xStreamBuffer ) +{ +BaseType_t xReturn; +size_t xBytesToStoreMessageLength; +const StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; + + configASSERT( pxStreamBuffer ); + + /* This generic version of the receive function is used by both message + buffers, which store discrete messages, and stream buffers, which store a + continuous stream of bytes. Discrete messages include an additional + sbBYTES_TO_STORE_MESSAGE_LENGTH bytes that hold the length of the message. */ + if( ( pxStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ) != ( uint8_t ) 0 ) + { + xBytesToStoreMessageLength = sbBYTES_TO_STORE_MESSAGE_LENGTH; + } + else + { + xBytesToStoreMessageLength = 0; + } + + /* True if the available space equals zero. */ + if( xStreamBufferSpacesAvailable( xStreamBuffer ) <= xBytesToStoreMessageLength ) + { + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferSendCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) +{ +StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +BaseType_t xReturn; +UBaseType_t uxSavedInterruptStatus; + + configASSERT( pxStreamBuffer ); + + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToReceive != NULL ) + { + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToReceive, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToReceive = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +BaseType_t xStreamBufferReceiveCompletedFromISR( StreamBufferHandle_t xStreamBuffer, BaseType_t *pxHigherPriorityTaskWoken ) +{ +StreamBuffer_t * const pxStreamBuffer = xStreamBuffer; +BaseType_t xReturn; +UBaseType_t uxSavedInterruptStatus; + + configASSERT( pxStreamBuffer ); + + uxSavedInterruptStatus = ( UBaseType_t ) portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( ( pxStreamBuffer )->xTaskWaitingToSend != NULL ) + { + ( void ) xTaskNotifyFromISR( ( pxStreamBuffer )->xTaskWaitingToSend, + ( uint32_t ) 0, + eNoAction, + pxHigherPriorityTaskWoken ); + ( pxStreamBuffer )->xTaskWaitingToSend = NULL; + xReturn = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +static size_t prvWriteBytesToBuffer( StreamBuffer_t * const pxStreamBuffer, const uint8_t *pucData, size_t xCount ) +{ +size_t xNextHead, xFirstLength; + + configASSERT( xCount > ( size_t ) 0 ); + + xNextHead = pxStreamBuffer->xHead; + + /* Calculate the number of bytes that can be added in the first write - + which may be less than the total number of bytes that need to be added if + the buffer will wrap back to the beginning. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xNextHead, xCount ); + + /* Write as many bytes as can be written in the first write. */ + configASSERT( ( xNextHead + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void* ) ( &( pxStreamBuffer->pucBuffer[ xNextHead ] ) ), ( const void * ) pucData, xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + + /* If the number of bytes written was less than the number that could be + written in the first write... */ + if( xCount > xFirstLength ) + { + /* ...then write the remaining bytes to the start of the buffer. */ + configASSERT( ( xCount - xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) pxStreamBuffer->pucBuffer, ( const void * ) &( pucData[ xFirstLength ] ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + xNextHead += xCount; + if( xNextHead >= pxStreamBuffer->xLength ) + { + xNextHead -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxStreamBuffer->xHead = xNextHead; + + return xCount; +} +/*-----------------------------------------------------------*/ + +static size_t prvReadBytesFromBuffer( StreamBuffer_t *pxStreamBuffer, uint8_t *pucData, size_t xMaxCount, size_t xBytesAvailable ) +{ +size_t xCount, xFirstLength, xNextTail; + + /* Use the minimum of the wanted bytes and the available bytes. */ + xCount = configMIN( xBytesAvailable, xMaxCount ); + + if( xCount > ( size_t ) 0 ) + { + xNextTail = pxStreamBuffer->xTail; + + /* Calculate the number of bytes that can be read - which may be + less than the number wanted if the data wraps around to the start of + the buffer. */ + xFirstLength = configMIN( pxStreamBuffer->xLength - xNextTail, xCount ); + + /* Obtain the number of bytes it is possible to obtain in the first + read. Asserts check bounds of read and write. */ + configASSERT( xFirstLength <= xMaxCount ); + configASSERT( ( xNextTail + xFirstLength ) <= pxStreamBuffer->xLength ); + ( void ) memcpy( ( void * ) pucData, ( const void * ) &( pxStreamBuffer->pucBuffer[ xNextTail ] ), xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + + /* If the total number of wanted bytes is greater than the number + that could be read in the first read... */ + if( xCount > xFirstLength ) + { + /*...then read the remaining bytes from the start of the buffer. */ + configASSERT( xCount <= xMaxCount ); + ( void ) memcpy( ( void * ) &( pucData[ xFirstLength ] ), ( void * ) ( pxStreamBuffer->pucBuffer ), xCount - xFirstLength ); /*lint !e9087 memcpy() requires void *. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Move the tail pointer to effectively remove the data read from + the buffer. */ + xNextTail += xCount; + + if( xNextTail >= pxStreamBuffer->xLength ) + { + xNextTail -= pxStreamBuffer->xLength; + } + + pxStreamBuffer->xTail = xNextTail; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xCount; +} +/*-----------------------------------------------------------*/ + +static size_t prvBytesInBuffer( const StreamBuffer_t * const pxStreamBuffer ) +{ +/* Returns the distance between xTail and xHead. */ +size_t xCount; + + xCount = pxStreamBuffer->xLength + pxStreamBuffer->xHead; + xCount -= pxStreamBuffer->xTail; + if ( xCount >= pxStreamBuffer->xLength ) + { + xCount -= pxStreamBuffer->xLength; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xCount; +} +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewStreamBuffer( StreamBuffer_t * const pxStreamBuffer, + uint8_t * const pucBuffer, + size_t xBufferSizeBytes, + size_t xTriggerLevelBytes, + uint8_t ucFlags ) +{ + /* Assert here is deliberately writing to the entire buffer to ensure it can + be written to without generating exceptions, and is setting the buffer to a + known value to assist in development/debugging. */ + #if( configASSERT_DEFINED == 1 ) + { + /* The value written just has to be identifiable when looking at the + memory. Don't use 0xA5 as that is the stack fill value and could + result in confusion as to what is actually being observed. */ + const BaseType_t xWriteValue = 0x55; + configASSERT( memset( pucBuffer, ( int ) xWriteValue, xBufferSizeBytes ) == pucBuffer ); + } /*lint !e529 !e438 xWriteValue is only used if configASSERT() is defined. */ + #endif + + ( void ) memset( ( void * ) pxStreamBuffer, 0x00, sizeof( StreamBuffer_t ) ); /*lint !e9087 memset() requires void *. */ + pxStreamBuffer->pucBuffer = pucBuffer; + pxStreamBuffer->xLength = xBufferSizeBytes; + pxStreamBuffer->xTriggerLevelBytes = xTriggerLevelBytes; + pxStreamBuffer->ucFlags = ucFlags; +} + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxStreamBufferGetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer ) + { + return xStreamBuffer->uxStreamBufferNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vStreamBufferSetStreamBufferNumber( StreamBufferHandle_t xStreamBuffer, UBaseType_t uxStreamBufferNumber ) + { + xStreamBuffer->uxStreamBufferNumber = uxStreamBufferNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + uint8_t ucStreamBufferGetStreamBufferType( StreamBufferHandle_t xStreamBuffer ) + { + return ( xStreamBuffer->ucFlags & sbFLAGS_IS_MESSAGE_BUFFER ); + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ diff --git a/Middlewares/Third_Party/FreeRTOS/Source/tasks.c b/Middlewares/Third_Party/FreeRTOS/Source/tasks.c new file mode 100644 index 0000000..f6a6a9b --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/tasks.c @@ -0,0 +1,5310 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* Standard includes. */ +#include +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining +all the API functions to use the MPU wrappers. That should only be done when +task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +/* FreeRTOS includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "timers.h" +#include "stack_macros.h" + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified +because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined +for the header files above, but not in this file, in order to generate the +correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */ + +/* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting +functions but without including stdio.h here. */ +#if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) + /* At the bottom of this file are two optional functions that can be used + to generate human readable text from the raw data generated by the + uxTaskGetSystemState() function. Note the formatting functions are provided + for convenience only, and are NOT considered part of the kernel. */ + #include +#endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */ + +#if( configUSE_PREEMPTION == 0 ) + /* If the cooperative scheduler is being used then a yield should not be + performed just because a higher priority task has been woken. */ + #define taskYIELD_IF_USING_PREEMPTION() +#else + #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API() +#endif + +/* Values that can be assigned to the ucNotifyState member of the TCB. */ +#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 ) +#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 ) +#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 ) + +/* + * The value used to fill the stack of a task when the task is created. This + * is used purely for checking the high water mark for tasks. + */ +#define tskSTACK_FILL_BYTE ( 0xa5U ) + +/* Bits used to recored how a task's stack and TCB were allocated. */ +#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 ) +#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 ) +#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 ) + +/* If any of the following are set then task stacks are filled with a known +value so the high water mark can be determined. If none of the following are +set then don't fill the stack so there is no unnecessary dependency on memset. */ +#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1 +#else + #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0 +#endif + +/* + * Macros used by vListTask to indicate which state a task is in. + */ +#define tskRUNNING_CHAR ( 'X' ) +#define tskBLOCKED_CHAR ( 'B' ) +#define tskREADY_CHAR ( 'R' ) +#define tskDELETED_CHAR ( 'D' ) +#define tskSUSPENDED_CHAR ( 'S' ) + +/* + * Some kernel aware debuggers require the data the debugger needs access to be + * global, rather than file scope. + */ +#ifdef portREMOVE_STATIC_QUALIFIER + #define static +#endif + +/* The name allocated to the Idle task. This can be overridden by defining +configIDLE_TASK_NAME in FreeRTOSConfig.h. */ +#ifndef configIDLE_TASK_NAME + #define configIDLE_TASK_NAME "IDLE" +#endif + +#if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) + + /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is + performed in a generic way that is not optimised to any particular + microcontroller architecture. */ + + /* uxTopReadyPriority holds the priority of the highest priority ready + state task. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) \ + { \ + if( ( uxPriority ) > uxTopReadyPriority ) \ + { \ + uxTopReadyPriority = ( uxPriority ); \ + } \ + } /* taskRECORD_READY_PRIORITY */ + + /*-----------------------------------------------------------*/ + + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + { \ + UBaseType_t uxTopPriority = uxTopReadyPriority; \ + \ + /* Find the highest priority queue that contains ready tasks. */ \ + while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \ + { \ + configASSERT( uxTopPriority ); \ + --uxTopPriority; \ + } \ + \ + /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \ + the same priority get an equal share of the processor time. */ \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + uxTopReadyPriority = uxTopPriority; \ + } /* taskSELECT_HIGHEST_PRIORITY_TASK */ + + /*-----------------------------------------------------------*/ + + /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as + they are only required when a port optimised method of task selection is + being used. */ + #define taskRESET_READY_PRIORITY( uxPriority ) + #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority ) + +#else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ + + /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is + performed in a way that is tailored to the particular microcontroller + architecture being used. */ + + /* A port optimised version is provided. Call the port defined macros. */ + #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority ) + + /*-----------------------------------------------------------*/ + + #define taskSELECT_HIGHEST_PRIORITY_TASK() \ + { \ + UBaseType_t uxTopPriority; \ + \ + /* Find the highest priority list that contains ready tasks. */ \ + portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \ + configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \ + listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \ + } /* taskSELECT_HIGHEST_PRIORITY_TASK() */ + + /*-----------------------------------------------------------*/ + + /* A port optimised version is provided, call it only if the TCB being reset + is being referenced from a ready list. If it is referenced from a delayed + or suspended list then it won't be in a ready list. */ + #define taskRESET_READY_PRIORITY( uxPriority ) \ + { \ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \ + { \ + portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \ + } \ + } + +#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */ + +/*-----------------------------------------------------------*/ + +/* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick +count overflows. */ +#define taskSWITCH_DELAYED_LISTS() \ +{ \ + List_t *pxTemp; \ + \ + /* The delayed tasks list should be empty when the lists are switched. */ \ + configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \ + \ + pxTemp = pxDelayedTaskList; \ + pxDelayedTaskList = pxOverflowDelayedTaskList; \ + pxOverflowDelayedTaskList = pxTemp; \ + xNumOfOverflows++; \ + prvResetNextTaskUnblockTime(); \ +} + +/*-----------------------------------------------------------*/ + +/* + * Place the task represented by pxTCB into the appropriate ready list for + * the task. It is inserted at the end of the list. + */ +#define prvAddTaskToReadyList( pxTCB ) \ + traceMOVED_TASK_TO_READY_STATE( pxTCB ); \ + taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \ + vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \ + tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB ) +/*-----------------------------------------------------------*/ + +/* + * Several functions take an TaskHandle_t parameter that can optionally be NULL, + * where NULL is used to indicate that the handle of the currently executing + * task should be used in place of the parameter. This macro simply checks to + * see if the parameter is NULL and returns a pointer to the appropriate TCB. + */ +#define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? pxCurrentTCB : ( pxHandle ) ) + +/* The item value of the event list item is normally used to hold the priority +of the task to which it belongs (coded to allow it to be held in reverse +priority order). However, it is occasionally borrowed for other purposes. It +is important its value is not updated due to a task priority change while it is +being used for another purpose. The following bit definition is used to inform +the scheduler that the value should not be changed - in which case it is the +responsibility of whichever module is using the value to ensure it gets set back +to its original value when it is released. */ +#if( configUSE_16_BIT_TICKS == 1 ) + #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U +#else + #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL +#endif + +/* + * Task control block. A task control block (TCB) is allocated for each task, + * and stores task state information, including a pointer to the task's context + * (the task's run time environment, including register values) + */ +typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +{ + volatile StackType_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */ + + #if ( portUSING_MPU_WRAPPERS == 1 ) + xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */ + #endif + + ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */ + ListItem_t xEventListItem; /*< Used to reference a task from an event list. */ + UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */ + StackType_t *pxStack; /*< Points to the start of the stack. */ + char pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + + #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) ) + StackType_t *pxEndOfStack; /*< Points to the highest valid address for the stack. */ + #endif + + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */ + #endif + + #if ( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */ + UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */ + #endif + + #if ( configUSE_MUTEXES == 1 ) + UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */ + UBaseType_t uxMutexesHeld; + #endif + + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + TaskHookFunction_t pxTaskTag; + #endif + + #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 ) + void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ]; + #endif + + #if( configGENERATE_RUN_TIME_STATS == 1 ) + uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */ + #endif + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + /* Allocate a Newlib reent structure that is specific to this task. + Note Newlib support has been included by popular demand, but is not + used by the FreeRTOS maintainers themselves. FreeRTOS is not + responsible for resulting newlib operation. User must be familiar with + newlib and must provide system-wide implementations of the necessary + stubs. Be warned that (at the time of writing) the current newlib design + implements a system-wide malloc() that must be provided with locks. + + See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + for additional information. */ + struct _reent xNewLib_reent; + #endif + + #if( configUSE_TASK_NOTIFICATIONS == 1 ) + volatile uint32_t ulNotifiedValue; + volatile uint8_t ucNotifyState; + #endif + + /* See the comments in FreeRTOS.h with the definition of + tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */ + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */ + #endif + + #if( INCLUDE_xTaskAbortDelay == 1 ) + uint8_t ucDelayAborted; + #endif + + #if( configUSE_POSIX_ERRNO == 1 ) + int iTaskErrno; + #endif + +} tskTCB; + +/* The old tskTCB name is maintained above then typedefed to the new TCB_t name +below to enable the use of older kernel aware debuggers. */ +typedef tskTCB TCB_t; + +/*lint -save -e956 A manual analysis and inspection has been used to determine +which static variables must be declared volatile. */ +PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL; + +/* Lists for ready and blocked tasks. -------------------- +xDelayedTaskList1 and xDelayedTaskList2 could be move to function scople but +doing so breaks some kernel aware debuggers and debuggers that rely on removing +the static qualifier. */ +PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ];/*< Prioritised ready tasks. */ +PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */ +PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */ +PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */ +PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */ + +#if( INCLUDE_vTaskDelete == 1 ) + + PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */ + PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U; + +#endif + +#if ( INCLUDE_vTaskSuspend == 1 ) + + PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */ + +#endif + +/* Global POSIX errno. Its value is changed upon context switching to match +the errno of the currently running task. */ +#if ( configUSE_POSIX_ERRNO == 1 ) + int FreeRTOS_errno = 0; +#endif + +/* Other file private variables. --------------------------------*/ +PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; +PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY; +PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE; +PRIVILEGED_DATA static volatile TickType_t xPendedTicks = ( TickType_t ) 0U; +PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE; +PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0; +PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U; +PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */ +PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */ + +/* Context switches are held pending while the scheduler is suspended. Also, +interrupts must not manipulate the xStateListItem of a TCB, or any of the +lists the xStateListItem can be referenced from, if the scheduler is suspended. +If an interrupt needs to unblock a task while the scheduler is suspended then it +moves the task's event list item into the xPendingReadyList, ready for the +kernel to move the task from the pending ready list into the real ready list +when the scheduler is unsuspended. The pending ready list itself can only be +accessed from a critical section. */ +PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE; + +#if ( configGENERATE_RUN_TIME_STATS == 1 ) + + /* Do not move these variables to function scope as doing so prevents the + code working with debuggers that need to remove the static qualifier. */ + PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */ + PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */ + +#endif + +/*lint -restore */ + +/*-----------------------------------------------------------*/ + +/* Callback function prototypes. --------------------------*/ +#if( configCHECK_FOR_STACK_OVERFLOW > 0 ) + + extern void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName ); + +#endif + +#if( configUSE_TICK_HOOK > 0 ) + + extern void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */ + +#endif + +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + + extern void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */ + +#endif + +/* File private functions. --------------------------------*/ + +/** + * Utility task that simply returns pdTRUE if the task referenced by xTask is + * currently in the Suspended state, or pdFALSE if the task referenced by xTask + * is in any other state. + */ +#if ( INCLUDE_vTaskSuspend == 1 ) + + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION; + +#endif /* INCLUDE_vTaskSuspend */ + +/* + * Utility to ready all the lists used by the scheduler. This is called + * automatically upon the creation of the first task. + */ +static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION; + +/* + * The idle task, which as all tasks is implemented as a never ending loop. + * The idle task is automatically created and added to the ready lists upon + * creation of the first user task. + * + * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific + * language extensions. The equivalent prototype for this function is: + * + * void prvIdleTask( void *pvParameters ); + * + */ +static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters ); + +/* + * Utility to free all memory allocated by the scheduler to hold a TCB, + * including the stack pointed to by the TCB. + * + * This does not free memory allocated by the task itself (i.e. memory + * allocated by calls to pvPortMalloc from within the tasks application code). + */ +#if ( INCLUDE_vTaskDelete == 1 ) + + static void prvDeleteTCB( TCB_t *pxTCB ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Used only by the idle task. This checks to see if anything has been placed + * in the list of tasks waiting to be deleted. If so the task is cleaned up + * and its TCB deleted. + */ +static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION; + +/* + * The currently executing task is entering the Blocked state. Add the task to + * either the current or the overflow delayed task list. + */ +static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseType_t xCanBlockIndefinitely ) PRIVILEGED_FUNCTION; + +/* + * Fills an TaskStatus_t structure with information on each task that is + * referenced from the pxList list (which may be a ready list, a delayed list, + * a suspended list, etc.). + * + * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM + * NORMAL APPLICATION CODE. + */ +#if ( configUSE_TRACE_FACILITY == 1 ) + + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Searches pxList for a task with name pcNameToQuery - returning a handle to + * the task if it is found, or NULL if the task is not found. + */ +#if ( INCLUDE_xTaskGetHandle == 1 ) + + static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) PRIVILEGED_FUNCTION; + +#endif + +/* + * When a task is created, the stack of the task is filled with a known value. + * This function determines the 'high water mark' of the task stack by + * determining how much of the stack remains at the original preset value. + */ +#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Return the amount of time, in ticks, that will pass before the kernel will + * next move a task from the Blocked state to the Running state. + * + * This conditional compilation should use inequality to 0, not equality to 1. + * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user + * defined low power mode implementations require configUSE_TICKLESS_IDLE to be + * set to a value other than 1. + */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + + static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Set xNextTaskUnblockTime to the time at which the next Blocked state task + * will exit the Blocked state. + */ +static void prvResetNextTaskUnblockTime( void ); + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + + /* + * Helper function used to pad task names with spaces when printing out + * human readable tables of task information. + */ + static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) PRIVILEGED_FUNCTION; + +#endif + +/* + * Called after a Task_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t *pxNewTCB, + const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; + +/* + * Called after a new task has been created and initialised to place the task + * under the control of the scheduler. + */ +static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) PRIVILEGED_FUNCTION; + +/* + * freertos_tasks_c_additions_init() should only be called if the user definable + * macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is the only macro + * called by the function. + */ +#ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + + static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION; + +#endif + +/*-----------------------------------------------------------*/ + +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + + TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + StackType_t * const puxStackBuffer, + StaticTask_t * const pxTaskBuffer ) + { + TCB_t *pxNewTCB; + TaskHandle_t xReturn; + + configASSERT( puxStackBuffer != NULL ); + configASSERT( pxTaskBuffer != NULL ); + + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticTask_t equals the size of the real task + structure. */ + volatile size_t xSize = sizeof( StaticTask_t ); + configASSERT( xSize == sizeof( TCB_t ) ); + ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */ + } + #endif /* configASSERT_DEFINED */ + + + if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) ) + { + /* The memory used for the task's TCB and stack are passed into this + function - use them. */ + pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */ + pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer; + + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + { + /* Tasks can be created statically or dynamically, so note this + task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL ); + prvAddNewTaskToReadyList( pxNewTCB ); + } + else + { + xReturn = NULL; + } + + return xReturn; + } + +#endif /* SUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) + + BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) + { + TCB_t *pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + + configASSERT( pxTaskDefinition->puxStackBuffer != NULL ); + configASSERT( pxTaskDefinition->pxTaskBuffer != NULL ); + + if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) ) + { + /* Allocate space for the TCB. Where the memory comes from depends + on the implementation of the port malloc function and whether or + not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer; + + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note this + task was created statically in case the task is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + + return xReturn; + } + +#endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */ +/*-----------------------------------------------------------*/ + +#if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask ) + { + TCB_t *pxNewTCB; + BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + + configASSERT( pxTaskDefinition->puxStackBuffer ); + + if( pxTaskDefinition->puxStackBuffer != NULL ) + { + /* Allocate space for the TCB. Where the memory comes from depends + on the implementation of the port malloc function and whether or + not static allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + + if( pxNewTCB != NULL ) + { + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer; + + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) + { + /* Tasks can be created statically or dynamically, so note + this task had a statically allocated stack in case it is + later deleted. The TCB was allocated dynamically. */ + pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskDefinition->pvTaskCode, + pxTaskDefinition->pcName, + ( uint32_t ) pxTaskDefinition->usStackDepth, + pxTaskDefinition->pvParameters, + pxTaskDefinition->uxPriority, + pxCreatedTask, pxNewTCB, + pxTaskDefinition->xRegions ); + + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + } + + return xReturn; + } + +#endif /* portUSING_MPU_WRAPPERS */ +/*-----------------------------------------------------------*/ + +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const configSTACK_DEPTH_TYPE usStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask ) + { + TCB_t *pxNewTCB; + BaseType_t xReturn; + + /* If the stack grows down then allocate the stack then the TCB so the stack + does not grow into the TCB. Likewise if the stack grows up then allocate + the TCB then the stack. */ + #if( portSTACK_GROWTH > 0 ) + { + /* Allocate space for the TCB. Where the memory comes from depends on + the implementation of the port malloc function and whether or not static + allocation is being used. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); + + if( pxNewTCB != NULL ) + { + /* Allocate space for the stack used by the task being created. + The base of the stack memory stored in the TCB so the task can + be deleted later if required. */ + pxNewTCB->pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + if( pxNewTCB->pxStack == NULL ) + { + /* Could not allocate the stack. Delete the allocated TCB. */ + vPortFree( pxNewTCB ); + pxNewTCB = NULL; + } + } + } + #else /* portSTACK_GROWTH */ + { + StackType_t *pxStack; + + /* Allocate space for the stack used by the task being created. */ + pxStack = pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */ + + if( pxStack != NULL ) + { + /* Allocate space for the TCB. */ + pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of TCB_t is always a pointer to the task's stack. */ + + if( pxNewTCB != NULL ) + { + /* Store the stack location in the TCB. */ + pxNewTCB->pxStack = pxStack; + } + else + { + /* The stack cannot be used as the TCB was not created. Free + it again. */ + vPortFree( pxStack ); + } + } + else + { + pxNewTCB = NULL; + } + } + #endif /* portSTACK_GROWTH */ + + if( pxNewTCB != NULL ) + { + #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */ + { + /* Tasks can be created statically or dynamically, so note this + task was created dynamically in case it is later deleted. */ + pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB; + } + #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */ + + prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL ); + prvAddNewTaskToReadyList( pxNewTCB ); + xReturn = pdPASS; + } + else + { + xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY; + } + + return xReturn; + } + +#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewTask( TaskFunction_t pxTaskCode, + const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const uint32_t ulStackDepth, + void * const pvParameters, + UBaseType_t uxPriority, + TaskHandle_t * const pxCreatedTask, + TCB_t *pxNewTCB, + const MemoryRegion_t * const xRegions ) +{ +StackType_t *pxTopOfStack; +UBaseType_t x; + + #if( portUSING_MPU_WRAPPERS == 1 ) + /* Should the task be created in privileged mode? */ + BaseType_t xRunPrivileged; + if( ( uxPriority & portPRIVILEGE_BIT ) != 0U ) + { + xRunPrivileged = pdTRUE; + } + else + { + xRunPrivileged = pdFALSE; + } + uxPriority &= ~portPRIVILEGE_BIT; + #endif /* portUSING_MPU_WRAPPERS == 1 */ + + /* Avoid dependency on memset() if it is not required. */ + #if( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 ) + { + /* Fill the stack with a known value to assist debugging. */ + ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) ); + } + #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */ + + /* Calculate the top of stack address. This depends on whether the stack + grows from high memory to low (as per the 80x86) or vice versa. + portSTACK_GROWTH is used to make the result positive or negative as required + by the port. */ + #if( portSTACK_GROWTH < 0 ) + { + pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] ); + pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */ + + /* Check the alignment of the calculated top of stack is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); + + #if( configRECORD_STACK_HIGH_ADDRESS == 1 ) + { + /* Also record the stack's high address, which may assist + debugging. */ + pxNewTCB->pxEndOfStack = pxTopOfStack; + } + #endif /* configRECORD_STACK_HIGH_ADDRESS */ + } + #else /* portSTACK_GROWTH */ + { + pxTopOfStack = pxNewTCB->pxStack; + + /* Check the alignment of the stack buffer is correct. */ + configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) ); + + /* The other extreme of the stack space is required if stack checking is + performed. */ + pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 ); + } + #endif /* portSTACK_GROWTH */ + + /* Store the task name in the TCB. */ + if( pcName != NULL ) + { + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + pxNewTCB->pcTaskName[ x ] = pcName[ x ]; + + /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than + configMAX_TASK_NAME_LEN characters just in case the memory after the + string is not accessible (extremely unlikely). */ + if( pcName[ x ] == ( char ) 0x00 ) + { + break; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Ensure the name string is terminated in the case that the string length + was greater or equal to configMAX_TASK_NAME_LEN. */ + pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0'; + } + else + { + /* The task has not been given a name, so just ensure there is a NULL + terminator when it is read out. */ + pxNewTCB->pcTaskName[ 0 ] = 0x00; + } + + /* This is used as an array index so must ensure it's not too large. First + remove the privilege bit if one is present. */ + if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxNewTCB->uxPriority = uxPriority; + #if ( configUSE_MUTEXES == 1 ) + { + pxNewTCB->uxBasePriority = uxPriority; + pxNewTCB->uxMutexesHeld = 0; + } + #endif /* configUSE_MUTEXES */ + + vListInitialiseItem( &( pxNewTCB->xStateListItem ) ); + vListInitialiseItem( &( pxNewTCB->xEventListItem ) ); + + /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get + back to the containing TCB from a generic item in a list. */ + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB ); + + /* Event lists are always in priority order. */ + listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB ); + + #if ( portCRITICAL_NESTING_IN_TCB == 1 ) + { + pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U; + } + #endif /* portCRITICAL_NESTING_IN_TCB */ + + #if ( configUSE_APPLICATION_TASK_TAG == 1 ) + { + pxNewTCB->pxTaskTag = NULL; + } + #endif /* configUSE_APPLICATION_TASK_TAG */ + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxNewTCB->ulRunTimeCounter = 0UL; + } + #endif /* configGENERATE_RUN_TIME_STATS */ + + #if ( portUSING_MPU_WRAPPERS == 1 ) + { + vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth ); + } + #else + { + /* Avoid compiler warning about unreferenced parameter. */ + ( void ) xRegions; + } + #endif + + #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + { + for( x = 0; x < ( UBaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ ) + { + pxNewTCB->pvThreadLocalStoragePointers[ x ] = NULL; + } + } + #endif + + #if ( configUSE_TASK_NOTIFICATIONS == 1 ) + { + pxNewTCB->ulNotifiedValue = 0; + pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + #endif + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Initialise this task's Newlib reent structure. + See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + for additional information. */ + _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) ); + } + #endif + + #if( INCLUDE_xTaskAbortDelay == 1 ) + { + pxNewTCB->ucDelayAborted = pdFALSE; + } + #endif + + /* Initialize the TCB stack to look as if the task was already running, + but had been interrupted by the scheduler. The return address is set + to the start of the task function. Once the stack has been initialised + the top of stack variable is updated. */ + #if( portUSING_MPU_WRAPPERS == 1 ) + { + /* If the port has capability to detect stack overflow, + pass the stack end address to the stack initialization + function as well. */ + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #else /* portUSING_MPU_WRAPPERS */ + { + /* If the port has capability to detect stack overflow, + pass the stack end address to the stack initialization + function as well. */ + #if( portHAS_STACK_OVERFLOW_CHECKING == 1 ) + { + #if( portSTACK_GROWTH < 0 ) + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters ); + } + #else /* portSTACK_GROWTH */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters ); + } + #endif /* portSTACK_GROWTH */ + } + #else /* portHAS_STACK_OVERFLOW_CHECKING */ + { + pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters ); + } + #endif /* portHAS_STACK_OVERFLOW_CHECKING */ + } + #endif /* portUSING_MPU_WRAPPERS */ + + if( pxCreatedTask != NULL ) + { + /* Pass the handle out in an anonymous way. The handle can be used to + change the created task's priority, delete the created task, etc.*/ + *pxCreatedTask = ( TaskHandle_t ) pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) +{ + /* Ensure interrupts don't access the task lists while the lists are being + updated. */ + taskENTER_CRITICAL(); + { + uxCurrentNumberOfTasks++; + if( pxCurrentTCB == NULL ) + { + /* There are no other tasks, or all the other tasks are in + the suspended state - make this the current task. */ + pxCurrentTCB = pxNewTCB; + + if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 ) + { + /* This is the first task to be created so do the preliminary + initialisation required. We will not recover if this call + fails, but we will report the failure. */ + prvInitialiseTaskLists(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* If the scheduler is not already running, make this task the + current task if it is the highest priority task to be created + so far. */ + if( xSchedulerRunning == pdFALSE ) + { + if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority ) + { + pxCurrentTCB = pxNewTCB; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + uxTaskNumber++; + + #if ( configUSE_TRACE_FACILITY == 1 ) + { + /* Add a counter into the TCB for tracing only. */ + pxNewTCB->uxTCBNumber = uxTaskNumber; + } + #endif /* configUSE_TRACE_FACILITY */ + traceTASK_CREATE( pxNewTCB ); + + prvAddTaskToReadyList( pxNewTCB ); + + portSETUP_TCB( pxNewTCB ); + } + taskEXIT_CRITICAL(); + + if( xSchedulerRunning != pdFALSE ) + { + /* If the created task is of a higher priority than the current task + then it should run now. */ + if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority ) + { + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } +} +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelete == 1 ) + + void vTaskDelete( TaskHandle_t xTaskToDelete ) + { + TCB_t *pxTCB; + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the calling task that is + being deleted. */ + pxTCB = prvGetTCBFromHandle( xTaskToDelete ); + + /* Remove task from the ready/delayed list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Increment the uxTaskNumber also so kernel aware debuggers can + detect that the task lists need re-generating. This is done before + portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will + not return. */ + uxTaskNumber++; + + if( pxTCB == pxCurrentTCB ) + { + /* A task is deleting itself. This cannot complete within the + task itself, as a context switch to another task is required. + Place the task in the termination list. The idle task will + check the termination list and free up any memory allocated by + the scheduler for the TCB and stack of the deleted task. */ + vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) ); + + /* Increment the ucTasksDeleted variable so the idle task knows + there is a task that has been deleted and that it should therefore + check the xTasksWaitingTermination list. */ + ++uxDeletedTasksWaitingCleanUp; + + /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as + portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */ + traceTASK_DELETE( pxTCB ); + + /* The pre-delete hook is primarily for the Windows simulator, + in which Windows specific clean up operations are performed, + after which it is not possible to yield away from this task - + hence xYieldPending is used to latch that a context switch is + required. */ + portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending ); + } + else + { + --uxCurrentNumberOfTasks; + traceTASK_DELETE( pxTCB ); + prvDeleteTCB( pxTCB ); + + /* Reset the next expected unblock time in case it referred to + the task that has just been deleted. */ + prvResetNextTaskUnblockTime(); + } + } + taskEXIT_CRITICAL(); + + /* Force a reschedule if it is the currently running task that has just + been deleted. */ + if( xSchedulerRunning != pdFALSE ) + { + if( pxTCB == pxCurrentTCB ) + { + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + +#endif /* INCLUDE_vTaskDelete */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelayUntil == 1 ) + + void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) + { + TickType_t xTimeToWake; + BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE; + + configASSERT( pxPreviousWakeTime ); + configASSERT( ( xTimeIncrement > 0U ) ); + configASSERT( uxSchedulerSuspended == 0 ); + + vTaskSuspendAll(); + { + /* Minor optimisation. The tick count cannot change in this + block. */ + const TickType_t xConstTickCount = xTickCount; + + /* Generate the tick time at which the task wants to wake. */ + xTimeToWake = *pxPreviousWakeTime + xTimeIncrement; + + if( xConstTickCount < *pxPreviousWakeTime ) + { + /* The tick count has overflowed since this function was + lasted called. In this case the only time we should ever + actually delay is if the wake time has also overflowed, + and the wake time is greater than the tick time. When this + is the case it is as if neither time had overflowed. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The tick time has not overflowed. In this case we will + delay if either the wake time has overflowed, and/or the + tick time is less than the wake time. */ + if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) ) + { + xShouldDelay = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Update the wake time ready for the next call. */ + *pxPreviousWakeTime = xTimeToWake; + + if( xShouldDelay != pdFALSE ) + { + traceTASK_DELAY_UNTIL( xTimeToWake ); + + /* prvAddCurrentTaskToDelayedList() needs the block time, not + the time to wake, so subtract the current tick count. */ + prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + xAlreadyYielded = xTaskResumeAll(); + + /* Force a reschedule if xTaskResumeAll has not already done so, we may + have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskDelayUntil */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelay == 1 ) + + void vTaskDelay( const TickType_t xTicksToDelay ) + { + BaseType_t xAlreadyYielded = pdFALSE; + + /* A delay time of zero just forces a reschedule. */ + if( xTicksToDelay > ( TickType_t ) 0U ) + { + configASSERT( uxSchedulerSuspended == 0 ); + vTaskSuspendAll(); + { + traceTASK_DELAY(); + + /* A task that is removed from the event list while the + scheduler is suspended will not get placed in the ready + list or removed from the blocked list until the scheduler + is resumed. + + This task cannot be in an event list as it is the currently + executing task. */ + prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE ); + } + xAlreadyYielded = xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Force a reschedule if xTaskResumeAll has not already done so, we may + have put ourselves to sleep. */ + if( xAlreadyYielded == pdFALSE ) + { + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskDelay */ +/*-----------------------------------------------------------*/ + +#if( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) ) + + eTaskState eTaskGetState( TaskHandle_t xTask ) + { + eTaskState eReturn; + List_t const * pxStateList, *pxDelayedList, *pxOverflowedDelayedList; + const TCB_t * const pxTCB = xTask; + + configASSERT( pxTCB ); + + if( pxTCB == pxCurrentTCB ) + { + /* The task calling this function is querying its own state. */ + eReturn = eRunning; + } + else + { + taskENTER_CRITICAL(); + { + pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) ); + pxDelayedList = pxDelayedTaskList; + pxOverflowedDelayedList = pxOverflowDelayedTaskList; + } + taskEXIT_CRITICAL(); + + if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) ) + { + /* The task being queried is referenced from one of the Blocked + lists. */ + eReturn = eBlocked; + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + else if( pxStateList == &xSuspendedTaskList ) + { + /* The task being queried is referenced from the suspended + list. Is it genuinely suspended or is it blocked + indefinitely? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ) + { + #if( configUSE_TASK_NOTIFICATIONS == 1 ) + { + /* The task does not appear on the event list item of + and of the RTOS objects, but could still be in the + blocked state if it is waiting on its notification + rather than waiting on an object. */ + if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) + { + eReturn = eBlocked; + } + else + { + eReturn = eSuspended; + } + } + #else + { + eReturn = eSuspended; + } + #endif + } + else + { + eReturn = eBlocked; + } + } + #endif + + #if ( INCLUDE_vTaskDelete == 1 ) + else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) ) + { + /* The task being queried is referenced from the deleted + tasks list, or it is not referenced from any lists at + all. */ + eReturn = eDeleted; + } + #endif + + else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */ + { + /* If the task is not in any other state, it must be in the + Ready (including pending ready) state. */ + eReturn = eReady; + } + } + + return eReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + +#endif /* INCLUDE_eTaskGetState */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskPriorityGet == 1 ) + + UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask ) + { + TCB_t const *pxTCB; + UBaseType_t uxReturn; + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the task + that called uxTaskPriorityGet() that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + taskEXIT_CRITICAL(); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskPriorityGet */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskPriorityGet == 1 ) + + UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask ) + { + TCB_t const *pxTCB; + UBaseType_t uxReturn, uxSavedInterruptState; + + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + https://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR(); + { + /* If null is passed in here then it is the priority of the calling + task that is being queried. */ + pxTCB = prvGetTCBFromHandle( xTask ); + uxReturn = pxTCB->uxPriority; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskPriorityGet */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskPrioritySet == 1 ) + + void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) + { + TCB_t *pxTCB; + UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry; + BaseType_t xYieldRequired = pdFALSE; + + configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) ); + + /* Ensure the new priority is valid. */ + if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES ) + { + uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the priority of the calling + task that is being changed. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + traceTASK_PRIORITY_SET( pxTCB, uxNewPriority ); + + #if ( configUSE_MUTEXES == 1 ) + { + uxCurrentBasePriority = pxTCB->uxBasePriority; + } + #else + { + uxCurrentBasePriority = pxTCB->uxPriority; + } + #endif + + if( uxCurrentBasePriority != uxNewPriority ) + { + /* The priority change may have readied a task of higher + priority than the calling task. */ + if( uxNewPriority > uxCurrentBasePriority ) + { + if( pxTCB != pxCurrentTCB ) + { + /* The priority of a task other than the currently + running task is being raised. Is the priority being + raised above that of the running task? */ + if( uxNewPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + /* The priority of the running task is being raised, + but the running task must already be the highest + priority task able to run so no yield is required. */ + } + } + else if( pxTCB == pxCurrentTCB ) + { + /* Setting the priority of the running task down means + there may now be another task of higher priority that + is ready to execute. */ + xYieldRequired = pdTRUE; + } + else + { + /* Setting the priority of any other task down does not + require a yield as the running task must be above the + new priority of the task being modified. */ + } + + /* Remember the ready list the task might be referenced from + before its uxPriority member is changed so the + taskRESET_READY_PRIORITY() macro can function correctly. */ + uxPriorityUsedOnEntry = pxTCB->uxPriority; + + #if ( configUSE_MUTEXES == 1 ) + { + /* Only change the priority being used if the task is not + currently using an inherited priority. */ + if( pxTCB->uxBasePriority == pxTCB->uxPriority ) + { + pxTCB->uxPriority = uxNewPriority; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* The base priority gets set whatever. */ + pxTCB->uxBasePriority = uxNewPriority; + } + #else + { + pxTCB->uxPriority = uxNewPriority; + } + #endif + + /* Only reset the event list item value if the value is not + being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the task is in the blocked or suspended list we need do + nothing more than change its priority variable. However, if + the task is in a ready list it needs to be removed and placed + in the list appropriate to its new priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* The task is currently in its ready list - remove before + adding it to it's new ready list. As we are in a critical + section we can do this even if the scheduler is suspended. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + there is no need to check again and the port level + reset macro can be called directly. */ + portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + prvAddTaskToReadyList( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xYieldRequired != pdFALSE ) + { + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Remove compiler warning about unused variables when the port + optimised task selection is not being used. */ + ( void ) uxPriorityUsedOnEntry; + } + } + taskEXIT_CRITICAL(); + } + +#endif /* INCLUDE_vTaskPrioritySet */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + void vTaskSuspend( TaskHandle_t xTaskToSuspend ) + { + TCB_t *pxTCB; + + taskENTER_CRITICAL(); + { + /* If null is passed in here then it is the running task that is + being suspended. */ + pxTCB = prvGetTCBFromHandle( xTaskToSuspend ); + + traceTASK_SUSPEND( pxTCB ); + + /* Remove task from the ready/delayed list and place in the + suspended list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Is the task waiting on an event also? */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ); + + #if( configUSE_TASK_NOTIFICATIONS == 1 ) + { + if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task was blocked to wait for a notification, but is + now suspended, so no notification was received. */ + pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + } + #endif + } + taskEXIT_CRITICAL(); + + if( xSchedulerRunning != pdFALSE ) + { + /* Reset the next expected unblock time in case it referred to the + task that is now in the Suspended state. */ + taskENTER_CRITICAL(); + { + prvResetNextTaskUnblockTime(); + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( pxTCB == pxCurrentTCB ) + { + if( xSchedulerRunning != pdFALSE ) + { + /* The current task has just been suspended. */ + configASSERT( uxSchedulerSuspended == 0 ); + portYIELD_WITHIN_API(); + } + else + { + /* The scheduler is not running, but the task that was pointed + to by pxCurrentTCB has just been suspended and pxCurrentTCB + must be adjusted to point to a different task. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */ + { + /* No other tasks are ready, so set pxCurrentTCB back to + NULL so when the next task is created pxCurrentTCB will + be set to point to it no matter what its relative priority + is. */ + pxCurrentTCB = NULL; + } + else + { + vTaskSwitchContext(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskSuspend */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) + { + BaseType_t xReturn = pdFALSE; + const TCB_t * const pxTCB = xTask; + + /* Accesses xPendingReadyList so must be called from a critical + section. */ + + /* It does not make sense to check if the calling task is suspended. */ + configASSERT( xTask ); + + /* Is the task being resumed actually in the suspended list? */ + if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + /* Has the task already been resumed from within an ISR? */ + if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE ) + { + /* Is it in the suspended list because it is in the Suspended + state, or because is is blocked with no timeout? */ + if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */ + { + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */ + +#endif /* INCLUDE_vTaskSuspend */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskSuspend == 1 ) + + void vTaskResume( TaskHandle_t xTaskToResume ) + { + TCB_t * const pxTCB = xTaskToResume; + + /* It does not make sense to resume the calling task. */ + configASSERT( xTaskToResume ); + + /* The parameter cannot be NULL as it is impossible to resume the + currently executing task. */ + if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) ) + { + taskENTER_CRITICAL(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME( pxTCB ); + + /* The ready list can be accessed even if the scheduler is + suspended because this is inside a critical section. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + /* A higher priority task may have just been resumed. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + /* This yield may not cause the task just resumed to run, + but will leave the lists in the correct state for the + next yield. */ + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* INCLUDE_vTaskSuspend */ + +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) + + BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) + { + BaseType_t xYieldRequired = pdFALSE; + TCB_t * const pxTCB = xTaskToResume; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( xTaskToResume ); + + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + https://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE ) + { + traceTASK_RESUME_FROM_ISR( pxTCB ); + + /* Check the ready lists can be accessed. */ + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + /* Ready lists can be accessed so move the task from the + suspended list to the ready list directly. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xYieldRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed or ready lists cannot be accessed so the task + is held in the pending ready list until the scheduler is + unsuspended. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xYieldRequired; + } + +#endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */ +/*-----------------------------------------------------------*/ + +void vTaskStartScheduler( void ) +{ +BaseType_t xReturn; + + /* Add the idle task at the lowest priority. */ + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t *pxIdleTaskTCBBuffer = NULL; + StackType_t *pxIdleTaskStackBuffer = NULL; + uint32_t ulIdleTaskStackSize; + + /* The Idle task is created using user provided RAM - obtain the + address of the RAM then create the idle task. */ + vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize ); + xIdleTaskHandle = xTaskCreateStatic( prvIdleTask, + configIDLE_TASK_NAME, + ulIdleTaskStackSize, + ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */ + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + pxIdleTaskStackBuffer, + pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + + if( xIdleTaskHandle != NULL ) + { + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + #else + { + /* The Idle task is being created using dynamically allocated RAM. */ + xReturn = xTaskCreate( prvIdleTask, + configIDLE_TASK_NAME, + configMINIMAL_STACK_SIZE, + ( void * ) NULL, + portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */ + &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */ + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + + #if ( configUSE_TIMERS == 1 ) + { + if( xReturn == pdPASS ) + { + xReturn = xTimerCreateTimerTask(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TIMERS */ + + if( xReturn == pdPASS ) + { + /* freertos_tasks_c_additions_init() should only be called if the user + definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is + the only macro called by the function. */ + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + { + freertos_tasks_c_additions_init(); + } + #endif + + /* Interrupts are turned off here, to ensure a tick does not occur + before or during the call to xPortStartScheduler(). The stacks of + the created tasks contain a status word with interrupts switched on + so interrupts will automatically get re-enabled when the first task + starts to run. */ + portDISABLE_INTERRUPTS(); + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Switch Newlib's _impure_ptr variable to point to the _reent + structure specific to the task that will run first. + See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + for additional information. */ + _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ + + xNextTaskUnblockTime = portMAX_DELAY; + xSchedulerRunning = pdTRUE; + xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT; + + /* If configGENERATE_RUN_TIME_STATS is defined then the following + macro must be defined to configure the timer/counter used to generate + the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS + is set to 0 and the following line fails to build then ensure you do not + have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your + FreeRTOSConfig.h file. */ + portCONFIGURE_TIMER_FOR_RUN_TIME_STATS(); + + traceTASK_SWITCHED_IN(); + + /* Setting up the timer tick is hardware specific and thus in the + portable interface. */ + if( xPortStartScheduler() != pdFALSE ) + { + /* Should not reach here as if the scheduler is running the + function will not return. */ + } + else + { + /* Should only reach here if a task calls xTaskEndScheduler(). */ + } + } + else + { + /* This line will only be reached if the kernel could not be started, + because there was not enough FreeRTOS heap to create the idle task + or the timer task. */ + configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY ); + } + + /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0, + meaning xIdleTaskHandle is not used anywhere else. */ + ( void ) xIdleTaskHandle; +} +/*-----------------------------------------------------------*/ + +void vTaskEndScheduler( void ) +{ + /* Stop the scheduler interrupts and call the portable scheduler end + routine so the original ISRs can be restored if necessary. The port + layer must ensure interrupts enable bit is left in the correct state. */ + portDISABLE_INTERRUPTS(); + xSchedulerRunning = pdFALSE; + vPortEndScheduler(); +} +/*----------------------------------------------------------*/ + +void vTaskSuspendAll( void ) +{ + /* A critical section is not required as the variable is of type + BaseType_t. Please read Richard Barry's reply in the following link to a + post in the FreeRTOS support forum before reporting this as a bug! - + http://goo.gl/wu4acr */ + + /* portSOFRWARE_BARRIER() is only implemented for emulated/simulated ports that + do not otherwise exhibit real time behaviour. */ + portSOFTWARE_BARRIER(); + + /* The scheduler is suspended if uxSchedulerSuspended is non-zero. An increment + is used to allow calls to vTaskSuspendAll() to nest. */ + ++uxSchedulerSuspended; + + /* Enforces ordering for ports and optimised compilers that may otherwise place + the above increment elsewhere. */ + portMEMORY_BARRIER(); +} +/*----------------------------------------------------------*/ + +#if ( configUSE_TICKLESS_IDLE != 0 ) + + static TickType_t prvGetExpectedIdleTime( void ) + { + TickType_t xReturn; + UBaseType_t uxHigherPriorityReadyTasks = pdFALSE; + + /* uxHigherPriorityReadyTasks takes care of the case where + configUSE_PREEMPTION is 0, so there may be tasks above the idle priority + task that are in the Ready state, even though the idle task is + running. */ + #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 ) + { + if( uxTopReadyPriority > tskIDLE_PRIORITY ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #else + { + const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01; + + /* When port optimised task selection is used the uxTopReadyPriority + variable is used as a bit map. If bits other than the least + significant bit are set then there are tasks that have a priority + above the idle priority that are in the Ready state. This takes + care of the case where the co-operative scheduler is in use. */ + if( uxTopReadyPriority > uxLeastSignificantBit ) + { + uxHigherPriorityReadyTasks = pdTRUE; + } + } + #endif + + if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY ) + { + xReturn = 0; + } + else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 ) + { + /* There are other idle priority tasks in the ready state. If + time slicing is used then the very next tick interrupt must be + processed. */ + xReturn = 0; + } + else if( uxHigherPriorityReadyTasks != pdFALSE ) + { + /* There are tasks in the Ready state that have a priority above the + idle priority. This path can only be reached if + configUSE_PREEMPTION is 0. */ + xReturn = 0; + } + else + { + xReturn = xNextTaskUnblockTime - xTickCount; + } + + return xReturn; + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskResumeAll( void ) +{ +TCB_t *pxTCB = NULL; +BaseType_t xAlreadyYielded = pdFALSE; + + /* If uxSchedulerSuspended is zero then this function does not match a + previous call to vTaskSuspendAll(). */ + configASSERT( uxSchedulerSuspended ); + + /* It is possible that an ISR caused a task to be removed from an event + list while the scheduler was suspended. If this was the case then the + removed task will have been added to the xPendingReadyList. Once the + scheduler has been resumed it is safe to move all the pending ready + tasks from this list into their appropriate ready list. */ + taskENTER_CRITICAL(); + { + --uxSchedulerSuspended; + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U ) + { + /* Move any readied tasks from the pending list into the + appropriate ready list. */ + while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE ) + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + /* If the moved task has a priority higher than the current + task then a yield must be performed. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + if( pxTCB != NULL ) + { + /* A task was unblocked while the scheduler was suspended, + which may have prevented the next unblock time from being + re-calculated, in which case re-calculate it now. Mainly + important for low power tickless implementations, where + this can prevent an unnecessary exit from low power + state. */ + prvResetNextTaskUnblockTime(); + } + + /* If any ticks occurred while the scheduler was suspended then + they should be processed now. This ensures the tick count does + not slip, and that any delayed tasks are resumed at the correct + time. */ + { + TickType_t xPendedCounts = xPendedTicks; /* Non-volatile copy. */ + + if( xPendedCounts > ( TickType_t ) 0U ) + { + do + { + if( xTaskIncrementTick() != pdFALSE ) + { + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + --xPendedCounts; + } while( xPendedCounts > ( TickType_t ) 0U ); + + xPendedTicks = 0; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + if( xYieldPending != pdFALSE ) + { + #if( configUSE_PREEMPTION != 0 ) + { + xAlreadyYielded = pdTRUE; + } + #endif + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + return xAlreadyYielded; +} +/*-----------------------------------------------------------*/ + +TickType_t xTaskGetTickCount( void ) +{ +TickType_t xTicks; + + /* Critical section required if running on a 16 bit processor. */ + portTICK_TYPE_ENTER_CRITICAL(); + { + xTicks = xTickCount; + } + portTICK_TYPE_EXIT_CRITICAL(); + + return xTicks; +} +/*-----------------------------------------------------------*/ + +TickType_t xTaskGetTickCountFromISR( void ) +{ +TickType_t xReturn; +UBaseType_t uxSavedInterruptStatus; + + /* RTOS ports that support interrupt nesting have the concept of a maximum + system call (or maximum API call) interrupt priority. Interrupts that are + above the maximum system call priority are kept permanently enabled, even + when the RTOS kernel is in a critical section, but cannot make any calls to + FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h + then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has been + assigned a priority above the configured maximum system call priority. + Only FreeRTOS functions that end in FromISR can be called from interrupts + that have been assigned a priority at or (logically) below the maximum + system call interrupt priority. FreeRTOS maintains a separate interrupt + safe API to ensure interrupt entry is as fast and as simple as possible. + More information (albeit Cortex-M specific) is provided on the following + link: https://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR(); + { + xReturn = xTickCount; + } + portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxTaskGetNumberOfTasks( void ) +{ + /* A critical section is not required because the variables are of type + BaseType_t. */ + return uxCurrentNumberOfTasks; +} +/*-----------------------------------------------------------*/ + +char *pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +{ +TCB_t *pxTCB; + + /* If null is passed in here then the name of the calling task is being + queried. */ + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + configASSERT( pxTCB ); + return &( pxTCB->pcTaskName[ 0 ] ); +} +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetHandle == 1 ) + + static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) + { + TCB_t *pxNextTCB, *pxFirstTCB, *pxReturn = NULL; + UBaseType_t x; + char cNextChar; + BaseType_t xBreakLoop; + + /* This function is called with the scheduler suspended. */ + + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + + do + { + listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + + /* Check each character in the name looking for a match or + mismatch. */ + xBreakLoop = pdFALSE; + for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ ) + { + cNextChar = pxNextTCB->pcTaskName[ x ]; + + if( cNextChar != pcNameToQuery[ x ] ) + { + /* Characters didn't match. */ + xBreakLoop = pdTRUE; + } + else if( cNextChar == ( char ) 0x00 ) + { + /* Both strings terminated, a match must have been + found. */ + pxReturn = pxNextTCB; + xBreakLoop = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + if( xBreakLoop != pdFALSE ) + { + break; + } + } + + if( pxReturn != NULL ) + { + /* The handle has been found. */ + break; + } + + } while( pxNextTCB != pxFirstTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return pxReturn; + } + +#endif /* INCLUDE_xTaskGetHandle */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetHandle == 1 ) + + TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + { + UBaseType_t uxQueue = configMAX_PRIORITIES; + TCB_t* pxTCB; + + /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */ + configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN ); + + vTaskSuspendAll(); + { + /* Search the ready lists. */ + do + { + uxQueue--; + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery ); + + if( pxTCB != NULL ) + { + /* Found the handle. */ + break; + } + + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + /* Search the delayed lists. */ + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery ); + } + + if( pxTCB == NULL ) + { + pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery ); + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the suspended list. */ + pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery ); + } + } + #endif + + #if( INCLUDE_vTaskDelete == 1 ) + { + if( pxTCB == NULL ) + { + /* Search the deleted list. */ + pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery ); + } + } + #endif + } + ( void ) xTaskResumeAll(); + + return pxTCB; + } + +#endif /* INCLUDE_xTaskGetHandle */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime ) + { + UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES; + + vTaskSuspendAll(); + { + /* Is there a space in the array for each task in the system? */ + if( uxArraySize >= uxCurrentNumberOfTasks ) + { + /* Fill in an TaskStatus_t structure with information on each + task in the Ready state. */ + do + { + uxQueue--; + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady ); + + } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + /* Fill in an TaskStatus_t structure with information on each + task in the Blocked state. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked ); + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked ); + + #if( INCLUDE_vTaskDelete == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + each task that has been deleted but not yet cleaned up. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted ); + } + #endif + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* Fill in an TaskStatus_t structure with information on + each task in the Suspended state. */ + uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended ); + } + #endif + + #if ( configGENERATE_RUN_TIME_STATS == 1) + { + if( pulTotalRunTime != NULL ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) ); + #else + *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); + #endif + } + } + #else + { + if( pulTotalRunTime != NULL ) + { + *pulTotalRunTime = 0; + } + } + #endif + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + + return uxTask; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) + + TaskHandle_t xTaskGetIdleTaskHandle( void ) + { + /* If xTaskGetIdleTaskHandle() is called before the scheduler has been + started, then xIdleTaskHandle will be NULL. */ + configASSERT( ( xIdleTaskHandle != NULL ) ); + return xIdleTaskHandle; + } + +#endif /* INCLUDE_xTaskGetIdleTaskHandle */ +/*----------------------------------------------------------*/ + +/* This conditional compilation should use inequality to 0, not equality to 1. +This is to ensure vTaskStepTick() is available when user defined low power mode +implementations require configUSE_TICKLESS_IDLE to be set to a value other than +1. */ +#if ( configUSE_TICKLESS_IDLE != 0 ) + + void vTaskStepTick( const TickType_t xTicksToJump ) + { + /* Correct the tick count value after a period during which the tick + was suppressed. Note this does *not* call the tick hook function for + each stepped tick. */ + configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime ); + xTickCount += xTicksToJump; + traceINCREASE_TICK_COUNT( xTicksToJump ); + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp ) +{ +BaseType_t xYieldRequired = pdFALSE; + + /* Must not be called with the scheduler suspended as the implementation + relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */ + configASSERT( uxSchedulerSuspended == 0 ); + + /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when + the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */ + vTaskSuspendAll(); + xPendedTicks += xTicksToCatchUp; + xYieldRequired = xTaskResumeAll(); + + return xYieldRequired; +} +/*----------------------------------------------------------*/ + +#if ( INCLUDE_xTaskAbortDelay == 1 ) + + BaseType_t xTaskAbortDelay( TaskHandle_t xTask ) + { + TCB_t *pxTCB = xTask; + BaseType_t xReturn; + + configASSERT( pxTCB ); + + vTaskSuspendAll(); + { + /* A task can only be prematurely removed from the Blocked state if + it is actually in the Blocked state. */ + if( eTaskGetState( xTask ) == eBlocked ) + { + xReturn = pdPASS; + + /* Remove the reference to the task from the blocked list. An + interrupt won't touch the xStateListItem because the + scheduler is suspended. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + + /* Is the task waiting on an event also? If so remove it from + the event list too. Interrupts can touch the event list item, + even though the scheduler is suspended, so a critical section + is used. */ + taskENTER_CRITICAL(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + + /* This lets the task know it was forcibly removed from the + blocked state so it should not re-evaluate its block time and + then block again. */ + pxTCB->ucDelayAborted = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + /* Place the unblocked task into the appropriate ready list. */ + prvAddTaskToReadyList( pxTCB ); + + /* A task being unblocked cannot cause an immediate context + switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + /* Preemption is on, but a context switch should only be + performed if the unblocked task has a priority that is + equal to or higher than the currently executing task. */ + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Pend the yield to be performed when the scheduler + is unsuspended. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + else + { + xReturn = pdFAIL; + } + } + ( void ) xTaskResumeAll(); + + return xReturn; + } + +#endif /* INCLUDE_xTaskAbortDelay */ +/*----------------------------------------------------------*/ + +BaseType_t xTaskIncrementTick( void ) +{ +TCB_t * pxTCB; +TickType_t xItemValue; +BaseType_t xSwitchRequired = pdFALSE; + + /* Called by the portable layer each time a tick interrupt occurs. + Increments the tick then checks to see if the new tick value will cause any + tasks to be unblocked. */ + traceTASK_INCREMENT_TICK( xTickCount ); + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + /* Minor optimisation. The tick count cannot change in this + block. */ + const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1; + + /* Increment the RTOS tick, switching the delayed and overflowed + delayed lists if it wraps to 0. */ + xTickCount = xConstTickCount; + + if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */ + { + taskSWITCH_DELAYED_LISTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* See if this tick has made a timeout expire. Tasks are stored in + the queue in the order of their wake time - meaning once one task + has been found whose block time has not expired there is no need to + look any further down the list. */ + if( xConstTickCount >= xNextTaskUnblockTime ) + { + for( ;; ) + { + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The delayed list is empty. Set xNextTaskUnblockTime + to the maximum possible value so it is extremely + unlikely that the + if( xTickCount >= xNextTaskUnblockTime ) test will pass + next time through. */ + xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + break; + } + else + { + /* The delayed list is not empty, get the value of the + item at the head of the delayed list. This is the time + at which the task at the head of the delayed list must + be removed from the Blocked state. */ + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) ); + + if( xConstTickCount < xItemValue ) + { + /* It is not time to unblock this item yet, but the + item value is the time at which the task at the head + of the blocked list must be removed from the Blocked + state - so record the item value in + xNextTaskUnblockTime. */ + xNextTaskUnblockTime = xItemValue; + break; /*lint !e9011 Code structure here is deedmed easier to understand with multiple breaks. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* It is time to remove the item from the Blocked state. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + + /* Is the task waiting on an event also? If so remove + it from the event list. */ + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + ( void ) uxListRemove( &( pxTCB->xEventListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Place the unblocked task into the appropriate ready + list. */ + prvAddTaskToReadyList( pxTCB ); + + /* A task being unblocked cannot cause an immediate + context switch if preemption is turned off. */ + #if ( configUSE_PREEMPTION == 1 ) + { + /* Preemption is on, but a context switch should + only be performed if the unblocked task has a + priority that is equal to or higher than the + currently executing task. */ + if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + } + } + + /* Tasks of equal priority to the currently running task will share + processing time (time slice) if preemption is on, and the application + writer has not explicitly turned time slicing off. */ + #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) + { + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */ + + #if ( configUSE_TICK_HOOK == 1 ) + { + /* Guard against the tick hook being called when the pended tick + count is being unwound (when the scheduler is being unlocked). */ + if( xPendedTicks == ( TickType_t ) 0 ) + { + vApplicationTickHook(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICK_HOOK */ + + #if ( configUSE_PREEMPTION == 1 ) + { + if( xYieldPending != pdFALSE ) + { + xSwitchRequired = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_PREEMPTION */ + } + else + { + ++xPendedTicks; + + /* The tick hook gets called at regular intervals, even if the + scheduler is locked. */ + #if ( configUSE_TICK_HOOK == 1 ) + { + vApplicationTickHook(); + } + #endif + } + + return xSwitchRequired; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) + { + TCB_t *xTCB; + + /* If xTask is NULL then it is the task hook of the calling task that is + getting set. */ + if( xTask == NULL ) + { + xTCB = ( TCB_t * ) pxCurrentTCB; + } + else + { + xTCB = xTask; + } + + /* Save the hook function in the TCB. A critical section is required as + the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xTCB->pxTaskTag = pxHookFunction; + } + taskEXIT_CRITICAL(); + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + TaskHookFunction_t xReturn; + + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + /* Save the hook function in the TCB. A critical section is required as + the value can be accessed from an interrupt. */ + taskENTER_CRITICAL(); + { + xReturn = pxTCB->pxTaskTag; + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + TaskHookFunction_t xReturn; + UBaseType_t uxSavedInterruptStatus; + + /* If xTask is NULL then set the calling task's hook. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + /* Save the hook function in the TCB. A critical section is required as + the value can be accessed from an interrupt. */ + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + xReturn = pxTCB->pxTaskTag; + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_APPLICATION_TASK_TAG == 1 ) + + BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) + { + TCB_t *xTCB; + BaseType_t xReturn; + + /* If xTask is NULL then we are calling our own task hook. */ + if( xTask == NULL ) + { + xTCB = pxCurrentTCB; + } + else + { + xTCB = xTask; + } + + if( xTCB->pxTaskTag != NULL ) + { + xReturn = xTCB->pxTaskTag( pvParameter ); + } + else + { + xReturn = pdFAIL; + } + + return xReturn; + } + +#endif /* configUSE_APPLICATION_TASK_TAG */ +/*-----------------------------------------------------------*/ + +void vTaskSwitchContext( void ) +{ + if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE ) + { + /* The scheduler is currently suspended - do not allow a context + switch. */ + xYieldPending = pdTRUE; + } + else + { + xYieldPending = pdFALSE; + traceTASK_SWITCHED_OUT(); + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE + portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime ); + #else + ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE(); + #endif + + /* Add the amount of time the task has been running to the + accumulated time so far. The time the task started running was + stored in ulTaskSwitchedInTime. Note that there is no overflow + protection here so count values are only valid until the timer + overflows. The guard against negative values is to protect + against suspect run time stat counter implementations - which + are provided by the application, not the kernel. */ + if( ulTotalRunTime > ulTaskSwitchedInTime ) + { + pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + ulTaskSwitchedInTime = ulTotalRunTime; + } + #endif /* configGENERATE_RUN_TIME_STATS */ + + /* Check for stack overflow, if configured. */ + taskCHECK_FOR_STACK_OVERFLOW(); + + /* Before the currently running task is switched out, save its errno. */ + #if( configUSE_POSIX_ERRNO == 1 ) + { + pxCurrentTCB->iTaskErrno = FreeRTOS_errno; + } + #endif + + /* Select a new task to run using either the generic C or port + optimised asm code. */ + taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + traceTASK_SWITCHED_IN(); + + /* After the new task is switched in, update the global errno. */ + #if( configUSE_POSIX_ERRNO == 1 ) + { + FreeRTOS_errno = pxCurrentTCB->iTaskErrno; + } + #endif + + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + /* Switch Newlib's _impure_ptr variable to point to the _reent + structure specific to this task. + See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + for additional information. */ + _impure_ptr = &( pxCurrentTCB->xNewLib_reent ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ + } +} +/*-----------------------------------------------------------*/ + +void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) +{ + configASSERT( pxEventList ); + + /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE + SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */ + + /* Place the event list item of the TCB in the appropriate event list. + This is placed in the list in priority order so the highest priority task + is the first to be woken by the event. The queue that contains the event + list is locked, preventing simultaneous access from interrupts. */ + vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); +} +/*-----------------------------------------------------------*/ + +void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) +{ + configASSERT( pxEventList ); + + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + the event groups implementation. */ + configASSERT( uxSchedulerSuspended != 0 ); + + /* Store the item value in the event list item. It is safe to access the + event list item here as interrupts won't access the event list item of a + task that is not in the Blocked state. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + + /* Place the event list item of the TCB at the end of the appropriate event + list. It is safe to access the event list here because it is part of an + event group implementation - and interrupts don't access event groups + directly (instead they access them indirectly by pending function calls to + the task level). */ + vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); +} +/*-----------------------------------------------------------*/ + +#if( configUSE_TIMERS == 1 ) + + void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely ) + { + configASSERT( pxEventList ); + + /* This function should not be called by application code hence the + 'Restricted' in its name. It is not part of the public API. It is + designed for use by kernel code, and has special calling requirements - + it should be called with the scheduler suspended. */ + + + /* Place the event list item of the TCB in the appropriate event list. + In this case it is assume that this is the only task that is going to + be waiting on this event list, so the faster vListInsertEnd() function + can be used in place of vListInsert. */ + vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) ); + + /* If the task should block indefinitely then set the block time to a + value that will be recognised as an indefinite delay inside the + prvAddCurrentTaskToDelayedList() function. */ + if( xWaitIndefinitely != pdFALSE ) + { + xTicksToWait = portMAX_DELAY; + } + + traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) ); + prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely ); + } + +#endif /* configUSE_TIMERS */ +/*-----------------------------------------------------------*/ + +BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) +{ +TCB_t *pxUnblockedTCB; +BaseType_t xReturn; + + /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be + called from a critical section within an ISR. */ + + /* The event list is sorted in priority order, so the first in the list can + be removed as it is known to be the highest priority. Remove the TCB from + the delayed list, and add it to the ready list. + + If an event is for a queue that is locked then this function will never + get called - the lock count on the queue will get modified instead. This + means exclusive access to the event list is guaranteed here. + + This function assumes that a check has already been made to ensure that + pxEventList is not empty. */ + pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + configASSERT( pxUnblockedTCB ); + ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) ); + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); + + #if( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked on a kernel object then xNextTaskUnblockTime + might be set to the blocked task's time out time. If the task is + unblocked for a reason other than a timeout xNextTaskUnblockTime is + normally left unchanged, because it is automatically reset to a new + value when the tick count equals xNextTaskUnblockTime. However if + tickless idling is used it might be more important to enter sleep mode + at the earliest possible time - so reset xNextTaskUnblockTime here to + ensure it is updated at the earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + } + else + { + /* The delayed and ready lists cannot be accessed, so hold this task + pending until the scheduler is resumed. */ + vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) ); + } + + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* Return true if the task removed from the event list has a higher + priority than the calling task. This allows the calling task to know if + it should force a context switch now. */ + xReturn = pdTRUE; + + /* Mark that a yield is pending in case the user is not using the + "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + xReturn = pdFALSE; + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue ) +{ +TCB_t *pxUnblockedTCB; + + /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by + the event flags implementation. */ + configASSERT( uxSchedulerSuspended != pdFALSE ); + + /* Store the new item value in the event list. */ + listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE ); + + /* Remove the event list form the event flag. Interrupts do not access + event flags. */ + pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + configASSERT( pxUnblockedTCB ); + ( void ) uxListRemove( pxEventListItem ); + + #if( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked on a kernel object then xNextTaskUnblockTime + might be set to the blocked task's time out time. If the task is + unblocked for a reason other than a timeout xNextTaskUnblockTime is + normally left unchanged, because it is automatically reset to a new + value when the tick count equals xNextTaskUnblockTime. However if + tickless idling is used it might be more important to enter sleep mode + at the earliest possible time - so reset xNextTaskUnblockTime here to + ensure it is updated at the earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + + /* Remove the task from the delayed list and add it to the ready list. The + scheduler is suspended so interrupts will not be accessing the ready + lists. */ + ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxUnblockedTCB ); + + if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The unblocked task has a priority above that of the calling task, so + a context switch is required. This function is called with the + scheduler suspended so xYieldPending is set so the context switch + occurs immediately that the scheduler is resumed (unsuspended). */ + xYieldPending = pdTRUE; + } +} +/*-----------------------------------------------------------*/ + +void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) +{ + configASSERT( pxTimeOut ); + taskENTER_CRITICAL(); + { + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut ) +{ + /* For internal use only as it does not use a critical section. */ + pxTimeOut->xOverflowCount = xNumOfOverflows; + pxTimeOut->xTimeOnEntering = xTickCount; +} +/*-----------------------------------------------------------*/ + +BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) +{ +BaseType_t xReturn; + + configASSERT( pxTimeOut ); + configASSERT( pxTicksToWait ); + + taskENTER_CRITICAL(); + { + /* Minor optimisation. The tick count cannot change in this block. */ + const TickType_t xConstTickCount = xTickCount; + const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering; + + #if( INCLUDE_xTaskAbortDelay == 1 ) + if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE ) + { + /* The delay was aborted, which is not the same as a time out, + but has the same result. */ + pxCurrentTCB->ucDelayAborted = pdFALSE; + xReturn = pdTRUE; + } + else + #endif + + #if ( INCLUDE_vTaskSuspend == 1 ) + if( *pxTicksToWait == portMAX_DELAY ) + { + /* If INCLUDE_vTaskSuspend is set to 1 and the block time + specified is the maximum block time then the task should block + indefinitely, and therefore never time out. */ + xReturn = pdFALSE; + } + else + #endif + + if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */ + { + /* The tick count is greater than the time at which + vTaskSetTimeout() was called, but has also overflowed since + vTaskSetTimeOut() was called. It must have wrapped all the way + around and gone past again. This passed since vTaskSetTimeout() + was called. */ + xReturn = pdTRUE; + } + else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */ + { + /* Not a genuine timeout. Adjust parameters for time remaining. */ + *pxTicksToWait -= xElapsedTime; + vTaskInternalSetTimeOutState( pxTimeOut ); + xReturn = pdFALSE; + } + else + { + *pxTicksToWait = 0; + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} +/*-----------------------------------------------------------*/ + +void vTaskMissedYield( void ) +{ + xYieldPending = pdTRUE; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) + { + UBaseType_t uxReturn; + TCB_t const *pxTCB; + + if( xTask != NULL ) + { + pxTCB = xTask; + uxReturn = pxTCB->uxTaskNumber; + } + else + { + uxReturn = 0U; + } + + return uxReturn; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) + { + TCB_t * pxTCB; + + if( xTask != NULL ) + { + pxTCB = xTask; + pxTCB->uxTaskNumber = uxHandle; + } + } + +#endif /* configUSE_TRACE_FACILITY */ + +/* + * ----------------------------------------------------------- + * The Idle task. + * ---------------------------------------------------------- + * + * The portTASK_FUNCTION() macro is used to allow port/compiler specific + * language extensions. The equivalent prototype for this function is: + * + * void prvIdleTask( void *pvParameters ); + * + */ +static portTASK_FUNCTION( prvIdleTask, pvParameters ) +{ + /* Stop warnings. */ + ( void ) pvParameters; + + /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE + SCHEDULER IS STARTED. **/ + + /* In case a task that has a secure context deletes itself, in which case + the idle task is responsible for deleting the task's secure context, if + any. */ + portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE ); + + for( ;; ) + { + /* See if any tasks have deleted themselves - if so then the idle task + is responsible for freeing the deleted task's TCB and stack. */ + prvCheckTasksWaitingTermination(); + + #if ( configUSE_PREEMPTION == 0 ) + { + /* If we are not using preemption we keep forcing a task switch to + see if any other task has become available. If we are using + preemption we don't need to do this as any task becoming available + will automatically get the processor anyway. */ + taskYIELD(); + } + #endif /* configUSE_PREEMPTION */ + + #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) + { + /* When using preemption tasks of equal priority will be + timesliced. If a task that is sharing the idle priority is ready + to run then the idle task should yield before the end of the + timeslice. + + A critical region is not required here as we are just reading from + the list, and an occasional incorrect value will not matter. If + the ready list at the idle priority contains more than one task + then a task other than the idle task is ready to execute. */ + if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 ) + { + taskYIELD(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */ + + #if ( configUSE_IDLE_HOOK == 1 ) + { + extern void vApplicationIdleHook( void ); + + /* Call the user defined function from within the idle task. This + allows the application designer to add background functionality + without the overhead of a separate task. + NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES, + CALL A FUNCTION THAT MIGHT BLOCK. */ + vApplicationIdleHook(); + } + #endif /* configUSE_IDLE_HOOK */ + + /* This conditional compilation should use inequality to 0, not equality + to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when + user defined low power mode implementations require + configUSE_TICKLESS_IDLE to be set to a value other than 1. */ + #if ( configUSE_TICKLESS_IDLE != 0 ) + { + TickType_t xExpectedIdleTime; + + /* It is not desirable to suspend then resume the scheduler on + each iteration of the idle task. Therefore, a preliminary + test of the expected idle time is performed without the + scheduler suspended. The result here is not necessarily + valid. */ + xExpectedIdleTime = prvGetExpectedIdleTime(); + + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + vTaskSuspendAll(); + { + /* Now the scheduler is suspended, the expected idle + time can be sampled again, and this time its value can + be used. */ + configASSERT( xNextTaskUnblockTime >= xTickCount ); + xExpectedIdleTime = prvGetExpectedIdleTime(); + + /* Define the following macro to set xExpectedIdleTime to 0 + if the application does not want + portSUPPRESS_TICKS_AND_SLEEP() to be called. */ + configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime ); + + if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP ) + { + traceLOW_POWER_IDLE_BEGIN(); + portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ); + traceLOW_POWER_IDLE_END(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + ( void ) xTaskResumeAll(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configUSE_TICKLESS_IDLE */ + } +} +/*-----------------------------------------------------------*/ + +#if( configUSE_TICKLESS_IDLE != 0 ) + + eSleepModeStatus eTaskConfirmSleepModeStatus( void ) + { + /* The idle task exists in addition to the application tasks. */ + const UBaseType_t uxNonApplicationTasks = 1; + eSleepModeStatus eReturn = eStandardSleep; + + /* This function must be called from a critical section. */ + + if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 ) + { + /* A task was made ready while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else if( xYieldPending != pdFALSE ) + { + /* A yield was pended while the scheduler was suspended. */ + eReturn = eAbortSleep; + } + else + { + /* If all the tasks are in the suspended list (which might mean they + have an infinite block time rather than actually being suspended) + then it is safe to turn all clocks off and just wait for external + interrupts. */ + if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) ) + { + eReturn = eNoTasksWaitingTimeout; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + return eReturn; + } + +#endif /* configUSE_TICKLESS_IDLE */ +/*-----------------------------------------------------------*/ + +#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + + void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue ) + { + TCB_t *pxTCB; + + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToSet ); + configASSERT( pxTCB != NULL ); + pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue; + } + } + +#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ +/*-----------------------------------------------------------*/ + +#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 ) + + void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex ) + { + void *pvReturn = NULL; + TCB_t *pxTCB; + + if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS ) + { + pxTCB = prvGetTCBFromHandle( xTaskToQuery ); + pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ]; + } + else + { + pvReturn = NULL; + } + + return pvReturn; + } + +#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */ +/*-----------------------------------------------------------*/ + +#if ( portUSING_MPU_WRAPPERS == 1 ) + + void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, const MemoryRegion_t * const xRegions ) + { + TCB_t *pxTCB; + + /* If null is passed in here then we are modifying the MPU settings of + the calling task. */ + pxTCB = prvGetTCBFromHandle( xTaskToModify ); + + vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 ); + } + +#endif /* portUSING_MPU_WRAPPERS */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseTaskLists( void ) +{ +UBaseType_t uxPriority; + + for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ ) + { + vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) ); + } + + vListInitialise( &xDelayedTaskList1 ); + vListInitialise( &xDelayedTaskList2 ); + vListInitialise( &xPendingReadyList ); + + #if ( INCLUDE_vTaskDelete == 1 ) + { + vListInitialise( &xTasksWaitingTermination ); + } + #endif /* INCLUDE_vTaskDelete */ + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + vListInitialise( &xSuspendedTaskList ); + } + #endif /* INCLUDE_vTaskSuspend */ + + /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList + using list2. */ + pxDelayedTaskList = &xDelayedTaskList1; + pxOverflowDelayedTaskList = &xDelayedTaskList2; +} +/*-----------------------------------------------------------*/ + +static void prvCheckTasksWaitingTermination( void ) +{ + + /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/ + + #if ( INCLUDE_vTaskDelete == 1 ) + { + TCB_t *pxTCB; + + /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL() + being called too often in the idle task. */ + while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U ) + { + taskENTER_CRITICAL(); + { + pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + --uxCurrentNumberOfTasks; + --uxDeletedTasksWaitingCleanUp; + } + taskEXIT_CRITICAL(); + + prvDeleteTCB( pxTCB ); + } + } + #endif /* INCLUDE_vTaskDelete */ +} +/*-----------------------------------------------------------*/ + +#if( configUSE_TRACE_FACILITY == 1 ) + + void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState ) + { + TCB_t *pxTCB; + + /* xTask is NULL then get the state of the calling task. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB; + pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName [ 0 ] ); + pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority; + pxTaskStatus->pxStackBase = pxTCB->pxStack; + pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber; + + #if ( configUSE_MUTEXES == 1 ) + { + pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; + } + #else + { + pxTaskStatus->uxBasePriority = 0; + } + #endif + + #if ( configGENERATE_RUN_TIME_STATS == 1 ) + { + pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; + } + #else + { + pxTaskStatus->ulRunTimeCounter = 0; + } + #endif + + /* Obtaining the task state is a little fiddly, so is only done if the + value of eState passed into this function is eInvalid - otherwise the + state is just set to whatever is passed in. */ + if( eState != eInvalid ) + { + if( pxTCB == pxCurrentTCB ) + { + pxTaskStatus->eCurrentState = eRunning; + } + else + { + pxTaskStatus->eCurrentState = eState; + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + /* If the task is in the suspended list then there is a + chance it is actually just blocked indefinitely - so really + it should be reported as being in the Blocked state. */ + if( eState == eSuspended ) + { + vTaskSuspendAll(); + { + if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL ) + { + pxTaskStatus->eCurrentState = eBlocked; + } + } + ( void ) xTaskResumeAll(); + } + } + #endif /* INCLUDE_vTaskSuspend */ + } + } + else + { + pxTaskStatus->eCurrentState = eTaskGetState( pxTCB ); + } + + /* Obtaining the stack space takes some time, so the xGetFreeStackSpace + parameter is provided to allow it to be skipped. */ + if( xGetFreeStackSpace != pdFALSE ) + { + #if ( portSTACK_GROWTH > 0 ) + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack ); + } + #else + { + pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack ); + } + #endif + } + else + { + pxTaskStatus->usStackHighWaterMark = 0; + } + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) + { + configLIST_VOLATILE TCB_t *pxNextTCB, *pxFirstTCB; + UBaseType_t uxTask = 0; + + if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 ) + { + listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + + /* Populate an TaskStatus_t structure within the + pxTaskStatusArray array for each task that is referenced from + pxList. See the definition of TaskStatus_t in task.h for the + meaning of each TaskStatus_t structure member. */ + do + { + listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState ); + uxTask++; + } while( pxNextTCB != pxFirstTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return uxTask; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) + + static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) + { + uint32_t ulCount = 0U; + + while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE ) + { + pucStackByte -= portSTACK_GROWTH; + ulCount++; + } + + ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */ + + return ( configSTACK_DEPTH_TYPE ) ulCount; + } + +#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) + + /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the + same except for their return type. Using configSTACK_DEPTH_TYPE allows the + user to determine the return type. It gets around the problem of the value + overflowing on 8-bit types without breaking backward compatibility for + applications that expect an 8-bit return type. */ + configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + uint8_t *pucEndOfStack; + configSTACK_DEPTH_TYPE uxReturn; + + /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are + the same except for their return type. Using configSTACK_DEPTH_TYPE + allows the user to determine the return type. It gets around the + problem of the value overflowing on 8-bit types without breaking + backward compatibility for applications that expect an 8-bit return + type. */ + + pxTCB = prvGetTCBFromHandle( xTask ); + + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif + + uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) + + UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + uint8_t *pucEndOfStack; + UBaseType_t uxReturn; + + pxTCB = prvGetTCBFromHandle( xTask ); + + #if portSTACK_GROWTH < 0 + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxStack; + } + #else + { + pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack; + } + #endif + + uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack ); + + return uxReturn; + } + +#endif /* INCLUDE_uxTaskGetStackHighWaterMark */ +/*-----------------------------------------------------------*/ + +#if ( INCLUDE_vTaskDelete == 1 ) + + static void prvDeleteTCB( TCB_t *pxTCB ) + { + /* This call is required specifically for the TriCore port. It must be + above the vPortFree() calls. The call is also used by ports/demos that + want to allocate and clean RAM statically. */ + portCLEAN_UP_TCB( pxTCB ); + + /* Free up the memory allocated by the scheduler for the task. It is up + to the task to free any memory allocated at the application level. + See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html + for additional information. */ + #if ( configUSE_NEWLIB_REENTRANT == 1 ) + { + _reclaim_reent( &( pxTCB->xNewLib_reent ) ); + } + #endif /* configUSE_NEWLIB_REENTRANT */ + + #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) ) + { + /* The task can only have been allocated dynamically - free both + the stack and TCB. */ + vPortFree( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + #elif( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */ + { + /* The task could have been allocated statically or dynamically, so + check what was statically allocated before trying to free the + memory. */ + if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ) + { + /* Both the stack and TCB were allocated dynamically, so both + must be freed. */ + vPortFree( pxTCB->pxStack ); + vPortFree( pxTCB ); + } + else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY ) + { + /* Only the stack was statically allocated, so the TCB is the + only memory that must be freed. */ + vPortFree( pxTCB ); + } + else + { + /* Neither the stack nor the TCB were allocated dynamically, so + nothing needs to be freed. */ + configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB ); + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + } + +#endif /* INCLUDE_vTaskDelete */ +/*-----------------------------------------------------------*/ + +static void prvResetNextTaskUnblockTime( void ) +{ +TCB_t *pxTCB; + + if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE ) + { + /* The new current delayed list is empty. Set xNextTaskUnblockTime to + the maximum possible value so it is extremely unlikely that the + if( xTickCount >= xNextTaskUnblockTime ) test will pass until + there is an item in the delayed list. */ + xNextTaskUnblockTime = portMAX_DELAY; + } + else + { + /* The new current delayed list is not empty, get the value of + the item at the head of the delayed list. This is the time at + which the task at the head of the delayed list should be removed + from the Blocked state. */ + ( pxTCB ) = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) ); + } +} +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) + + TaskHandle_t xTaskGetCurrentTaskHandle( void ) + { + TaskHandle_t xReturn; + + /* A critical section is not required as this is not called from + an interrupt and the current TCB will always be the same for any + individual execution thread. */ + xReturn = pxCurrentTCB; + + return xReturn; + } + +#endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) + + BaseType_t xTaskGetSchedulerState( void ) + { + BaseType_t xReturn; + + if( xSchedulerRunning == pdFALSE ) + { + xReturn = taskSCHEDULER_NOT_STARTED; + } + else + { + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + xReturn = taskSCHEDULER_RUNNING; + } + else + { + xReturn = taskSCHEDULER_SUSPENDED; + } + } + + return xReturn; + } + +#endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxMutexHolderTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; + + /* If the mutex was given back by an interrupt while the queue was + locked then the mutex holder might now be NULL. _RB_ Is this still + needed as interrupts can no longer use mutexes? */ + if( pxMutexHolder != NULL ) + { + /* If the holder of the mutex has a priority below the priority of + the task attempting to obtain the mutex then it will temporarily + inherit the priority of the task attempting to obtain the mutex. */ + if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority ) + { + /* Adjust the mutex holder state to account for its new + priority. Only reset the event list item value if the value is + not being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the task being modified is in the ready state it will need + to be moved into a new list. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + there is no need to check again and the port level + reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Inherit the priority before being moved into the new list. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + prvAddTaskToReadyList( pxMutexHolderTCB ); + } + else + { + /* Just inherit the priority. */ + pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority; + } + + traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority ); + + /* Inheritance occurred. */ + xReturn = pdTRUE; + } + else + { + if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority ) + { + /* The base priority of the mutex holder is lower than the + priority of the task attempting to take the mutex, but the + current priority of the mutex holder is not lower than the + priority of the task attempting to take the mutex. + Therefore the mutex holder must have already inherited a + priority, but inheritance would have occurred if that had + not been the case. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) + { + TCB_t * const pxTCB = pxMutexHolder; + BaseType_t xReturn = pdFALSE; + + if( pxMutexHolder != NULL ) + { + /* A task can only have an inherited priority if it holds the mutex. + If the mutex is held by a task then it cannot be given from an + interrupt, and if a mutex is given by the holding task then it must + be the running state task. */ + configASSERT( pxTCB == pxCurrentTCB ); + configASSERT( pxTCB->uxMutexesHeld ); + ( pxTCB->uxMutexesHeld )--; + + /* Has the holder of the mutex inherited the priority of another + task? */ + if( pxTCB->uxPriority != pxTCB->uxBasePriority ) + { + /* Only disinherit if no other mutexes are held. */ + if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 ) + { + /* A task can only have an inherited priority if it holds + the mutex. If the mutex is held by a task then it cannot be + given from an interrupt, and if a mutex is given by the + holding task then it must be the running state task. Remove + the holding task from the ready/delayed list. */ + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + taskRESET_READY_PRIORITY( pxTCB->uxPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Disinherit the priority before adding the task into the + new ready list. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); + pxTCB->uxPriority = pxTCB->uxBasePriority; + + /* Reset the event list item value. It cannot be in use for + any other purpose if this task is running, and it must be + running to give back the mutex. */ + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + prvAddTaskToReadyList( pxTCB ); + + /* Return true to indicate that a context switch is required. + This is only actually required in the corner case whereby + multiple mutexes were held and the mutexes were given back + in an order different to that in which they were taken. + If a context switch did not occur when the first mutex was + returned, even if a task was waiting on it, then a context + switch should occur when the last mutex is returned whether + a task is waiting on it or not. */ + xReturn = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask ) + { + TCB_t * const pxTCB = pxMutexHolder; + UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse; + const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1; + + if( pxMutexHolder != NULL ) + { + /* If pxMutexHolder is not NULL then the holder must hold at least + one mutex. */ + configASSERT( pxTCB->uxMutexesHeld ); + + /* Determine the priority to which the priority of the task that + holds the mutex should be set. This will be the greater of the + holding task's base priority and the priority of the highest + priority task that is waiting to obtain the mutex. */ + if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask ) + { + uxPriorityToUse = uxHighestPriorityWaitingTask; + } + else + { + uxPriorityToUse = pxTCB->uxBasePriority; + } + + /* Does the priority need to change? */ + if( pxTCB->uxPriority != uxPriorityToUse ) + { + /* Only disinherit if no other mutexes are held. This is a + simplification in the priority inheritance implementation. If + the task that holds the mutex is also holding other mutexes then + the other mutexes may have caused the priority inheritance. */ + if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld ) + { + /* If a task has timed out because it already holds the + mutex it was trying to obtain then it cannot of inherited + its own priority. */ + configASSERT( pxTCB != pxCurrentTCB ); + + /* Disinherit the priority, remembering the previous + priority to facilitate determining the subject task's + state. */ + traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority ); + uxPriorityUsedOnEntry = pxTCB->uxPriority; + pxTCB->uxPriority = uxPriorityToUse; + + /* Only reset the event list item value if the value is not + being used for anything else. */ + if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL ) + { + listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* If the running task is not the task that holds the mutex + then the task that holds the mutex could be in either the + Ready, Blocked or Suspended states. Only remove the task + from its current state list if it is in the Ready state as + the task's priority is going to change and there is one + Ready list per priority. */ + if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE ) + { + if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* It is known that the task is in its ready list so + there is no need to check again and the port level + reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + prvAddTaskToReadyList( pxTCB ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if ( portCRITICAL_NESTING_IN_TCB == 1 ) + + void vTaskEnterCritical( void ) + { + portDISABLE_INTERRUPTS(); + + if( xSchedulerRunning != pdFALSE ) + { + ( pxCurrentTCB->uxCriticalNesting )++; + + /* This is not the interrupt safe version of the enter critical + function so assert() if it is being called from an interrupt + context. Only API functions that end in "FromISR" can be used in an + interrupt. Only assert if the critical nesting count is 1 to + protect against recursive calls if the assert function also uses a + critical section. */ + if( pxCurrentTCB->uxCriticalNesting == 1 ) + { + portASSERT_IF_IN_ISR(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* portCRITICAL_NESTING_IN_TCB */ +/*-----------------------------------------------------------*/ + +#if ( portCRITICAL_NESTING_IN_TCB == 1 ) + + void vTaskExitCritical( void ) + { + if( xSchedulerRunning != pdFALSE ) + { + if( pxCurrentTCB->uxCriticalNesting > 0U ) + { + ( pxCurrentTCB->uxCriticalNesting )--; + + if( pxCurrentTCB->uxCriticalNesting == 0U ) + { + portENABLE_INTERRUPTS(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* portCRITICAL_NESTING_IN_TCB */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) + + static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) + { + size_t x; + + /* Start by copying the entire string. */ + strcpy( pcBuffer, pcTaskName ); + + /* Pad the end of the string with spaces to ensure columns line up when + printed out. */ + for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ ) + { + pcBuffer[ x ] = ' '; + } + + /* Terminate. */ + pcBuffer[ x ] = ( char ) 0x00; + + /* Return the new end of string. */ + return &( pcBuffer[ x ] ); + } + +#endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */ +/*-----------------------------------------------------------*/ + +#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + void vTaskList( char * pcWriteBuffer ) + { + TaskStatus_t *pxTaskStatusArray; + UBaseType_t uxArraySize, x; + char cStatus; + + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskList() calls uxTaskGetSystemState(), then formats part of the + * uxTaskGetSystemState() output into a human readable table that + * displays task names, states and stack usage. + * + * vTaskList() has a dependency on the sprintf() C library function that + * might bloat the code size, use a lot of stack, and provide different + * results on different platforms. An alternative, tiny, third party, + * and limited functionality implementation of sprintf() is provided in + * many of the FreeRTOS/Demo sub-directories in a file called + * printf-stdarg.c (note printf-stdarg.c does not provide a full + * snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskList(). + */ + + + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; + + /* Take a snapshot of the number of tasks in case it changes while this + function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; + + /* Allocate an array index for each task. NOTE! if + configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + equate to NULL. */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ + + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL ); + + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + switch( pxTaskStatusArray[ x ].eCurrentState ) + { + case eRunning: cStatus = tskRUNNING_CHAR; + break; + + case eReady: cStatus = tskREADY_CHAR; + break; + + case eBlocked: cStatus = tskBLOCKED_CHAR; + break; + + case eSuspended: cStatus = tskSUSPENDED_CHAR; + break; + + case eDeleted: cStatus = tskDELETED_CHAR; + break; + + case eInvalid: /* Fall through. */ + default: /* Should not get here, but it is included + to prevent static checking errors. */ + cStatus = ( char ) 0x00; + break; + } + + /* Write the task name to the string, padding with spaces so it + can be printed in tabular form more easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + + /* Write the rest of the string. */ + sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ + } + + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */ +/*----------------------------------------------------------*/ + +#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) + + void vTaskGetRunTimeStats( char *pcWriteBuffer ) + { + TaskStatus_t *pxTaskStatusArray; + UBaseType_t uxArraySize, x; + uint32_t ulTotalTime, ulStatsAsPercentage; + + #if( configUSE_TRACE_FACILITY != 1 ) + { + #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats(). + } + #endif + + /* + * PLEASE NOTE: + * + * This function is provided for convenience only, and is used by many + * of the demo applications. Do not consider it to be part of the + * scheduler. + * + * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part + * of the uxTaskGetSystemState() output into a human readable table that + * displays the amount of time each task has spent in the Running state + * in both absolute and percentage terms. + * + * vTaskGetRunTimeStats() has a dependency on the sprintf() C library + * function that might bloat the code size, use a lot of stack, and + * provide different results on different platforms. An alternative, + * tiny, third party, and limited functionality implementation of + * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in + * a file called printf-stdarg.c (note printf-stdarg.c does not provide + * a full snprintf() implementation!). + * + * It is recommended that production systems call uxTaskGetSystemState() + * directly to get access to raw stats data, rather than indirectly + * through a call to vTaskGetRunTimeStats(). + */ + + /* Make sure the write buffer does not contain a string. */ + *pcWriteBuffer = ( char ) 0x00; + + /* Take a snapshot of the number of tasks in case it changes while this + function is executing. */ + uxArraySize = uxCurrentNumberOfTasks; + + /* Allocate an array index for each task. NOTE! If + configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will + equate to NULL. */ + pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */ + + if( pxTaskStatusArray != NULL ) + { + /* Generate the (binary) data. */ + uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime ); + + /* For percentage calculations. */ + ulTotalTime /= 100UL; + + /* Avoid divide by zero errors. */ + if( ulTotalTime > 0UL ) + { + /* Create a human readable table from the binary data. */ + for( x = 0; x < uxArraySize; x++ ) + { + /* What percentage of the total run time has the task used? + This will always be rounded down to the nearest integer. + ulTotalRunTimeDiv100 has already been divided by 100. */ + ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime; + + /* Write the task name to the string, padding with + spaces so it can be printed in tabular form more + easily. */ + pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName ); + + if( ulStatsAsPercentage > 0UL ) + { + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage ); + } + #else + { + /* sizeof( int ) == sizeof( long ) so a smaller + printf() library can be used. */ + sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + } + #endif + } + else + { + /* If the percentage is zero here then the task has + consumed less than 1% of the total run time. */ + #ifdef portLU_PRINTF_SPECIFIER_REQUIRED + { + sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter ); + } + #else + { + /* sizeof( int ) == sizeof( long ) so a smaller + printf() library can be used. */ + sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */ + } + #endif + } + + pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */ + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION + is 0 then vPortFree() will be #defined to nothing. */ + vPortFree( pxTaskStatusArray ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + +#endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */ +/*-----------------------------------------------------------*/ + +TickType_t uxTaskResetEventItemValue( void ) +{ +TickType_t uxReturn; + + uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) ); + + /* Reset the event list item to its normal value - so it can be used with + queues and semaphores. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +#if ( configUSE_MUTEXES == 1 ) + + TaskHandle_t pvTaskIncrementMutexHeldCount( void ) + { + /* If xSemaphoreCreateMutex() is called before any tasks have been created + then pxCurrentTCB will be NULL. */ + if( pxCurrentTCB != NULL ) + { + ( pxCurrentTCB->uxMutexesHeld )++; + } + + return pxCurrentTCB; + } + +#endif /* configUSE_MUTEXES */ +/*-----------------------------------------------------------*/ + +#if( configUSE_TASK_NOTIFICATIONS == 1 ) + + uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait ) + { + uint32_t ulReturn; + + taskENTER_CRITICAL(); + { + /* Only block if the notification count is not already non-zero. */ + if( pxCurrentTCB->ulNotifiedValue == 0UL ) + { + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; + + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_TAKE_BLOCK(); + + /* All ports are written to allow a yield in a critical + section (some will yield immediately, others wait until the + critical section exits) - but it is not something that + application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_TAKE(); + ulReturn = pxCurrentTCB->ulNotifiedValue; + + if( ulReturn != 0UL ) + { + if( xClearCountOnExit != pdFALSE ) + { + pxCurrentTCB->ulNotifiedValue = 0UL; + } + else + { + pxCurrentTCB->ulNotifiedValue = ulReturn - ( uint32_t ) 1; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); + + return ulReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait ) + { + BaseType_t xReturn; + + taskENTER_CRITICAL(); + { + /* Only block if a notification is not already pending. */ + if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) + { + /* Clear bits in the task's notification value as bits may get + set by the notifying task or interrupt. This can be used to + clear the value to zero. */ + pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry; + + /* Mark this task as waiting for a notification. */ + pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION; + + if( xTicksToWait > ( TickType_t ) 0 ) + { + prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE ); + traceTASK_NOTIFY_WAIT_BLOCK(); + + /* All ports are written to allow a yield in a critical + section (some will yield immediately, others wait until the + critical section exits) - but it is not something that + application code should ever do. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + taskENTER_CRITICAL(); + { + traceTASK_NOTIFY_WAIT(); + + if( pulNotificationValue != NULL ) + { + /* Output the current notification value, which may or may not + have changed. */ + *pulNotificationValue = pxCurrentTCB->ulNotifiedValue; + } + + /* If ucNotifyValue is set then either the task never entered the + blocked state (because a notification was already pending) or the + task unblocked because of a notification. Otherwise the task + unblocked because of a timeout. */ + if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED ) + { + /* A notification was not received. */ + xReturn = pdFALSE; + } + else + { + /* A notification was already pending or a notification was + received while the task was waiting. */ + pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit; + xReturn = pdTRUE; + } + + pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue ) + { + TCB_t * pxTCB; + BaseType_t xReturn = pdPASS; + uint8_t ucOriginalNotifyState; + + configASSERT( xTaskToNotify ); + pxTCB = xTaskToNotify; + + taskENTER_CRITICAL(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; + } + + ucOriginalNotifyState = pxTCB->ucNotifyState; + + pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; + + switch( eAction ) + { + case eSetBits : + pxTCB->ulNotifiedValue |= ulValue; + break; + + case eIncrement : + ( pxTCB->ulNotifiedValue )++; + break; + + case eSetValueWithOverwrite : + pxTCB->ulNotifiedValue = ulValue; + break; + + case eSetValueWithoutOverwrite : + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + break; + + case eNoAction: + /* The task is being notified without its notify value being + updated. */ + break; + + default: + /* Should not get here if all enums are handled. + Artificially force an assert by testing a value the + compiler can't assume is const. */ + configASSERT( pxTCB->ulNotifiedValue == ~0UL ); + + break; + } + + traceTASK_NOTIFY(); + + /* If the task is in the blocked state specifically to wait for a + notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + #if( configUSE_TICKLESS_IDLE != 0 ) + { + /* If a task is blocked waiting for a notification then + xNextTaskUnblockTime might be set to the blocked task's time + out time. If the task is unblocked for a reason other than + a timeout xNextTaskUnblockTime is normally left unchanged, + because it will automatically get reset to a new value when + the tick count equals xNextTaskUnblockTime. However if + tickless idling is used it might be more important to enter + sleep mode at the earliest possible time - so reset + xNextTaskUnblockTime here to ensure it is updated at the + earliest possible time. */ + prvResetNextTaskUnblockTime(); + } + #endif + + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + executing task so a yield is required. */ + taskYIELD_IF_USING_PREEMPTION(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + BaseType_t xReturn = pdPASS; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( xTaskToNotify ); + + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + pxTCB = xTaskToNotify; + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + if( pulPreviousNotificationValue != NULL ) + { + *pulPreviousNotificationValue = pxTCB->ulNotifiedValue; + } + + ucOriginalNotifyState = pxTCB->ucNotifyState; + pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; + + switch( eAction ) + { + case eSetBits : + pxTCB->ulNotifiedValue |= ulValue; + break; + + case eIncrement : + ( pxTCB->ulNotifiedValue )++; + break; + + case eSetValueWithOverwrite : + pxTCB->ulNotifiedValue = ulValue; + break; + + case eSetValueWithoutOverwrite : + if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED ) + { + pxTCB->ulNotifiedValue = ulValue; + } + else + { + /* The value could not be written to the task. */ + xReturn = pdFAIL; + } + break; + + case eNoAction : + /* The task is being notified without its notify value being + updated. */ + break; + + default: + /* Should not get here if all enums are handled. + Artificially force an assert by testing a value the + compiler can't assume is const. */ + configASSERT( pxTCB->ulNotifiedValue == ~0UL ); + break; + } + + traceTASK_NOTIFY_FROM_ISR(); + + /* If the task is in the blocked state specifically to wait for a + notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + this task pending until the scheduler is resumed. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + + /* Mark that a yield is pending in case the user is not + using the "xHigherPriorityTaskWoken" parameter to an ISR + safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if( configUSE_TASK_NOTIFICATIONS == 1 ) + + void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken ) + { + TCB_t * pxTCB; + uint8_t ucOriginalNotifyState; + UBaseType_t uxSavedInterruptStatus; + + configASSERT( xTaskToNotify ); + + /* RTOS ports that support interrupt nesting have the concept of a + maximum system call (or maximum API call) interrupt priority. + Interrupts that are above the maximum system call priority are keep + permanently enabled, even when the RTOS kernel is in a critical section, + but cannot make any calls to FreeRTOS API functions. If configASSERT() + is defined in FreeRTOSConfig.h then + portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion + failure if a FreeRTOS API function is called from an interrupt that has + been assigned a priority above the configured maximum system call + priority. Only FreeRTOS functions that end in FromISR can be called + from interrupts that have been assigned a priority at or (logically) + below the maximum system call interrupt priority. FreeRTOS maintains a + separate interrupt safe API to ensure interrupt entry is as fast and as + simple as possible. More information (albeit Cortex-M specific) is + provided on the following link: + http://www.freertos.org/RTOS-Cortex-M3-M4.html */ + portASSERT_IF_INTERRUPT_PRIORITY_INVALID(); + + pxTCB = xTaskToNotify; + + uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR(); + { + ucOriginalNotifyState = pxTCB->ucNotifyState; + pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED; + + /* 'Giving' is equivalent to incrementing a count in a counting + semaphore. */ + ( pxTCB->ulNotifiedValue )++; + + traceTASK_NOTIFY_GIVE_FROM_ISR(); + + /* If the task is in the blocked state specifically to wait for a + notification then unblock it now. */ + if( ucOriginalNotifyState == taskWAITING_NOTIFICATION ) + { + /* The task should not have been on an event list. */ + configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL ); + + if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE ) + { + ( void ) uxListRemove( &( pxTCB->xStateListItem ) ); + prvAddTaskToReadyList( pxTCB ); + } + else + { + /* The delayed and ready lists cannot be accessed, so hold + this task pending until the scheduler is resumed. */ + vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) ); + } + + if( pxTCB->uxPriority > pxCurrentTCB->uxPriority ) + { + /* The notified task has a priority above the currently + executing task so a yield is required. */ + if( pxHigherPriorityTaskWoken != NULL ) + { + *pxHigherPriorityTaskWoken = pdTRUE; + } + + /* Mark that a yield is pending in case the user is not + using the "xHigherPriorityTaskWoken" parameter in an ISR + safe FreeRTOS function. */ + xYieldPending = pdTRUE; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus ); + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if( configUSE_TASK_NOTIFICATIONS == 1 ) + + BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask ) + { + TCB_t *pxTCB; + BaseType_t xReturn; + + /* If null is passed in here then it is the calling task that is having + its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + taskENTER_CRITICAL(); + { + if( pxTCB->ucNotifyState == taskNOTIFICATION_RECEIVED ) + { + pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION; + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + taskEXIT_CRITICAL(); + + return xReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if( configUSE_TASK_NOTIFICATIONS == 1 ) + + uint32_t ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear ) + { + TCB_t *pxTCB; + uint32_t ulReturn; + + /* If null is passed in here then it is the calling task that is having + its notification state cleared. */ + pxTCB = prvGetTCBFromHandle( xTask ); + + taskENTER_CRITICAL(); + { + /* Return the notification as it was before the bits were cleared, + then clear the bit mask. */ + ulReturn = pxCurrentTCB->ulNotifiedValue; + pxTCB->ulNotifiedValue &= ~ulBitsToClear; + } + taskEXIT_CRITICAL(); + + return ulReturn; + } + +#endif /* configUSE_TASK_NOTIFICATIONS */ +/*-----------------------------------------------------------*/ + +#if( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) ) + + uint32_t ulTaskGetIdleRunTimeCounter( void ) + { + return xIdleTaskHandle->ulRunTimeCounter; + } + +#endif +/*-----------------------------------------------------------*/ + +static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseType_t xCanBlockIndefinitely ) +{ +TickType_t xTimeToWake; +const TickType_t xConstTickCount = xTickCount; + + #if( INCLUDE_xTaskAbortDelay == 1 ) + { + /* About to enter a delayed list, so ensure the ucDelayAborted flag is + reset to pdFALSE so it can be detected as having been set to pdTRUE + when the task leaves the Blocked state. */ + pxCurrentTCB->ucDelayAborted = pdFALSE; + } + #endif + + /* Remove the task from the ready list before adding it to the blocked list + as the same list item is used for both lists. */ + if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 ) + { + /* The current task must be in a ready list, so there is no need to + check, and the port reset macro can be called directly. */ + portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority cannot change as called with scheduler suspended or in a critical section. */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + #if ( INCLUDE_vTaskSuspend == 1 ) + { + if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) ) + { + /* Add the task to the suspended task list instead of a delayed task + list to ensure it is not woken by a timing event. It will block + indefinitely. */ + vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* Calculate the time at which the task should be woken if the event + does not occur. This may overflow but this doesn't matter, the + kernel will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; + + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + + if( xTimeToWake < xConstTickCount ) + { + /* Wake time has overflowed. Place this item in the overflow + list. */ + vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* The wake time has not overflowed, so the current block list + is used. */ + vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + + /* If the task entering the blocked state was placed at the + head of the list of blocked tasks then xNextTaskUnblockTime + needs to be updated too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + } + #else /* INCLUDE_vTaskSuspend */ + { + /* Calculate the time at which the task should be woken if the event + does not occur. This may overflow but this doesn't matter, the kernel + will manage it correctly. */ + xTimeToWake = xConstTickCount + xTicksToWait; + + /* The list item will be inserted in wake time order. */ + listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake ); + + if( xTimeToWake < xConstTickCount ) + { + /* Wake time has overflowed. Place this item in the overflow list. */ + vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + } + else + { + /* The wake time has not overflowed, so the current block list is used. */ + vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) ); + + /* If the task entering the blocked state was placed at the head of the + list of blocked tasks then xNextTaskUnblockTime needs to be updated + too. */ + if( xTimeToWake < xNextTaskUnblockTime ) + { + xNextTaskUnblockTime = xTimeToWake; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */ + ( void ) xCanBlockIndefinitely; + } + #endif /* INCLUDE_vTaskSuspend */ +} + +/* Code below here allows additional code to be inserted into this source file, +especially where access to file scope functions and data is needed (for example +when performing module tests). */ + +#ifdef FREERTOS_MODULE_TEST + #include "tasks_test_access_functions.h" +#endif + + +#if( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 ) + + #include "freertos_tasks_c_additions.h" + + #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT + static void freertos_tasks_c_additions_init( void ) + { + FREERTOS_TASKS_C_ADDITIONS_INIT(); + } + #endif + +#endif + + diff --git a/Middlewares/Third_Party/FreeRTOS/Source/timers.c b/Middlewares/Third_Party/FreeRTOS/Source/timers.c new file mode 100644 index 0000000..00200b8 --- /dev/null +++ b/Middlewares/Third_Party/FreeRTOS/Source/timers.c @@ -0,0 +1,1127 @@ +/* + * FreeRTOS Kernel V10.3.1 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* Standard includes. */ +#include + +/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining +all the API functions to use the MPU wrappers. That should only be done when +task.h is included from an application file. */ +#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "timers.h" + +#if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 ) + #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available. +#endif + +/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified +because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined +for the header files above, but not in this file, in order to generate the +correct privileged Vs unprivileged linkage and placement. */ +#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e9021 !e961 !e750. */ + + +/* This entire source file will be skipped if the application is not configured +to include software timer functionality. This #if is closed at the very bottom +of this file. If you want to include software timer functionality then ensure +configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ +#if ( configUSE_TIMERS == 1 ) + +/* Misc definitions. */ +#define tmrNO_DELAY ( TickType_t ) 0U + +/* The name assigned to the timer service task. This can be overridden by +defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */ +#ifndef configTIMER_SERVICE_TASK_NAME + #define configTIMER_SERVICE_TASK_NAME "Tmr Svc" +#endif + +/* Bit definitions used in the ucStatus member of a timer structure. */ +#define tmrSTATUS_IS_ACTIVE ( ( uint8_t ) 0x01 ) +#define tmrSTATUS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 0x02 ) +#define tmrSTATUS_IS_AUTORELOAD ( ( uint8_t ) 0x04 ) + +/* The definition of the timers themselves. */ +typedef struct tmrTimerControl /* The old naming convention is used to prevent breaking kernel aware debuggers. */ +{ + const char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */ + TickType_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */ + void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */ + TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */ + #if( configUSE_TRACE_FACILITY == 1 ) + UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */ + #endif + uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */ +} xTIMER; + +/* The old xTIMER name is maintained above then typedefed to the new Timer_t +name below to enable the use of older kernel aware debuggers. */ +typedef xTIMER Timer_t; + +/* The definition of messages that can be sent and received on the timer queue. +Two types of message can be queued - messages that manipulate a software timer, +and messages that request the execution of a non-timer related callback. The +two message types are defined in two separate structures, xTimerParametersType +and xCallbackParametersType respectively. */ +typedef struct tmrTimerParameters +{ + TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */ + Timer_t * pxTimer; /*<< The timer to which the command will be applied. */ +} TimerParameter_t; + + +typedef struct tmrCallbackParameters +{ + PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */ + void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */ + uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */ +} CallbackParameters_t; + +/* The structure that contains the two message types, along with an identifier +that is used to determine which message type is valid. */ +typedef struct tmrTimerQueueMessage +{ + BaseType_t xMessageID; /*<< The command being sent to the timer service task. */ + union + { + TimerParameter_t xTimerParameters; + + /* Don't include xCallbackParameters if it is not going to be used as + it makes the structure (and therefore the timer queue) larger. */ + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + CallbackParameters_t xCallbackParameters; + #endif /* INCLUDE_xTimerPendFunctionCall */ + } u; +} DaemonTaskMessage_t; + +/*lint -save -e956 A manual analysis and inspection has been used to determine +which static variables must be declared volatile. */ + +/* The list in which active timers are stored. Timers are referenced in expire +time order, with the nearest expiry time at the front of the list. Only the +timer service task is allowed to access these lists. +xActiveTimerList1 and xActiveTimerList2 could be at function scope but that +breaks some kernel aware debuggers, and debuggers that reply on removing the +static qualifier. */ +PRIVILEGED_DATA static List_t xActiveTimerList1; +PRIVILEGED_DATA static List_t xActiveTimerList2; +PRIVILEGED_DATA static List_t *pxCurrentTimerList; +PRIVILEGED_DATA static List_t *pxOverflowTimerList; + +/* A queue that is used to send commands to the timer service task. */ +PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL; +PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL; + +/*lint -restore */ + +/*-----------------------------------------------------------*/ + +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + + /* If static allocation is supported then the application must provide the + following callback function - which enables the application to optionally + provide the memory that will be used by the timer task as the task's stack + and TCB. */ + extern void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize ); + +#endif + +/* + * Initialise the infrastructure used by the timer service task if it has not + * been initialised already. + */ +static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION; + +/* + * The timer service task (daemon). Timer functionality is controlled by this + * task. Other tasks communicate with the timer service task using the + * xTimerQueue queue. + */ +static portTASK_FUNCTION_PROTO( prvTimerTask, pvParameters ) PRIVILEGED_FUNCTION; + +/* + * Called by the timer service task to interpret and process a command it + * received on the timer queue. + */ +static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION; + +/* + * Insert the timer into either xActiveTimerList1, or xActiveTimerList2, + * depending on if the expire time causes a timer counter overflow. + */ +static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime ) PRIVILEGED_FUNCTION; + +/* + * An active timer has reached its expire time. Reload the timer if it is an + * auto-reload timer, then call its callback. + */ +static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow ) PRIVILEGED_FUNCTION; + +/* + * The tick count has overflowed. Switch the timer lists after ensuring the + * current timer list does not still reference some timers. + */ +static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION; + +/* + * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE + * if a tick count overflow occurred since prvSampleTimeNow() was last called. + */ +static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION; + +/* + * If the timer list contains any active timers then return the expire time of + * the timer that will expire first and set *pxListWasEmpty to false. If the + * timer list does not contain any timers then return 0 and set *pxListWasEmpty + * to pdTRUE. + */ +static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION; + +/* + * If a timer has expired, process it. Otherwise, block the timer service task + * until either a timer does expire or a command is received. + */ +static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION; + +/* + * Called after a Timer_t structure has been allocated either statically or + * dynamically to fill in the structure's members. + */ +static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t *pxNewTimer ) PRIVILEGED_FUNCTION; +/*-----------------------------------------------------------*/ + +BaseType_t xTimerCreateTimerTask( void ) +{ +BaseType_t xReturn = pdFAIL; + + /* This function is called when the scheduler is started if + configUSE_TIMERS is set to 1. Check that the infrastructure used by the + timer service task has been created/initialised. If timers have already + been created then the initialisation will already have been performed. */ + prvCheckForValidListAndQueue(); + + if( xTimerQueue != NULL ) + { + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + StaticTask_t *pxTimerTaskTCBBuffer = NULL; + StackType_t *pxTimerTaskStackBuffer = NULL; + uint32_t ulTimerTaskStackSize; + + vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize ); + xTimerTaskHandle = xTaskCreateStatic( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + ulTimerTaskStackSize, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + pxTimerTaskStackBuffer, + pxTimerTaskTCBBuffer ); + + if( xTimerTaskHandle != NULL ) + { + xReturn = pdPASS; + } + } + #else + { + xReturn = xTaskCreate( prvTimerTask, + configTIMER_SERVICE_TASK_NAME, + configTIMER_TASK_STACK_DEPTH, + NULL, + ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, + &xTimerTaskHandle ); + } + #endif /* configSUPPORT_STATIC_ALLOCATION */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + configASSERT( xReturn ); + return xReturn; +} +/*-----------------------------------------------------------*/ + +#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + + TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction ) + { + Timer_t *pxNewTimer; + + pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */ + + if( pxNewTimer != NULL ) + { + /* Status is thus far zero as the timer is not created statically + and has not been started. The auto-reload bit may get set in + prvInitialiseNewTimer. */ + pxNewTimer->ucStatus = 0x00; + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } + + return pxNewTimer; + } + +#endif /* configSUPPORT_DYNAMIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +#if( configSUPPORT_STATIC_ALLOCATION == 1 ) + + TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + StaticTimer_t *pxTimerBuffer ) + { + Timer_t *pxNewTimer; + + #if( configASSERT_DEFINED == 1 ) + { + /* Sanity check that the size of the structure used to declare a + variable of type StaticTimer_t equals the size of the real timer + structure. */ + volatile size_t xSize = sizeof( StaticTimer_t ); + configASSERT( xSize == sizeof( Timer_t ) ); + ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */ + } + #endif /* configASSERT_DEFINED */ + + /* A pointer to a StaticTimer_t structure MUST be provided, use it. */ + configASSERT( pxTimerBuffer ); + pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */ + + if( pxNewTimer != NULL ) + { + /* Timers can be created statically or dynamically so note this + timer was created statically in case it is later deleted. The + auto-reload bit may get set in prvInitialiseNewTimer(). */ + pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED; + + prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer ); + } + + return pxNewTimer; + } + +#endif /* configSUPPORT_STATIC_ALLOCATION */ +/*-----------------------------------------------------------*/ + +static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ + const TickType_t xTimerPeriodInTicks, + const UBaseType_t uxAutoReload, + void * const pvTimerID, + TimerCallbackFunction_t pxCallbackFunction, + Timer_t *pxNewTimer ) +{ + /* 0 is not a valid value for xTimerPeriodInTicks. */ + configASSERT( ( xTimerPeriodInTicks > 0 ) ); + + if( pxNewTimer != NULL ) + { + /* Ensure the infrastructure used by the timer service task has been + created/initialised. */ + prvCheckForValidListAndQueue(); + + /* Initialise the timer structure members using the function + parameters. */ + pxNewTimer->pcTimerName = pcTimerName; + pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks; + pxNewTimer->pvTimerID = pvTimerID; + pxNewTimer->pxCallbackFunction = pxCallbackFunction; + vListInitialiseItem( &( pxNewTimer->xTimerListItem ) ); + if( uxAutoReload != pdFALSE ) + { + pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; + } + traceTIMER_CREATE( pxNewTimer ); + } +} +/*-----------------------------------------------------------*/ + +BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) +{ +BaseType_t xReturn = pdFAIL; +DaemonTaskMessage_t xMessage; + + configASSERT( xTimer ); + + /* Send a message to the timer service task to perform a particular action + on a particular timer definition. */ + if( xTimerQueue != NULL ) + { + /* Send a command to the timer service task to start the xTimer timer. */ + xMessage.xMessageID = xCommandID; + xMessage.u.xTimerParameters.xMessageValue = xOptionalValue; + xMessage.u.xTimerParameters.pxTimer = xTimer; + + if( xCommandID < tmrFIRST_FROM_ISR_COMMAND ) + { + if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING ) + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + } + else + { + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY ); + } + } + else + { + xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + } + + traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + return xReturn; +} +/*-----------------------------------------------------------*/ + +TaskHandle_t xTimerGetTimerDaemonTaskHandle( void ) +{ + /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been + started, then xTimerTaskHandle will be NULL. */ + configASSERT( ( xTimerTaskHandle != NULL ) ); + return xTimerTaskHandle; +} +/*-----------------------------------------------------------*/ + +TickType_t xTimerGetPeriod( TimerHandle_t xTimer ) +{ +Timer_t *pxTimer = xTimer; + + configASSERT( xTimer ); + return pxTimer->xTimerPeriodInTicks; +} +/*-----------------------------------------------------------*/ + +void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload ) +{ +Timer_t * pxTimer = xTimer; + + configASSERT( xTimer ); + taskENTER_CRITICAL(); + { + if( uxAutoReload != pdFALSE ) + { + pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD; + } + else + { + pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD; + } + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer ) +{ +Timer_t * pxTimer = xTimer; +UBaseType_t uxReturn; + + configASSERT( xTimer ); + taskENTER_CRITICAL(); + { + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) == 0 ) + { + /* Not an auto-reload timer. */ + uxReturn = ( UBaseType_t ) pdFALSE; + } + else + { + /* Is an auto-reload timer. */ + uxReturn = ( UBaseType_t ) pdTRUE; + } + } + taskEXIT_CRITICAL(); + + return uxReturn; +} +/*-----------------------------------------------------------*/ + +TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer ) +{ +Timer_t * pxTimer = xTimer; +TickType_t xReturn; + + configASSERT( xTimer ); + xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) ); + return xReturn; +} +/*-----------------------------------------------------------*/ + +const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */ +{ +Timer_t *pxTimer = xTimer; + + configASSERT( xTimer ); + return pxTimer->pcTimerName; +} +/*-----------------------------------------------------------*/ + +static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow ) +{ +BaseType_t xResult; +Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + + /* Remove the timer from the list of active timers. A check has already + been performed to ensure the list is not empty. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + traceTIMER_EXPIRED( pxTimer ); + + /* If the timer is an auto-reload timer then calculate the next + expiry time and re-insert the timer in the list of active timers. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + /* The timer is inserted into a list using a time relative to anything + other than the current time. It will therefore be inserted into the + correct list relative to the time this task thinks it is now. */ + if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE ) + { + /* The timer expired before it was added to the active timer + list. Reload it now. */ + xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); + configASSERT( xResult ); + ( void ) xResult; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + mtCOVERAGE_TEST_MARKER(); + } + + /* Call the timer callback. */ + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( prvTimerTask, pvParameters ) +{ +TickType_t xNextExpireTime; +BaseType_t xListWasEmpty; + + /* Just to avoid compiler warnings. */ + ( void ) pvParameters; + + #if( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 ) + { + extern void vApplicationDaemonTaskStartupHook( void ); + + /* Allow the application writer to execute some code in the context of + this task at the point the task starts executing. This is useful if the + application includes initialisation code that would benefit from + executing after the scheduler has been started. */ + vApplicationDaemonTaskStartupHook(); + } + #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */ + + for( ;; ) + { + /* Query the timers list to see if it contains any timers, and if so, + obtain the time at which the next timer will expire. */ + xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty ); + + /* If a timer has expired, process it. Otherwise, block this task + until either a timer does expire, or a command is received. */ + prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty ); + + /* Empty the command queue. */ + prvProcessReceivedCommands(); + } +} +/*-----------------------------------------------------------*/ + +static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty ) +{ +TickType_t xTimeNow; +BaseType_t xTimerListsWereSwitched; + + vTaskSuspendAll(); + { + /* Obtain the time now to make an assessment as to whether the timer + has expired or not. If obtaining the time causes the lists to switch + then don't process this timer as any timers that remained in the list + when the lists were switched will have been processed within the + prvSampleTimeNow() function. */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + if( xTimerListsWereSwitched == pdFALSE ) + { + /* The tick count has not overflowed, has the timer expired? */ + if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) ) + { + ( void ) xTaskResumeAll(); + prvProcessExpiredTimer( xNextExpireTime, xTimeNow ); + } + else + { + /* The tick count has not overflowed, and the next expire + time has not been reached yet. This task should therefore + block to wait for the next expire time or a command to be + received - whichever comes first. The following line cannot + be reached unless xNextExpireTime > xTimeNow, except in the + case when the current timer list is empty. */ + if( xListWasEmpty != pdFALSE ) + { + /* The current timer list is empty - is the overflow list + also empty? */ + xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList ); + } + + vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty ); + + if( xTaskResumeAll() == pdFALSE ) + { + /* Yield to wait for either a command to arrive, or the + block time to expire. If a command arrived between the + critical section being exited and this yield then the yield + will not cause the task to block. */ + portYIELD_WITHIN_API(); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + } + else + { + ( void ) xTaskResumeAll(); + } + } +} +/*-----------------------------------------------------------*/ + +static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) +{ +TickType_t xNextExpireTime; + + /* Timers are listed in expiry time order, with the head of the list + referencing the task that will expire first. Obtain the time at which + the timer with the nearest expiry time will expire. If there are no + active timers then just set the next expire time to 0. That will cause + this task to unblock when the tick count overflows, at which point the + timer lists will be switched and the next expiry time can be + re-assessed. */ + *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList ); + if( *pxListWasEmpty == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + } + else + { + /* Ensure the task unblocks when the tick count rolls over. */ + xNextExpireTime = ( TickType_t ) 0U; + } + + return xNextExpireTime; +} +/*-----------------------------------------------------------*/ + +static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) +{ +TickType_t xTimeNow; +PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */ + + xTimeNow = xTaskGetTickCount(); + + if( xTimeNow < xLastTime ) + { + prvSwitchTimerLists(); + *pxTimerListsWereSwitched = pdTRUE; + } + else + { + *pxTimerListsWereSwitched = pdFALSE; + } + + xLastTime = xTimeNow; + + return xTimeNow; +} +/*-----------------------------------------------------------*/ + +static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime ) +{ +BaseType_t xProcessTimerNow = pdFALSE; + + listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime ); + listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); + + if( xNextExpiryTime <= xTimeNow ) + { + /* Has the expiry time elapsed between the command to start/reset a + timer was issued, and the time the command was processed? */ + if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */ + { + /* The time between a command being issued and the command being + processed actually exceeds the timers period. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) ); + } + } + else + { + if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) ) + { + /* If, since the command was issued, the tick count has overflowed + but the expiry time has not, then the timer must have already passed + its expiry time and should be processed immediately. */ + xProcessTimerNow = pdTRUE; + } + else + { + vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); + } + } + + return xProcessTimerNow; +} +/*-----------------------------------------------------------*/ + +static void prvProcessReceivedCommands( void ) +{ +DaemonTaskMessage_t xMessage; +Timer_t *pxTimer; +BaseType_t xTimerListsWereSwitched, xResult; +TickType_t xTimeNow; + + while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */ + { + #if ( INCLUDE_xTimerPendFunctionCall == 1 ) + { + /* Negative commands are pended function calls rather than timer + commands. */ + if( xMessage.xMessageID < ( BaseType_t ) 0 ) + { + const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters ); + + /* The timer uses the xCallbackParameters member to request a + callback be executed. Check the callback is not NULL. */ + configASSERT( pxCallback ); + + /* Call the function. */ + pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* INCLUDE_xTimerPendFunctionCall */ + + /* Commands that are positive are timer commands rather than pended + function calls. */ + if( xMessage.xMessageID >= ( BaseType_t ) 0 ) + { + /* The messages uses the xTimerParameters member to work on a + software timer. */ + pxTimer = xMessage.u.xTimerParameters.pxTimer; + + if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */ + { + /* The timer is in a list, remove it. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + + traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue ); + + /* In this case the xTimerListsWereSwitched parameter is not used, but + it must be present in the function call. prvSampleTimeNow() must be + called after the message is received from xTimerQueue so there is no + possibility of a higher priority task adding a message to the message + queue with a time that is ahead of the timer daemon task (because it + pre-empted the timer daemon task after the xTimeNow value was set). */ + xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched ); + + switch( xMessage.xMessageID ) + { + case tmrCOMMAND_START : + case tmrCOMMAND_START_FROM_ISR : + case tmrCOMMAND_RESET : + case tmrCOMMAND_RESET_FROM_ISR : + case tmrCOMMAND_START_DONT_TRACE : + /* Start or restart a timer. */ + pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; + if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE ) + { + /* The timer expired before it was added to the active + timer list. Process it now. */ + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + traceTIMER_EXPIRED( pxTimer ); + + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY ); + configASSERT( xResult ); + ( void ) xResult; + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + break; + + case tmrCOMMAND_STOP : + case tmrCOMMAND_STOP_FROM_ISR : + /* The timer has already been removed from the active list. */ + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + break; + + case tmrCOMMAND_CHANGE_PERIOD : + case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR : + pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE; + pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue; + configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) ); + + /* The new period does not really have a reference, and can + be longer or shorter than the old one. The command time is + therefore set to the current time, and as the period cannot + be zero the next expiry time can only be in the future, + meaning (unlike for the xTimerStart() case above) there is + no fail case that needs to be handled here. */ + ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow ); + break; + + case tmrCOMMAND_DELETE : + #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) + { + /* The timer has already been removed from the active list, + just free up the memory if the memory was dynamically + allocated. */ + if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 ) + { + vPortFree( pxTimer ); + } + else + { + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + } + } + #else + { + /* If dynamic allocation is not enabled, the memory + could not have been dynamically allocated. So there is + no need to free the memory - just mark the timer as + "not active". */ + pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE; + } + #endif /* configSUPPORT_DYNAMIC_ALLOCATION */ + break; + + default : + /* Don't expect to get here. */ + break; + } + } + } +} +/*-----------------------------------------------------------*/ + +static void prvSwitchTimerLists( void ) +{ +TickType_t xNextExpireTime, xReloadTime; +List_t *pxTemp; +Timer_t *pxTimer; +BaseType_t xResult; + + /* The tick count has overflowed. The timer lists must be switched. + If there are any timers still referenced from the current timer list + then they must have expired and should be processed before the lists + are switched. */ + while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE ) + { + xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList ); + + /* Remove the timer from the list. */ + pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */ + ( void ) uxListRemove( &( pxTimer->xTimerListItem ) ); + traceTIMER_EXPIRED( pxTimer ); + + /* Execute its callback, then send a command to restart the timer if + it is an auto-reload timer. It cannot be restarted here as the lists + have not yet been switched. */ + pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer ); + + if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 ) + { + /* Calculate the reload value, and if the reload value results in + the timer going into the same timer list then it has already expired + and the timer should be re-inserted into the current list so it is + processed again within this loop. Otherwise a command should be sent + to restart the timer to ensure it is only inserted into a list after + the lists have been swapped. */ + xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ); + if( xReloadTime > xNextExpireTime ) + { + listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime ); + listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer ); + vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) ); + } + else + { + xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY ); + configASSERT( xResult ); + ( void ) xResult; + } + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + + pxTemp = pxCurrentTimerList; + pxCurrentTimerList = pxOverflowTimerList; + pxOverflowTimerList = pxTemp; +} +/*-----------------------------------------------------------*/ + +static void prvCheckForValidListAndQueue( void ) +{ + /* Check that the list from which active timers are referenced, and the + queue used to communicate with the timer service, have been + initialised. */ + taskENTER_CRITICAL(); + { + if( xTimerQueue == NULL ) + { + vListInitialise( &xActiveTimerList1 ); + vListInitialise( &xActiveTimerList2 ); + pxCurrentTimerList = &xActiveTimerList1; + pxOverflowTimerList = &xActiveTimerList2; + + #if( configSUPPORT_STATIC_ALLOCATION == 1 ) + { + /* The timer queue is allocated statically in case + configSUPPORT_DYNAMIC_ALLOCATION is 0. */ + static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */ + + xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue ); + } + #else + { + xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) ); + } + #endif + + #if ( configQUEUE_REGISTRY_SIZE > 0 ) + { + if( xTimerQueue != NULL ) + { + vQueueAddToRegistry( xTimerQueue, "TmrQ" ); + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + #endif /* configQUEUE_REGISTRY_SIZE */ + } + else + { + mtCOVERAGE_TEST_MARKER(); + } + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) +{ +BaseType_t xReturn; +Timer_t *pxTimer = xTimer; + + configASSERT( xTimer ); + + /* Is the timer in the list of active timers? */ + taskENTER_CRITICAL(); + { + if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 ) + { + xReturn = pdFALSE; + } + else + { + xReturn = pdTRUE; + } + } + taskEXIT_CRITICAL(); + + return xReturn; +} /*lint !e818 Can't be pointer to const due to the typedef. */ +/*-----------------------------------------------------------*/ + +void *pvTimerGetTimerID( const TimerHandle_t xTimer ) +{ +Timer_t * const pxTimer = xTimer; +void *pvReturn; + + configASSERT( xTimer ); + + taskENTER_CRITICAL(); + { + pvReturn = pxTimer->pvTimerID; + } + taskEXIT_CRITICAL(); + + return pvReturn; +} +/*-----------------------------------------------------------*/ + +void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID ) +{ +Timer_t * const pxTimer = xTimer; + + configASSERT( xTimer ); + + taskENTER_CRITICAL(); + { + pxTimer->pvTimerID = pvNewID; + } + taskEXIT_CRITICAL(); +} +/*-----------------------------------------------------------*/ + +#if( INCLUDE_xTimerPendFunctionCall == 1 ) + + BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; + + /* Complete the message with the function parameters and post it to the + daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + + xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken ); + + tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + + return xReturn; + } + +#endif /* INCLUDE_xTimerPendFunctionCall */ +/*-----------------------------------------------------------*/ + +#if( INCLUDE_xTimerPendFunctionCall == 1 ) + + BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait ) + { + DaemonTaskMessage_t xMessage; + BaseType_t xReturn; + + /* This function can only be called after a timer has been created or + after the scheduler has been started because, until then, the timer + queue does not exist. */ + configASSERT( xTimerQueue ); + + /* Complete the message with the function parameters and post it to the + daemon task. */ + xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK; + xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend; + xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1; + xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2; + + xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait ); + + tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn ); + + return xReturn; + } + +#endif /* INCLUDE_xTimerPendFunctionCall */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer ) + { + return ( ( Timer_t * ) xTimer )->uxTimerNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +#if ( configUSE_TRACE_FACILITY == 1 ) + + void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber ) + { + ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber; + } + +#endif /* configUSE_TRACE_FACILITY */ +/*-----------------------------------------------------------*/ + +/* This entire source file will be skipped if the application is not configured +to include software timer functionality. If you want to include software timer +functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */ +#endif /* configUSE_TIMERS == 1 */ + + + diff --git a/Middlewares/Third_Party/SEGGER/Config/SEGGER_RTT_Conf.h b/Middlewares/Third_Party/SEGGER/Config/SEGGER_RTT_Conf.h new file mode 100644 index 0000000..203f33a --- /dev/null +++ b/Middlewares/Third_Party/SEGGER/Config/SEGGER_RTT_Conf.h @@ -0,0 +1,429 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH * +* The Embedded Experts * +********************************************************************** +* * +* (c) 1995 - 2021 SEGGER Microcontroller GmbH * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* condition is met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this condition and the following disclaimer. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 7.58c * +* * +********************************************************************** + +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT_Conf.h +Purpose : Implementation of SEGGER real-time transfer (RTT) which + allows real-time communication on targets which support + debugger memory accesses while the CPU is running. +Revision: $Rev: 24316 $ + +*/ + +#ifndef SEGGER_RTT_CONF_H +#define SEGGER_RTT_CONF_H + +#ifdef __IAR_SYSTEMS_ICC__ + #include +#endif + +/********************************************************************* +* +* Defines, configurable +* +********************************************************************** +*/ + +// +// Take in and set to correct values for Cortex-A systems with CPU cache +// +//#define SEGGER_RTT_CPU_CACHE_LINE_SIZE (32) // Largest cache line size (in bytes) in the current system +//#define SEGGER_RTT_UNCACHED_OFF (0xFB000000) // Address alias where RTT CB and buffers can be accessed uncached +// +// Most common case: +// Up-channel 0: RTT +// Up-channel 1: SystemView +// +#ifndef SEGGER_RTT_MAX_NUM_UP_BUFFERS + #define SEGGER_RTT_MAX_NUM_UP_BUFFERS (3) // Max. number of up-buffers (T->H) available on this target (Default: 3) +#endif +// +// Most common case: +// Down-channel 0: RTT +// Down-channel 1: SystemView +// +#ifndef SEGGER_RTT_MAX_NUM_DOWN_BUFFERS + #define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (3) // Max. number of down-buffers (H->T) available on this target (Default: 3) +#endif + +#ifndef BUFFER_SIZE_UP + #define BUFFER_SIZE_UP (1024) // Size of the buffer for terminal output of target, up to host (Default: 1k) +#endif + +#ifndef BUFFER_SIZE_DOWN + #define BUFFER_SIZE_DOWN (16) // Size of the buffer for terminal input to target from host (Usually keyboard input) (Default: 16) +#endif + +#ifndef SEGGER_RTT_PRINTF_BUFFER_SIZE + #define SEGGER_RTT_PRINTF_BUFFER_SIZE (64u) // Size of buffer for RTT printf to bulk-send chars via RTT (Default: 64) +#endif + +#ifndef SEGGER_RTT_MODE_DEFAULT + #define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP // Mode for pre-initialized terminal channel (buffer 0) +#endif + +/********************************************************************* +* +* RTT memcpy configuration +* +* memcpy() is good for large amounts of data, +* but the overhead is big for small amounts, which are usually stored via RTT. +* With SEGGER_RTT_MEMCPY_USE_BYTELOOP a simple byte loop can be used instead. +* +* SEGGER_RTT_MEMCPY() can be used to replace standard memcpy() in RTT functions. +* This is may be required with memory access restrictions, +* such as on Cortex-A devices with MMU. +*/ +#ifndef SEGGER_RTT_MEMCPY_USE_BYTELOOP + #define SEGGER_RTT_MEMCPY_USE_BYTELOOP 0 // 0: Use memcpy/SEGGER_RTT_MEMCPY, 1: Use a simple byte-loop +#endif +// +// Example definition of SEGGER_RTT_MEMCPY to external memcpy with GCC toolchains and Cortex-A targets +// +//#if ((defined __SES_ARM) || (defined __CROSSWORKS_ARM) || (defined __GNUC__)) && (defined (__ARM_ARCH_7A__)) +// #define SEGGER_RTT_MEMCPY(pDest, pSrc, NumBytes) SEGGER_memcpy((pDest), (pSrc), (NumBytes)) +//#endif + +// +// Target is not allowed to perform other RTT operations while string still has not been stored completely. +// Otherwise we would probably end up with a mixed string in the buffer. +// If using RTT from within interrupts, multiple tasks or multi processors, define the SEGGER_RTT_LOCK() and SEGGER_RTT_UNLOCK() function here. +// +// SEGGER_RTT_MAX_INTERRUPT_PRIORITY can be used in the sample lock routines on Cortex-M3/4. +// Make sure to mask all interrupts which can send RTT data, i.e. generate SystemView events, or cause task switches. +// When high-priority interrupts must not be masked while sending RTT data, SEGGER_RTT_MAX_INTERRUPT_PRIORITY needs to be adjusted accordingly. +// (Higher priority = lower priority number) +// Default value for embOS: 128u +// Default configuration in FreeRTOS: configMAX_SYSCALL_INTERRUPT_PRIORITY: ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) +// In case of doubt mask all interrupts: 1 << (8 - BASEPRI_PRIO_BITS) i.e. 1 << 5 when 3 bits are implemented in NVIC +// or define SEGGER_RTT_LOCK() to completely disable interrupts. +// +#ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) // Interrupt priority to lock on SEGGER_RTT_LOCK on Cortex-M3/4 (Default: 0x20) +#endif + +/********************************************************************* +* +* RTT lock configuration for SEGGER Embedded Studio, +* Rowley CrossStudio and GCC +*/ +#if ((defined(__SES_ARM) || defined(__SES_RISCV) || defined(__CROSSWORKS_ARM) || defined(__GNUC__) || defined(__clang__)) && !defined (__CC_ARM) && !defined(WIN32)) + #if (defined(__ARM_ARCH_6M__) || defined(__ARM_ARCH_8M_BASE__)) + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + __asm volatile ("mrs %0, primask \n\t" \ + "movs r1, #1 \n\t" \ + "msr primask, r1 \n\t" \ + : "=r" (_SEGGER_RTT__LockState) \ + : \ + : "r1", "cc" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("msr primask, %0 \n\t" \ + : \ + : "r" (_SEGGER_RTT__LockState) \ + : \ + ); \ + } + #elif (defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_8M_MAIN__)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + __asm volatile ("mrs %0, basepri \n\t" \ + "mov r1, %1 \n\t" \ + "msr basepri, r1 \n\t" \ + : "=r" (_SEGGER_RTT__LockState) \ + : "i"(SEGGER_RTT_MAX_INTERRUPT_PRIORITY) \ + : "r1", "cc" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("msr basepri, %0 \n\t" \ + : \ + : "r" (_SEGGER_RTT__LockState) \ + : \ + ); \ + } + + #elif (defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__)) + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + __asm volatile ("mrs r1, CPSR \n\t" \ + "mov %0, r1 \n\t" \ + "orr r1, r1, #0xC0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : "=r" (_SEGGER_RTT__LockState) \ + : \ + : "r1", "cc" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("mov r0, %0 \n\t" \ + "mrs r1, CPSR \n\t" \ + "bic r1, r1, #0xC0 \n\t" \ + "and r0, r0, #0xC0 \n\t" \ + "orr r1, r1, r0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : \ + : "r" (_SEGGER_RTT__LockState) \ + : "r0", "r1", "cc" \ + ); \ + } + #elif defined(__riscv) || defined(__riscv_xlen) + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + __asm volatile ("csrr %0, mstatus \n\t" \ + "csrci mstatus, 8 \n\t" \ + "andi %0, %0, 8 \n\t" \ + : "=r" (_SEGGER_RTT__LockState) \ + : \ + : \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("csrr a1, mstatus \n\t" \ + "or %0, %0, a1 \n\t" \ + "csrs mstatus, %0 \n\t" \ + : \ + : "r" (_SEGGER_RTT__LockState) \ + : "a1" \ + ); \ + } + #else + #define SEGGER_RTT_LOCK() + #define SEGGER_RTT_UNLOCK() + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for IAR EWARM +*/ +#ifdef __ICCARM__ + #if (defined (__ARM6M__) && (__CORE__ == __ARM6M__)) || \ + (defined (__ARM8M_BASELINE__) && (__CORE__ == __ARM8M_BASELINE__)) + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + _SEGGER_RTT__LockState = __get_PRIMASK(); \ + __set_PRIMASK(1); + + #define SEGGER_RTT_UNLOCK() __set_PRIMASK(_SEGGER_RTT__LockState); \ + } + #elif (defined (__ARM7EM__) && (__CORE__ == __ARM7EM__)) || \ + (defined (__ARM7M__) && (__CORE__ == __ARM7M__)) || \ + (defined (__ARM8M_MAINLINE__) && (__CORE__ == __ARM8M_MAINLINE__)) || \ + (defined (__ARM8M_MAINLINE__) && (__CORE__ == __ARM8M_MAINLINE__)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + _SEGGER_RTT__LockState = __get_BASEPRI(); \ + __set_BASEPRI(SEGGER_RTT_MAX_INTERRUPT_PRIORITY); + + #define SEGGER_RTT_UNLOCK() __set_BASEPRI(_SEGGER_RTT__LockState); \ + } + #elif (defined (__ARM7A__) && (__CORE__ == __ARM7A__)) || \ + (defined (__ARM7R__) && (__CORE__ == __ARM7R__)) + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + __asm volatile ("mrs r1, CPSR \n\t" \ + "mov %0, r1 \n\t" \ + "orr r1, r1, #0xC0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : "=r" (_SEGGER_RTT__LockState) \ + : \ + : "r1", "cc" \ + ); + + #define SEGGER_RTT_UNLOCK() __asm volatile ("mov r0, %0 \n\t" \ + "mrs r1, CPSR \n\t" \ + "bic r1, r1, #0xC0 \n\t" \ + "and r0, r0, #0xC0 \n\t" \ + "orr r1, r1, r0 \n\t" \ + "msr CPSR_c, r1 \n\t" \ + : \ + : "r" (_SEGGER_RTT__LockState) \ + : "r0", "r1", "cc" \ + ); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for IAR RX +*/ +#ifdef __ICCRX__ + #define SEGGER_RTT_LOCK() { \ + unsigned long _SEGGER_RTT__LockState; \ + _SEGGER_RTT__LockState = __get_interrupt_state(); \ + __disable_interrupt(); + + #define SEGGER_RTT_UNLOCK() __set_interrupt_state(_SEGGER_RTT__LockState); \ + } +#endif + +/********************************************************************* +* +* RTT lock configuration for IAR RL78 +*/ +#ifdef __ICCRL78__ + #define SEGGER_RTT_LOCK() { \ + __istate_t _SEGGER_RTT__LockState; \ + _SEGGER_RTT__LockState = __get_interrupt_state(); \ + __disable_interrupt(); + + #define SEGGER_RTT_UNLOCK() __set_interrupt_state(_SEGGER_RTT__LockState); \ + } +#endif + +/********************************************************************* +* +* RTT lock configuration for KEIL ARM +*/ +#ifdef __CC_ARM + #if (defined __TARGET_ARCH_6S_M) + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + register unsigned char _SEGGER_RTT__PRIMASK __asm( "primask"); \ + _SEGGER_RTT__LockState = _SEGGER_RTT__PRIMASK; \ + _SEGGER_RTT__PRIMASK = 1u; \ + __schedule_barrier(); + + #define SEGGER_RTT_UNLOCK() _SEGGER_RTT__PRIMASK = _SEGGER_RTT__LockState; \ + __schedule_barrier(); \ + } + #elif (defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + register unsigned char BASEPRI __asm( "basepri"); \ + _SEGGER_RTT__LockState = BASEPRI; \ + BASEPRI = SEGGER_RTT_MAX_INTERRUPT_PRIORITY; \ + __schedule_barrier(); + + #define SEGGER_RTT_UNLOCK() BASEPRI = _SEGGER_RTT__LockState; \ + __schedule_barrier(); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for TI ARM +*/ +#ifdef __TI_ARM__ + #if defined (__TI_ARM_V6M0__) + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + _SEGGER_RTT__LockState = __get_PRIMASK(); \ + __set_PRIMASK(1); + + #define SEGGER_RTT_UNLOCK() __set_PRIMASK(_SEGGER_RTT__LockState); \ + } + #elif (defined (__TI_ARM_V7M3__) || defined (__TI_ARM_V7M4__)) + #ifndef SEGGER_RTT_MAX_INTERRUPT_PRIORITY + #define SEGGER_RTT_MAX_INTERRUPT_PRIORITY (0x20) + #endif + #define SEGGER_RTT_LOCK() { \ + unsigned int _SEGGER_RTT__LockState; \ + _SEGGER_RTT__LockState = _set_interrupt_priority(SEGGER_RTT_MAX_INTERRUPT_PRIORITY); + + #define SEGGER_RTT_UNLOCK() _set_interrupt_priority(_SEGGER_RTT__LockState); \ + } + #endif +#endif + +/********************************************************************* +* +* RTT lock configuration for CCRX +*/ +#ifdef __RX + #include + #define SEGGER_RTT_LOCK() { \ + unsigned long _SEGGER_RTT__LockState; \ + _SEGGER_RTT__LockState = get_psw() & 0x010000; \ + clrpsw_i(); + + #define SEGGER_RTT_UNLOCK() set_psw(get_psw() | _SEGGER_RTT__LockState); \ + } +#endif + +/********************************************************************* +* +* RTT lock configuration for embOS Simulation on Windows +* (Can also be used for generic RTT locking with embOS) +*/ +#if defined(WIN32) || defined(SEGGER_RTT_LOCK_EMBOS) + +void OS_SIM_EnterCriticalSection(void); +void OS_SIM_LeaveCriticalSection(void); + +#define SEGGER_RTT_LOCK() { \ + OS_SIM_EnterCriticalSection(); + +#define SEGGER_RTT_UNLOCK() OS_SIM_LeaveCriticalSection(); \ + } +#endif + +/********************************************************************* +* +* RTT lock configuration fallback +*/ +#ifndef SEGGER_RTT_LOCK + #define SEGGER_RTT_LOCK() // Lock RTT (nestable) (i.e. disable interrupts) +#endif + +#ifndef SEGGER_RTT_UNLOCK + #define SEGGER_RTT_UNLOCK() // Unlock RTT (nestable) (i.e. enable previous interrupt lock state) +#endif + +#endif +/*************************** End of file ****************************/ diff --git a/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT.c b/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT.c new file mode 100644 index 0000000..23211cc --- /dev/null +++ b/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT.c @@ -0,0 +1,2090 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH * +* The Embedded Experts * +********************************************************************** +* * +* (c) 1995 - 2021 SEGGER Microcontroller GmbH * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* condition is met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this condition and the following disclaimer. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 7.58c * +* * +********************************************************************** + +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT.c +Purpose : Implementation of SEGGER real-time transfer (RTT) which + allows real-time communication on targets which support + debugger memory accesses while the CPU is running. +Revision: $Rev: 24715 $ + +Additional information: + Type "int" is assumed to be 32-bits in size + H->T Host to target communication + T->H Target to host communication + + RTT channel 0 is always present and reserved for Terminal usage. + Name is fixed to "Terminal" + + Effective buffer size: SizeOfBuffer - 1 + + WrOff == RdOff: Buffer is empty + WrOff == (RdOff - 1): Buffer is full + WrOff > RdOff: Free space includes wrap-around + WrOff < RdOff: Used space includes wrap-around + (WrOff == (SizeOfBuffer - 1)) && (RdOff == 0): + Buffer full and wrap-around after next byte + + +---------------------------------------------------------------------- +*/ + +#include "SEGGER_RTT.h" + +#include // for memcpy + +/********************************************************************* +* +* Configuration, default values +* +********************************************************************** +*/ + +#if SEGGER_RTT_CPU_CACHE_LINE_SIZE + #ifdef SEGGER_RTT_CB_ALIGN + #error "Custom SEGGER_RTT_CB_ALIGN() is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0" + #endif + #ifdef SEGGER_RTT_BUFFER_ALIGN + #error "Custom SEGGER_RTT_BUFFER_ALIGN() is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0" + #endif + #ifdef SEGGER_RTT_PUT_CB_SECTION + #error "Custom SEGGER_RTT_PUT_CB_SECTION() is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0" + #endif + #ifdef SEGGER_RTT_PUT_BUFFER_SECTION + #error "Custom SEGGER_RTT_PUT_BUFFER_SECTION() is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0" + #endif + #ifdef SEGGER_RTT_BUFFER_ALIGNMENT + #error "Custom SEGGER_RTT_BUFFER_ALIGNMENT is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0" + #endif + #ifdef SEGGER_RTT_ALIGNMENT + #error "Custom SEGGER_RTT_ALIGNMENT is not supported for SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0" + #endif +#endif + +#ifndef BUFFER_SIZE_UP + #define BUFFER_SIZE_UP 1024 // Size of the buffer for terminal output of target, up to host +#endif + +#ifndef BUFFER_SIZE_DOWN + #define BUFFER_SIZE_DOWN 16 // Size of the buffer for terminal input to target from host (Usually keyboard input) +#endif + +#ifndef SEGGER_RTT_MAX_NUM_UP_BUFFERS + #define SEGGER_RTT_MAX_NUM_UP_BUFFERS 2 // Number of up-buffers (T->H) available on this target +#endif + +#ifndef SEGGER_RTT_MAX_NUM_DOWN_BUFFERS + #define SEGGER_RTT_MAX_NUM_DOWN_BUFFERS 2 // Number of down-buffers (H->T) available on this target +#endif + +#ifndef SEGGER_RTT_BUFFER_SECTION + #if defined(SEGGER_RTT_SECTION) + #define SEGGER_RTT_BUFFER_SECTION SEGGER_RTT_SECTION + #endif +#endif + +#ifndef SEGGER_RTT_ALIGNMENT + #define SEGGER_RTT_ALIGNMENT SEGGER_RTT_CPU_CACHE_LINE_SIZE +#endif + +#ifndef SEGGER_RTT_BUFFER_ALIGNMENT + #define SEGGER_RTT_BUFFER_ALIGNMENT SEGGER_RTT_CPU_CACHE_LINE_SIZE +#endif + +#ifndef SEGGER_RTT_MODE_DEFAULT + #define SEGGER_RTT_MODE_DEFAULT SEGGER_RTT_MODE_NO_BLOCK_SKIP +#endif + +#ifndef SEGGER_RTT_LOCK + #define SEGGER_RTT_LOCK() +#endif + +#ifndef SEGGER_RTT_UNLOCK + #define SEGGER_RTT_UNLOCK() +#endif + +#ifndef STRLEN + #define STRLEN(a) strlen((a)) +#endif + +#ifndef STRCPY + #define STRCPY(pDest, pSrc) strcpy((pDest), (pSrc)) +#endif + +#ifndef SEGGER_RTT_MEMCPY_USE_BYTELOOP + #define SEGGER_RTT_MEMCPY_USE_BYTELOOP 0 +#endif + +#ifndef SEGGER_RTT_MEMCPY + #ifdef MEMCPY + #define SEGGER_RTT_MEMCPY(pDest, pSrc, NumBytes) MEMCPY((pDest), (pSrc), (NumBytes)) + #else + #define SEGGER_RTT_MEMCPY(pDest, pSrc, NumBytes) memcpy((pDest), (pSrc), (NumBytes)) + #endif +#endif + +#ifndef MIN + #define MIN(a, b) (((a) < (b)) ? (a) : (b)) +#endif + +#ifndef MAX + #define MAX(a, b) (((a) > (b)) ? (a) : (b)) +#endif +// +// For some environments, NULL may not be defined until certain headers are included +// +#ifndef NULL + #define NULL 0 +#endif + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ +#if (defined __ICCARM__) || (defined __ICCRX__) + #define RTT_PRAGMA(P) _Pragma(#P) +#endif + +#if SEGGER_RTT_ALIGNMENT || SEGGER_RTT_BUFFER_ALIGNMENT + #if ((defined __GNUC__) || (defined __clang__)) + #define SEGGER_RTT_ALIGN(Var, Alignment) Var __attribute__ ((aligned (Alignment))) + #elif (defined __ICCARM__) || (defined __ICCRX__) + #define PRAGMA(A) _Pragma(#A) +#define SEGGER_RTT_ALIGN(Var, Alignment) RTT_PRAGMA(data_alignment=Alignment) \ + Var + #elif (defined __CC_ARM) + #define SEGGER_RTT_ALIGN(Var, Alignment) Var __attribute__ ((aligned (Alignment))) + #else + #error "Alignment not supported for this compiler." + #endif +#else + #define SEGGER_RTT_ALIGN(Var, Alignment) Var +#endif + +#if defined(SEGGER_RTT_SECTION) || defined (SEGGER_RTT_BUFFER_SECTION) + #if ((defined __GNUC__) || (defined __clang__)) + #define SEGGER_RTT_PUT_SECTION(Var, Section) __attribute__ ((section (Section))) Var + #elif (defined __ICCARM__) || (defined __ICCRX__) +#define SEGGER_RTT_PUT_SECTION(Var, Section) RTT_PRAGMA(location=Section) \ + Var + #elif (defined __CC_ARM) + #define SEGGER_RTT_PUT_SECTION(Var, Section) __attribute__ ((section (Section), zero_init)) Var + #else + #error "Section placement not supported for this compiler." + #endif +#else + #define SEGGER_RTT_PUT_SECTION(Var, Section) Var +#endif + +#if SEGGER_RTT_ALIGNMENT + #define SEGGER_RTT_CB_ALIGN(Var) SEGGER_RTT_ALIGN(Var, SEGGER_RTT_ALIGNMENT) +#else + #define SEGGER_RTT_CB_ALIGN(Var) Var +#endif + +#if SEGGER_RTT_BUFFER_ALIGNMENT + #define SEGGER_RTT_BUFFER_ALIGN(Var) SEGGER_RTT_ALIGN(Var, SEGGER_RTT_BUFFER_ALIGNMENT) +#else + #define SEGGER_RTT_BUFFER_ALIGN(Var) Var +#endif + + +#if defined(SEGGER_RTT_SECTION) + #define SEGGER_RTT_PUT_CB_SECTION(Var) SEGGER_RTT_PUT_SECTION(Var, SEGGER_RTT_SECTION) +#else + #define SEGGER_RTT_PUT_CB_SECTION(Var) Var +#endif + +#if defined(SEGGER_RTT_BUFFER_SECTION) + #define SEGGER_RTT_PUT_BUFFER_SECTION(Var) SEGGER_RTT_PUT_SECTION(Var, SEGGER_RTT_BUFFER_SECTION) +#else + #define SEGGER_RTT_PUT_BUFFER_SECTION(Var) Var +#endif + +/********************************************************************* +* +* Static const data +* +********************************************************************** +*/ + +static unsigned char _aTerminalId[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + +/********************************************************************* +* +* Static data +* +********************************************************************** +*/ + +// +// RTT Control Block and allocate buffers for channel 0 +// +#if SEGGER_RTT_CPU_CACHE_LINE_SIZE + #if ((defined __GNUC__) || (defined __clang__)) + SEGGER_RTT_CB _SEGGER_RTT __attribute__ ((aligned (SEGGER_RTT_CPU_CACHE_LINE_SIZE))); + static char _acUpBuffer [SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(BUFFER_SIZE_UP)] __attribute__ ((aligned (SEGGER_RTT_CPU_CACHE_LINE_SIZE))); + static char _acDownBuffer[SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(BUFFER_SIZE_DOWN)] __attribute__ ((aligned (SEGGER_RTT_CPU_CACHE_LINE_SIZE))); + #else + #error "Don't know how to place _SEGGER_RTT, _acUpBuffer, _acDownBuffer cache-line aligned" + #endif +#else + SEGGER_RTT_PUT_CB_SECTION(SEGGER_RTT_CB_ALIGN(SEGGER_RTT_CB _SEGGER_RTT)); + SEGGER_RTT_PUT_BUFFER_SECTION(SEGGER_RTT_BUFFER_ALIGN(static char _acUpBuffer [BUFFER_SIZE_UP])); + SEGGER_RTT_PUT_BUFFER_SECTION(SEGGER_RTT_BUFFER_ALIGN(static char _acDownBuffer[BUFFER_SIZE_DOWN])); +#endif + +static unsigned char _ActiveTerminal; + +/********************************************************************* +* +* Static functions +* +********************************************************************** +*/ + +/********************************************************************* +* +* _DoInit() +* +* Function description +* Initializes the control block an buffers. +* May only be called via INIT() to avoid overriding settings. +* +*/ +#define INIT() { \ + volatile SEGGER_RTT_CB* pRTTCBInit; \ + pRTTCBInit = (volatile SEGGER_RTT_CB*)((char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); \ + do { \ + if (pRTTCBInit->acID[0] == '\0') { \ + _DoInit(); \ + } \ + } while (0); \ + } + +static void _DoInit(void) { + volatile SEGGER_RTT_CB* p; // Volatile to make sure that compiler cannot change the order of accesses to the control block + static const char _aInitStr[] = "\0\0\0\0\0\0TTR REGGES"; // Init complete ID string to make sure that things also work if RTT is linked to a no-init memory area + unsigned i; + // + // Initialize control block + // + p = (volatile SEGGER_RTT_CB*)((char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access control block uncached so that nothing in the cache ever becomes dirty and all changes are visible in HW directly + memset((SEGGER_RTT_CB*)p, 0, sizeof(_SEGGER_RTT)); // Make sure that the RTT CB is always zero initialized. + p->MaxNumUpBuffers = SEGGER_RTT_MAX_NUM_UP_BUFFERS; + p->MaxNumDownBuffers = SEGGER_RTT_MAX_NUM_DOWN_BUFFERS; + // + // Initialize up buffer 0 + // + p->aUp[0].sName = "Terminal"; + p->aUp[0].pBuffer = _acUpBuffer; + p->aUp[0].SizeOfBuffer = BUFFER_SIZE_UP; + p->aUp[0].RdOff = 0u; + p->aUp[0].WrOff = 0u; + p->aUp[0].Flags = SEGGER_RTT_MODE_DEFAULT; + // + // Initialize down buffer 0 + // + p->aDown[0].sName = "Terminal"; + p->aDown[0].pBuffer = _acDownBuffer; + p->aDown[0].SizeOfBuffer = BUFFER_SIZE_DOWN; + p->aDown[0].RdOff = 0u; + p->aDown[0].WrOff = 0u; + p->aDown[0].Flags = SEGGER_RTT_MODE_DEFAULT; + // + // Finish initialization of the control block. + // Copy Id string backwards to make sure that "SEGGER RTT" is not found in initializer memory (usually flash), + // as this would cause J-Link to "find" the control block at a wrong address. + // + RTT__DMB(); // Force order of memory accesses for cores that may perform out-of-order memory accesses + for (i = 0; i < sizeof(_aInitStr) - 1; ++i) { + p->acID[i] = _aInitStr[sizeof(_aInitStr) - 2 - i]; // Skip terminating \0 at the end of the array + } + RTT__DMB(); // Force order of memory accesses for cores that may perform out-of-order memory accesses +} + +/********************************************************************* +* +* _WriteBlocking() +* +* Function description +* Stores a specified number of characters in SEGGER RTT ring buffer +* and updates the associated write pointer which is periodically +* read by the host. +* The caller is responsible for managing the write chunk sizes as +* _WriteBlocking() will block until all data has been posted successfully. +* +* Parameters +* pRing Ring buffer to post to. +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* >= 0 - Number of bytes written into buffer. +*/ +static unsigned _WriteBlocking(SEGGER_RTT_BUFFER_UP* pRing, const char* pBuffer, unsigned NumBytes) { + unsigned NumBytesToWrite; + unsigned NumBytesWritten; + unsigned RdOff; + unsigned WrOff; + volatile char* pDst; + // + // Write data to buffer and handle wrap-around if necessary + // + NumBytesWritten = 0u; + WrOff = pRing->WrOff; + do { + RdOff = pRing->RdOff; // May be changed by host (debug probe) in the meantime + if (RdOff > WrOff) { + NumBytesToWrite = RdOff - WrOff - 1u; + } else { + NumBytesToWrite = pRing->SizeOfBuffer - (WrOff - RdOff + 1u); + } + NumBytesToWrite = MIN(NumBytesToWrite, (pRing->SizeOfBuffer - WrOff)); // Number of bytes that can be written until buffer wrap-around + NumBytesToWrite = MIN(NumBytesToWrite, NumBytes); + pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF; +#if SEGGER_RTT_MEMCPY_USE_BYTELOOP + NumBytesWritten += NumBytesToWrite; + NumBytes -= NumBytesToWrite; + WrOff += NumBytesToWrite; + while (NumBytesToWrite--) { + *pDst++ = *pBuffer++; + }; +#else + SEGGER_RTT_MEMCPY((void*)pDst, pBuffer, NumBytesToWrite); + NumBytesWritten += NumBytesToWrite; + pBuffer += NumBytesToWrite; + NumBytes -= NumBytesToWrite; + WrOff += NumBytesToWrite; +#endif + if (WrOff == pRing->SizeOfBuffer) { + WrOff = 0u; + } + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = WrOff; + } while (NumBytes); + return NumBytesWritten; +} + +/********************************************************************* +* +* _WriteNoCheck() +* +* Function description +* Stores a specified number of characters in SEGGER RTT ring buffer +* and updates the associated write pointer which is periodically +* read by the host. +* It is callers responsibility to make sure data actually fits in buffer. +* +* Parameters +* pRing Ring buffer to post to. +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Notes +* (1) If there might not be enough space in the "Up"-buffer, call _WriteBlocking +*/ +static void _WriteNoCheck(SEGGER_RTT_BUFFER_UP* pRing, const char* pData, unsigned NumBytes) { + unsigned NumBytesAtOnce; + unsigned WrOff; + unsigned Rem; + volatile char* pDst; + + WrOff = pRing->WrOff; + Rem = pRing->SizeOfBuffer - WrOff; + if (Rem > NumBytes) { + // + // All data fits before wrap around + // + pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF; +#if SEGGER_RTT_MEMCPY_USE_BYTELOOP + WrOff += NumBytes; + while (NumBytes--) { + *pDst++ = *pData++; + }; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = WrOff; +#else + SEGGER_RTT_MEMCPY((void*)pDst, pData, NumBytes); + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = WrOff + NumBytes; +#endif + } else { + // + // We reach the end of the buffer, so need to wrap around + // +#if SEGGER_RTT_MEMCPY_USE_BYTELOOP + pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF; + NumBytesAtOnce = Rem; + while (NumBytesAtOnce--) { + *pDst++ = *pData++; + }; + pDst = pRing->pBuffer + SEGGER_RTT_UNCACHED_OFF; + NumBytesAtOnce = NumBytes - Rem; + while (NumBytesAtOnce--) { + *pDst++ = *pData++; + }; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = NumBytes - Rem; +#else + NumBytesAtOnce = Rem; + pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF; + SEGGER_RTT_MEMCPY((void*)pDst, pData, NumBytesAtOnce); + NumBytesAtOnce = NumBytes - Rem; + pDst = pRing->pBuffer + SEGGER_RTT_UNCACHED_OFF; + SEGGER_RTT_MEMCPY((void*)pDst, pData + Rem, NumBytesAtOnce); + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = NumBytesAtOnce; +#endif + } +} + +/********************************************************************* +* +* _PostTerminalSwitch() +* +* Function description +* Switch terminal to the given terminal ID. It is the caller's +* responsibility to ensure the terminal ID is correct and there is +* enough space in the buffer for this to complete successfully. +* +* Parameters +* pRing Ring buffer to post to. +* TerminalId Terminal ID to switch to. +*/ +static void _PostTerminalSwitch(SEGGER_RTT_BUFFER_UP* pRing, unsigned char TerminalId) { + unsigned char ac[2]; + + ac[0] = 0xFFu; + ac[1] = _aTerminalId[TerminalId]; // Caller made already sure that TerminalId does not exceed our terminal limit + _WriteBlocking(pRing, (const char*)ac, 2u); +} + +/********************************************************************* +* +* _GetAvailWriteSpace() +* +* Function description +* Returns the number of bytes that can be written to the ring +* buffer without blocking. +* +* Parameters +* pRing Ring buffer to check. +* +* Return value +* Number of bytes that are free in the buffer. +*/ +static unsigned _GetAvailWriteSpace(SEGGER_RTT_BUFFER_UP* pRing) { + unsigned RdOff; + unsigned WrOff; + unsigned r; + // + // Avoid warnings regarding volatile access order. It's not a problem + // in this case, but dampen compiler enthusiasm. + // + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + if (RdOff <= WrOff) { + r = pRing->SizeOfBuffer - 1u - WrOff + RdOff; + } else { + r = RdOff - WrOff - 1u; + } + return r; +} + +/********************************************************************* +* +* Public code +* +********************************************************************** +*/ + +/********************************************************************* +* +* SEGGER_RTT_ReadUpBufferNoLock() +* +* Function description +* Reads characters from SEGGER real-time-terminal control block +* which have been previously stored by the application. +* Do not lock against interrupts and multiple access. +* Used to do the same operation that J-Link does, to transfer +* RTT data via other channels, such as TCP/IP or UART. +* +* Parameters +* BufferIndex Index of Up-buffer to be used. +* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-up-buffer to. +* BufferSize Size of the target application buffer. +* +* Return value +* Number of bytes that have been read. +* +* Additional information +* This function must not be called when J-Link might also do RTT. +*/ +unsigned SEGGER_RTT_ReadUpBufferNoLock(unsigned BufferIndex, void* pData, unsigned BufferSize) { + unsigned NumBytesRem; + unsigned NumBytesRead; + unsigned RdOff; + unsigned WrOff; + unsigned char* pBuffer; + SEGGER_RTT_BUFFER_UP* pRing; + volatile char* pSrc; + + INIT(); + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + pBuffer = (unsigned char*)pData; + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + NumBytesRead = 0u; + // + // Read from current read position to wrap-around of buffer, first + // + if (RdOff > WrOff) { + NumBytesRem = pRing->SizeOfBuffer - RdOff; + NumBytesRem = MIN(NumBytesRem, BufferSize); + pSrc = (pRing->pBuffer + RdOff) + SEGGER_RTT_UNCACHED_OFF; +#if SEGGER_RTT_MEMCPY_USE_BYTELOOP + NumBytesRead += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; + while (NumBytesRem--) { + *pBuffer++ = *pSrc++; + }; +#else + SEGGER_RTT_MEMCPY(pBuffer, (void*)pSrc, NumBytesRem); + NumBytesRead += NumBytesRem; + pBuffer += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; +#endif + // + // Handle wrap-around of buffer + // + if (RdOff == pRing->SizeOfBuffer) { + RdOff = 0u; + } + } + // + // Read remaining items of buffer + // + NumBytesRem = WrOff - RdOff; + NumBytesRem = MIN(NumBytesRem, BufferSize); + if (NumBytesRem > 0u) { + pSrc = (pRing->pBuffer + RdOff) + SEGGER_RTT_UNCACHED_OFF; +#if SEGGER_RTT_MEMCPY_USE_BYTELOOP + NumBytesRead += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; + while (NumBytesRem--) { + *pBuffer++ = *pSrc++; + }; +#else + SEGGER_RTT_MEMCPY(pBuffer, (void*)pSrc, NumBytesRem); + NumBytesRead += NumBytesRem; + pBuffer += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; +#endif + } + // + // Update read offset of buffer + // + if (NumBytesRead) { + pRing->RdOff = RdOff; + } + // + return NumBytesRead; +} + +/********************************************************************* +* +* SEGGER_RTT_ReadNoLock() +* +* Function description +* Reads characters from SEGGER real-time-terminal control block +* which have been previously stored by the host. +* Do not lock against interrupts and multiple access. +* +* Parameters +* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. +* BufferSize Size of the target application buffer. +* +* Return value +* Number of bytes that have been read. +*/ +unsigned SEGGER_RTT_ReadNoLock(unsigned BufferIndex, void* pData, unsigned BufferSize) { + unsigned NumBytesRem; + unsigned NumBytesRead; + unsigned RdOff; + unsigned WrOff; + unsigned char* pBuffer; + SEGGER_RTT_BUFFER_DOWN* pRing; + volatile char* pSrc; + // + INIT(); + pRing = (SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + pBuffer = (unsigned char*)pData; + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + NumBytesRead = 0u; + // + // Read from current read position to wrap-around of buffer, first + // + if (RdOff > WrOff) { + NumBytesRem = pRing->SizeOfBuffer - RdOff; + NumBytesRem = MIN(NumBytesRem, BufferSize); + pSrc = (pRing->pBuffer + RdOff) + SEGGER_RTT_UNCACHED_OFF; +#if SEGGER_RTT_MEMCPY_USE_BYTELOOP + NumBytesRead += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; + while (NumBytesRem--) { + *pBuffer++ = *pSrc++; + }; +#else + SEGGER_RTT_MEMCPY(pBuffer, (void*)pSrc, NumBytesRem); + NumBytesRead += NumBytesRem; + pBuffer += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; +#endif + // + // Handle wrap-around of buffer + // + if (RdOff == pRing->SizeOfBuffer) { + RdOff = 0u; + } + } + // + // Read remaining items of buffer + // + NumBytesRem = WrOff - RdOff; + NumBytesRem = MIN(NumBytesRem, BufferSize); + if (NumBytesRem > 0u) { + pSrc = (pRing->pBuffer + RdOff) + SEGGER_RTT_UNCACHED_OFF; +#if SEGGER_RTT_MEMCPY_USE_BYTELOOP + NumBytesRead += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; + while (NumBytesRem--) { + *pBuffer++ = *pSrc++; + }; +#else + SEGGER_RTT_MEMCPY(pBuffer, (void*)pSrc, NumBytesRem); + NumBytesRead += NumBytesRem; + pBuffer += NumBytesRem; + BufferSize -= NumBytesRem; + RdOff += NumBytesRem; +#endif + } + if (NumBytesRead) { + pRing->RdOff = RdOff; + } + // + return NumBytesRead; +} + +/********************************************************************* +* +* SEGGER_RTT_ReadUpBuffer +* +* Function description +* Reads characters from SEGGER real-time-terminal control block +* which have been previously stored by the application. +* Used to do the same operation that J-Link does, to transfer +* RTT data via other channels, such as TCP/IP or UART. +* +* Parameters +* BufferIndex Index of Up-buffer to be used. +* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-up-buffer to. +* BufferSize Size of the target application buffer. +* +* Return value +* Number of bytes that have been read. +* +* Additional information +* This function must not be called when J-Link might also do RTT. +* This function locks against all other RTT operations. I.e. during +* the read operation, writing is also locked. +* If only one consumer reads from the up buffer, +* call sEGGER_RTT_ReadUpBufferNoLock() instead. +*/ +unsigned SEGGER_RTT_ReadUpBuffer(unsigned BufferIndex, void* pBuffer, unsigned BufferSize) { + unsigned NumBytesRead; + + SEGGER_RTT_LOCK(); + // + // Call the non-locking read function + // + NumBytesRead = SEGGER_RTT_ReadUpBufferNoLock(BufferIndex, pBuffer, BufferSize); + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + // + return NumBytesRead; +} + +/********************************************************************* +* +* SEGGER_RTT_Read +* +* Function description +* Reads characters from SEGGER real-time-terminal control block +* which have been previously stored by the host. +* +* Parameters +* BufferIndex Index of Down-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to buffer provided by target application, to copy characters from RTT-down-buffer to. +* BufferSize Size of the target application buffer. +* +* Return value +* Number of bytes that have been read. +*/ +unsigned SEGGER_RTT_Read(unsigned BufferIndex, void* pBuffer, unsigned BufferSize) { + unsigned NumBytesRead; + + SEGGER_RTT_LOCK(); + // + // Call the non-locking read function + // + NumBytesRead = SEGGER_RTT_ReadNoLock(BufferIndex, pBuffer, BufferSize); + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + // + return NumBytesRead; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteWithOverwriteNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block. +* SEGGER_RTT_WriteWithOverwriteNoLock does not lock the application +* and overwrites data if the data does not fit into the buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, data is overwritten. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +* (3) Do not use SEGGER_RTT_WriteWithOverwriteNoLock if a J-Link +* connection reads RTT data. +*/ +void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + unsigned Avail; + volatile char* pDst; + // + // Get "to-host" ring buffer and copy some elements into local variables. + // + pData = (const char *)pBuffer; + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + // + // Check if we will overwrite data and need to adjust the RdOff. + // + if (pRing->WrOff == pRing->RdOff) { + Avail = pRing->SizeOfBuffer - 1u; + } else if ( pRing->WrOff < pRing->RdOff) { + Avail = pRing->RdOff - pRing->WrOff - 1u; + } else { + Avail = pRing->RdOff - pRing->WrOff - 1u + pRing->SizeOfBuffer; + } + if (NumBytes > Avail) { + pRing->RdOff += (NumBytes - Avail); + while (pRing->RdOff >= pRing->SizeOfBuffer) { + pRing->RdOff -= pRing->SizeOfBuffer; + } + } + // + // Write all data, no need to check the RdOff, but possibly handle multiple wrap-arounds + // + Avail = pRing->SizeOfBuffer - pRing->WrOff; + do { + if (Avail > NumBytes) { + // + // Last round + // + pDst = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF; +#if SEGGER_RTT_MEMCPY_USE_BYTELOOP + Avail = NumBytes; + while (NumBytes--) { + *pDst++ = *pData++; + }; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff += Avail; +#else + SEGGER_RTT_MEMCPY((void*)pDst, pData, NumBytes); + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff += NumBytes; +#endif + break; + } else { + // + // Wrap-around necessary, write until wrap-around and reset WrOff + // + pDst = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF; +#if SEGGER_RTT_MEMCPY_USE_BYTELOOP + NumBytes -= Avail; + while (Avail--) { + *pDst++ = *pData++; + }; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = 0; +#else + SEGGER_RTT_MEMCPY((void*)pDst, pData, Avail); + pData += Avail; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = 0; + NumBytes -= Avail; +#endif + Avail = (pRing->SizeOfBuffer - 1); + } + } while (NumBytes); +} + +/********************************************************************* +* +* SEGGER_RTT_WriteSkipNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* SEGGER_RTT_WriteSkipNoLock does not lock the application and +* skips all data, if the data does not fit into the buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* MUST be > 0!!! +* This is done for performance reasons, so no initial check has do be done. +* +* Return value +* 1: Data has been copied +* 0: No space, data has not been copied +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, all data is dropped. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +*/ +#if (RTT_USE_ASM == 0) +unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + unsigned Avail; + unsigned RdOff; + unsigned WrOff; + unsigned Rem; + volatile char* pDst; + // + // Cases: + // 1) RdOff <= WrOff => Space until wrap-around is sufficient + // 2) RdOff <= WrOff => Space after wrap-around needed (copy in 2 chunks) + // 3) RdOff < WrOff => No space in buf + // 4) RdOff > WrOff => Space is sufficient + // 5) RdOff > WrOff => No space in buf + // + // 1) is the most common case for large buffers and assuming that J-Link reads the data fast enough + // + pData = (const char *)pBuffer; + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + RdOff = pRing->RdOff; + WrOff = pRing->WrOff; + if (RdOff <= WrOff) { // Case 1), 2) or 3) + Avail = pRing->SizeOfBuffer - WrOff - 1u; // Space until wrap-around (assume 1 byte not usable for case that RdOff == 0) + if (Avail >= NumBytes) { // Case 1)? +CopyStraight: + pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF; + memcpy((void*)pDst, pData, NumBytes); + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = WrOff + NumBytes; + return 1; + } + Avail += RdOff; // Space incl. wrap-around + if (Avail >= NumBytes) { // Case 2? => If not, we have case 3) (does not fit) + Rem = pRing->SizeOfBuffer - WrOff; // Space until end of buffer + pDst = (pRing->pBuffer + WrOff) + SEGGER_RTT_UNCACHED_OFF; + memcpy((void*)pDst, pData, Rem); // Copy 1st chunk + NumBytes -= Rem; + // + // Special case: First check that assumed RdOff == 0 calculated that last element before wrap-around could not be used + // But 2nd check (considering space until wrap-around and until RdOff) revealed that RdOff is not 0, so we can use the last element + // In this case, we may use a copy straight until buffer end anyway without needing to copy 2 chunks + // Therefore, check if 2nd memcpy is necessary at all + // + if (NumBytes) { + pDst = pRing->pBuffer + SEGGER_RTT_UNCACHED_OFF; + memcpy((void*)pDst, pData + Rem, NumBytes); + } + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = NumBytes; + return 1; + } + } else { // Potential case 4) + Avail = RdOff - WrOff - 1u; + if (Avail >= NumBytes) { // Case 4)? => If not, we have case 5) (does not fit) + goto CopyStraight; + } + } + return 0; // No space in buffer +} +#endif + +/********************************************************************* +* +* SEGGER_RTT_WriteDownBufferNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block inside a buffer. +* SEGGER_RTT_WriteDownBufferNoLock does not lock the application. +* Used to do the same operation that J-Link does, to transfer +* RTT data from other channels, such as TCP/IP or UART. +* +* Parameters +* BufferIndex Index of "Down"-buffer to be used. +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Down"-buffer. +* +* Notes +* (1) Data is stored according to buffer flags. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +* +* Additional information +* This function must not be called when J-Link might also do RTT. +*/ +unsigned SEGGER_RTT_WriteDownBufferNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + unsigned Status; + unsigned Avail; + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + // + // Get "to-target" ring buffer. + // It is save to cast that to a "to-host" buffer. Up and Down buffer differ in volatility of offsets that might be modified by J-Link. + // + pData = (const char *)pBuffer; + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aDown[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + // + // How we output depends upon the mode... + // + switch (pRing->Flags) { + case SEGGER_RTT_MODE_NO_BLOCK_SKIP: + // + // If we are in skip mode and there is no space for the whole + // of this output, don't bother. + // + Avail = _GetAvailWriteSpace(pRing); + if (Avail < NumBytes) { + Status = 0u; + } else { + Status = NumBytes; + _WriteNoCheck(pRing, pData, NumBytes); + } + break; + case SEGGER_RTT_MODE_NO_BLOCK_TRIM: + // + // If we are in trim mode, trim to what we can output without blocking. + // + Avail = _GetAvailWriteSpace(pRing); + Status = Avail < NumBytes ? Avail : NumBytes; + _WriteNoCheck(pRing, pData, Status); + break; + case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: + // + // If we are in blocking mode, output everything. + // + Status = _WriteBlocking(pRing, pData, NumBytes); + break; + default: + Status = 0u; + break; + } + // + // Finish up. + // + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* SEGGER_RTT_WriteNoLock does not lock the application. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) Data is stored according to buffer flags. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +*/ +unsigned SEGGER_RTT_WriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + unsigned Status; + unsigned Avail; + const char* pData; + SEGGER_RTT_BUFFER_UP* pRing; + // + // Get "to-host" ring buffer. + // + pData = (const char *)pBuffer; + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + // + // How we output depends upon the mode... + // + switch (pRing->Flags) { + case SEGGER_RTT_MODE_NO_BLOCK_SKIP: + // + // If we are in skip mode and there is no space for the whole + // of this output, don't bother. + // + Avail = _GetAvailWriteSpace(pRing); + if (Avail < NumBytes) { + Status = 0u; + } else { + Status = NumBytes; + _WriteNoCheck(pRing, pData, NumBytes); + } + break; + case SEGGER_RTT_MODE_NO_BLOCK_TRIM: + // + // If we are in trim mode, trim to what we can output without blocking. + // + Avail = _GetAvailWriteSpace(pRing); + Status = Avail < NumBytes ? Avail : NumBytes; + _WriteNoCheck(pRing, pData, Status); + break; + case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: + // + // If we are in blocking mode, output everything. + // + Status = _WriteBlocking(pRing, pData, NumBytes); + break; + default: + Status = 0u; + break; + } + // + // Finish up. + // + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteDownBuffer +* +* Function description +* Stores a specified number of characters in SEGGER RTT control block in a buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Down"-buffer. +* +* Notes +* (1) Data is stored according to buffer flags. +* +* Additional information +* This function must not be called when J-Link might also do RTT. +* This function locks against all other RTT operations. I.e. during +* the write operation, writing from the application is also locked. +* If only one consumer writes to the down buffer, +* call SEGGER_RTT_WriteDownBufferNoLock() instead. +*/ +unsigned SEGGER_RTT_WriteDownBuffer(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + unsigned Status; + + INIT(); + SEGGER_RTT_LOCK(); + Status = SEGGER_RTT_WriteDownBufferNoLock(BufferIndex, pBuffer, NumBytes); // Call the non-locking write function + SEGGER_RTT_UNLOCK(); + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_Write +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) Data is stored according to buffer flags. +*/ +unsigned SEGGER_RTT_Write(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes) { + unsigned Status; + + INIT(); + SEGGER_RTT_LOCK(); + Status = SEGGER_RTT_WriteNoLock(BufferIndex, pBuffer, NumBytes); // Call the non-locking write function + SEGGER_RTT_UNLOCK(); + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_WriteString +* +* Function description +* Stores string in SEGGER RTT control block. +* This data is read by the host. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* s Pointer to string. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) Data is stored according to buffer flags. +* (2) String passed to this function has to be \0 terminated +* (3) \0 termination character is *not* stored in RTT buffer +*/ +unsigned SEGGER_RTT_WriteString(unsigned BufferIndex, const char* s) { + unsigned Len; + + Len = STRLEN(s); + return SEGGER_RTT_Write(BufferIndex, s, Len); +} + +/********************************************************************* +* +* SEGGER_RTT_PutCharSkipNoLock +* +* Function description +* Stores a single character/byte in SEGGER RTT buffer. +* SEGGER_RTT_PutCharSkipNoLock does not lock the application and +* skips the byte, if it does not fit into the buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* c Byte to be stored. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, the character is dropped. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +*/ + +unsigned SEGGER_RTT_PutCharSkipNoLock(unsigned BufferIndex, char c) { + SEGGER_RTT_BUFFER_UP* pRing; + unsigned WrOff; + unsigned Status; + volatile char* pDst; + // + // Get "to-host" ring buffer. + // + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + // + // Get write position and handle wrap-around if necessary + // + WrOff = pRing->WrOff + 1; + if (WrOff == pRing->SizeOfBuffer) { + WrOff = 0; + } + // + // Output byte if free space is available + // + if (WrOff != pRing->RdOff) { + pDst = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF; + *pDst = c; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = WrOff; + Status = 1; + } else { + Status = 0; + } + // + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_PutCharSkip +* +* Function description +* Stores a single character/byte in SEGGER RTT buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* c Byte to be stored. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, the character is dropped. +*/ + +unsigned SEGGER_RTT_PutCharSkip(unsigned BufferIndex, char c) { + SEGGER_RTT_BUFFER_UP* pRing; + unsigned WrOff; + unsigned Status; + volatile char* pDst; + // + // Prepare + // + INIT(); + SEGGER_RTT_LOCK(); + // + // Get "to-host" ring buffer. + // + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + // + // Get write position and handle wrap-around if necessary + // + WrOff = pRing->WrOff + 1; + if (WrOff == pRing->SizeOfBuffer) { + WrOff = 0; + } + // + // Output byte if free space is available + // + if (WrOff != pRing->RdOff) { + pDst = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF; + *pDst = c; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = WrOff; + Status = 1; + } else { + Status = 0; + } + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + // + return Status; +} + + /********************************************************************* +* +* SEGGER_RTT_PutChar +* +* Function description +* Stores a single character/byte in SEGGER RTT buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* c Byte to be stored. +* +* Return value +* Number of bytes which have been stored in the "Up"-buffer. +* +* Notes +* (1) Data is stored according to buffer flags. +*/ + +unsigned SEGGER_RTT_PutChar(unsigned BufferIndex, char c) { + SEGGER_RTT_BUFFER_UP* pRing; + unsigned WrOff; + unsigned Status; + volatile char* pDst; + // + // Prepare + // + INIT(); + SEGGER_RTT_LOCK(); + // + // Get "to-host" ring buffer. + // + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + // + // Get write position and handle wrap-around if necessary + // + WrOff = pRing->WrOff + 1; + if (WrOff == pRing->SizeOfBuffer) { + WrOff = 0; + } + // + // Wait for free space if mode is set to blocking + // + if (pRing->Flags == SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) { + while (WrOff == pRing->RdOff) { + ; + } + } + // + // Output byte if free space is available + // + if (WrOff != pRing->RdOff) { + pDst = (pRing->pBuffer + pRing->WrOff) + SEGGER_RTT_UNCACHED_OFF; + *pDst = c; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + pRing->WrOff = WrOff; + Status = 1; + } else { + Status = 0; + } + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_GetKey +* +* Function description +* Reads one character from the SEGGER RTT buffer. +* Host has previously stored data there. +* +* Return value +* < 0 - No character available (buffer empty). +* >= 0 - Character which has been read. (Possible values: 0 - 255) +* +* Notes +* (1) This function is only specified for accesses to RTT buffer 0. +*/ +int SEGGER_RTT_GetKey(void) { + char c; + int r; + + r = (int)SEGGER_RTT_Read(0u, &c, 1u); + if (r == 1) { + r = (int)(unsigned char)c; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_WaitKey +* +* Function description +* Waits until at least one character is avaible in the SEGGER RTT buffer. +* Once a character is available, it is read and this function returns. +* +* Return value +* >=0 - Character which has been read. +* +* Notes +* (1) This function is only specified for accesses to RTT buffer 0 +* (2) This function is blocking if no character is present in RTT buffer +*/ +int SEGGER_RTT_WaitKey(void) { + int r; + + do { + r = SEGGER_RTT_GetKey(); + } while (r < 0); + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_HasKey +* +* Function description +* Checks if at least one character for reading is available in the SEGGER RTT buffer. +* +* Return value +* == 0 - No characters are available to read. +* == 1 - At least one character is available. +* +* Notes +* (1) This function is only specified for accesses to RTT buffer 0 +*/ +int SEGGER_RTT_HasKey(void) { + SEGGER_RTT_BUFFER_DOWN* pRing; + unsigned RdOff; + int r; + + INIT(); + pRing = (SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[0] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + RdOff = pRing->RdOff; + if (RdOff != pRing->WrOff) { + r = 1; + } else { + r = 0; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_HasData +* +* Function description +* Check if there is data from the host in the given buffer. +* +* Return value: +* ==0: No data +* !=0: Data in buffer +* +*/ +unsigned SEGGER_RTT_HasData(unsigned BufferIndex) { + SEGGER_RTT_BUFFER_DOWN* pRing; + unsigned v; + + pRing = (SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + v = pRing->WrOff; + return v - pRing->RdOff; +} + +/********************************************************************* +* +* SEGGER_RTT_HasDataUp +* +* Function description +* Check if there is data remaining to be sent in the given buffer. +* +* Return value: +* ==0: No data +* !=0: Data in buffer +* +*/ +unsigned SEGGER_RTT_HasDataUp(unsigned BufferIndex) { + SEGGER_RTT_BUFFER_UP* pRing; + unsigned v; + + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + v = pRing->RdOff; + return pRing->WrOff - v; +} + +/********************************************************************* +* +* SEGGER_RTT_AllocDownBuffer +* +* Function description +* Run-time configuration of the next down-buffer (H->T). +* The next buffer, which is not used yet is configured. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. Buffer Index +* < 0 - Error +*/ +int SEGGER_RTT_AllocDownBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int BufferIndex; + volatile SEGGER_RTT_CB* pRTTCB; + + INIT(); + SEGGER_RTT_LOCK(); + pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + BufferIndex = 0; + do { + if (pRTTCB->aDown[BufferIndex].pBuffer == NULL) { + break; + } + BufferIndex++; + } while (BufferIndex < pRTTCB->MaxNumDownBuffers); + if (BufferIndex < pRTTCB->MaxNumDownBuffers) { + pRTTCB->aDown[BufferIndex].sName = sName; + pRTTCB->aDown[BufferIndex].pBuffer = (char*)pBuffer; + pRTTCB->aDown[BufferIndex].SizeOfBuffer = BufferSize; + pRTTCB->aDown[BufferIndex].RdOff = 0u; + pRTTCB->aDown[BufferIndex].WrOff = 0u; + pRTTCB->aDown[BufferIndex].Flags = Flags; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + } else { + BufferIndex = -1; + } + SEGGER_RTT_UNLOCK(); + return BufferIndex; +} + +/********************************************************************* +* +* SEGGER_RTT_AllocUpBuffer +* +* Function description +* Run-time configuration of the next up-buffer (T->H). +* The next buffer, which is not used yet is configured. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. Buffer Index +* < 0 - Error +*/ +int SEGGER_RTT_AllocUpBuffer(const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int BufferIndex; + volatile SEGGER_RTT_CB* pRTTCB; + + INIT(); + SEGGER_RTT_LOCK(); + pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + BufferIndex = 0; + do { + if (pRTTCB->aUp[BufferIndex].pBuffer == NULL) { + break; + } + BufferIndex++; + } while (BufferIndex < pRTTCB->MaxNumUpBuffers); + if (BufferIndex < pRTTCB->MaxNumUpBuffers) { + pRTTCB->aUp[BufferIndex].sName = sName; + pRTTCB->aUp[BufferIndex].pBuffer = (char*)pBuffer; + pRTTCB->aUp[BufferIndex].SizeOfBuffer = BufferSize; + pRTTCB->aUp[BufferIndex].RdOff = 0u; + pRTTCB->aUp[BufferIndex].WrOff = 0u; + pRTTCB->aUp[BufferIndex].Flags = Flags; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + } else { + BufferIndex = -1; + } + SEGGER_RTT_UNLOCK(); + return BufferIndex; +} + +/********************************************************************* +* +* SEGGER_RTT_ConfigUpBuffer +* +* Function description +* Run-time configuration of a specific up-buffer (T->H). +* Buffer to be configured is specified by index. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* BufferIndex Index of the buffer to configure. +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 - O.K. +* < 0 - Error +* +* Additional information +* Buffer 0 is configured on compile-time. +* May only be called once per buffer. +* Buffer name and flags can be reconfigured using the appropriate functions. +*/ +int SEGGER_RTT_ConfigUpBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int r; + volatile SEGGER_RTT_CB* pRTTCB; + volatile SEGGER_RTT_BUFFER_UP* pUp; + + INIT(); + pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + if (BufferIndex < SEGGER_RTT_MAX_NUM_UP_BUFFERS) { + SEGGER_RTT_LOCK(); + pUp = &pRTTCB->aUp[BufferIndex]; + if (BufferIndex) { + pUp->sName = sName; + pUp->pBuffer = (char*)pBuffer; + pUp->SizeOfBuffer = BufferSize; + pUp->RdOff = 0u; + pUp->WrOff = 0u; + } + pUp->Flags = Flags; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_ConfigDownBuffer +* +* Function description +* Run-time configuration of a specific down-buffer (H->T). +* Buffer to be configured is specified by index. +* This includes: Buffer address, size, name, flags, ... +* +* Parameters +* BufferIndex Index of the buffer to configure. +* sName Pointer to a constant name string. +* pBuffer Pointer to a buffer to be used. +* BufferSize Size of the buffer. +* Flags Operating modes. Define behavior if buffer is full (not enough space for entire message). +* +* Return value +* >= 0 O.K. +* < 0 Error +* +* Additional information +* Buffer 0 is configured on compile-time. +* May only be called once per buffer. +* Buffer name and flags can be reconfigured using the appropriate functions. +*/ +int SEGGER_RTT_ConfigDownBuffer(unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags) { + int r; + volatile SEGGER_RTT_CB* pRTTCB; + volatile SEGGER_RTT_BUFFER_DOWN* pDown; + + INIT(); + pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + if (BufferIndex < SEGGER_RTT_MAX_NUM_DOWN_BUFFERS) { + SEGGER_RTT_LOCK(); + pDown = &pRTTCB->aDown[BufferIndex]; + if (BufferIndex) { + pDown->sName = sName; + pDown->pBuffer = (char*)pBuffer; + pDown->SizeOfBuffer = BufferSize; + pDown->RdOff = 0u; + pDown->WrOff = 0u; + } + pDown->Flags = Flags; + RTT__DMB(); // Force data write to be complete before writing the , in case CPU is allowed to change the order of memory accesses + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_SetNameUpBuffer +* +* Function description +* Run-time configuration of a specific up-buffer name (T->H). +* Buffer to be configured is specified by index. +* +* Parameters +* BufferIndex Index of the buffer to renamed. +* sName Pointer to a constant name string. +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_SetNameUpBuffer(unsigned BufferIndex, const char* sName) { + int r; + volatile SEGGER_RTT_CB* pRTTCB; + volatile SEGGER_RTT_BUFFER_UP* pUp; + + INIT(); + pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + if (BufferIndex < SEGGER_RTT_MAX_NUM_UP_BUFFERS) { + SEGGER_RTT_LOCK(); + pUp = &pRTTCB->aUp[BufferIndex]; + pUp->sName = sName; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_SetNameDownBuffer +* +* Function description +* Run-time configuration of a specific Down-buffer name (T->H). +* Buffer to be configured is specified by index. +* +* Parameters +* BufferIndex Index of the buffer to renamed. +* sName Pointer to a constant name string. +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_SetNameDownBuffer(unsigned BufferIndex, const char* sName) { + int r; + volatile SEGGER_RTT_CB* pRTTCB; + volatile SEGGER_RTT_BUFFER_DOWN* pDown; + + INIT(); + pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + if (BufferIndex < SEGGER_RTT_MAX_NUM_DOWN_BUFFERS) { + SEGGER_RTT_LOCK(); + pDown = &pRTTCB->aDown[BufferIndex]; + pDown->sName = sName; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_SetFlagsUpBuffer +* +* Function description +* Run-time configuration of specific up-buffer flags (T->H). +* Buffer to be configured is specified by index. +* +* Parameters +* BufferIndex Index of the buffer. +* Flags Flags to set for the buffer. +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_SetFlagsUpBuffer(unsigned BufferIndex, unsigned Flags) { + int r; + volatile SEGGER_RTT_CB* pRTTCB; + volatile SEGGER_RTT_BUFFER_UP* pUp; + + INIT(); + pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + if (BufferIndex < SEGGER_RTT_MAX_NUM_UP_BUFFERS) { + SEGGER_RTT_LOCK(); + pUp = &pRTTCB->aUp[BufferIndex]; + pUp->Flags = Flags; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_SetFlagsDownBuffer +* +* Function description +* Run-time configuration of specific Down-buffer flags (T->H). +* Buffer to be configured is specified by index. +* +* Parameters +* BufferIndex Index of the buffer to renamed. +* Flags Flags to set for the buffer. +* +* Return value +* >= 0 O.K. +* < 0 Error +*/ +int SEGGER_RTT_SetFlagsDownBuffer(unsigned BufferIndex, unsigned Flags) { + int r; + volatile SEGGER_RTT_CB* pRTTCB; + volatile SEGGER_RTT_BUFFER_DOWN* pDown; + + INIT(); + pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + if (BufferIndex < SEGGER_RTT_MAX_NUM_DOWN_BUFFERS) { + SEGGER_RTT_LOCK(); + pDown = &pRTTCB->aDown[BufferIndex]; + pDown->Flags = Flags; + SEGGER_RTT_UNLOCK(); + r = 0; + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_Init +* +* Function description +* Initializes the RTT Control Block. +* Should be used in RAM targets, at start of the application. +* +*/ +void SEGGER_RTT_Init (void) { + _DoInit(); +} + +/********************************************************************* +* +* SEGGER_RTT_SetTerminal +* +* Function description +* Sets the terminal to be used for output on channel 0. +* +* Parameters +* TerminalId Index of the terminal. +* +* Return value +* >= 0 O.K. +* < 0 Error (e.g. if RTT is configured for non-blocking mode and there was no space in the buffer to set the new terminal Id) +* +* Notes +* (1) Buffer 0 is always reserved for terminal I/O, so we can use index 0 here, fixed +*/ +int SEGGER_RTT_SetTerminal (unsigned char TerminalId) { + unsigned char ac[2]; + SEGGER_RTT_BUFFER_UP* pRing; + unsigned Avail; + int r; + + INIT(); + r = 0; + ac[0] = 0xFFu; + if (TerminalId < sizeof(_aTerminalId)) { // We only support a certain number of channels + ac[1] = _aTerminalId[TerminalId]; + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[0] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + SEGGER_RTT_LOCK(); // Lock to make sure that no other task is writing into buffer, while we are and number of free bytes in buffer does not change downwards after checking and before writing + if ((pRing->Flags & SEGGER_RTT_MODE_MASK) == SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL) { + _ActiveTerminal = TerminalId; + _WriteBlocking(pRing, (const char*)ac, 2u); + } else { // Skipping mode or trim mode? => We cannot trim this command so handling is the same for both modes + Avail = _GetAvailWriteSpace(pRing); + if (Avail >= 2) { + _ActiveTerminal = TerminalId; // Only change active terminal in case of success + _WriteNoCheck(pRing, (const char*)ac, 2u); + } else { + r = -1; + } + } + SEGGER_RTT_UNLOCK(); + } else { + r = -1; + } + return r; +} + +/********************************************************************* +* +* SEGGER_RTT_TerminalOut +* +* Function description +* Writes a string to the given terminal +* without changing the terminal for channel 0. +* +* Parameters +* TerminalId Index of the terminal. +* s String to be printed on the terminal. +* +* Return value +* >= 0 - Number of bytes written. +* < 0 - Error. +* +*/ +int SEGGER_RTT_TerminalOut (unsigned char TerminalId, const char* s) { + int Status; + unsigned FragLen; + unsigned Avail; + SEGGER_RTT_BUFFER_UP* pRing; + // + INIT(); + // + // Validate terminal ID. + // + if (TerminalId < (char)sizeof(_aTerminalId)) { // We only support a certain number of channels + // + // Get "to-host" ring buffer. + // + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[0] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + // + // Need to be able to change terminal, write data, change back. + // Compute the fixed and variable sizes. + // + FragLen = STRLEN(s); + // + // How we output depends upon the mode... + // + SEGGER_RTT_LOCK(); + Avail = _GetAvailWriteSpace(pRing); + switch (pRing->Flags & SEGGER_RTT_MODE_MASK) { + case SEGGER_RTT_MODE_NO_BLOCK_SKIP: + // + // If we are in skip mode and there is no space for the whole + // of this output, don't bother switching terminals at all. + // + if (Avail < (FragLen + 4u)) { + Status = 0; + } else { + _PostTerminalSwitch(pRing, TerminalId); + Status = (int)_WriteBlocking(pRing, s, FragLen); + _PostTerminalSwitch(pRing, _ActiveTerminal); + } + break; + case SEGGER_RTT_MODE_NO_BLOCK_TRIM: + // + // If we are in trim mode and there is not enough space for everything, + // trim the output but always include the terminal switch. If no room + // for terminal switch, skip that totally. + // + if (Avail < 4u) { + Status = -1; + } else { + _PostTerminalSwitch(pRing, TerminalId); + Status = (int)_WriteBlocking(pRing, s, (FragLen < (Avail - 4u)) ? FragLen : (Avail - 4u)); + _PostTerminalSwitch(pRing, _ActiveTerminal); + } + break; + case SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL: + // + // If we are in blocking mode, output everything. + // + _PostTerminalSwitch(pRing, TerminalId); + Status = (int)_WriteBlocking(pRing, s, FragLen); + _PostTerminalSwitch(pRing, _ActiveTerminal); + break; + default: + Status = -1; + break; + } + // + // Finish up. + // + SEGGER_RTT_UNLOCK(); + } else { + Status = -1; + } + return Status; +} + +/********************************************************************* +* +* SEGGER_RTT_GetAvailWriteSpace +* +* Function description +* Returns the number of bytes available in the ring buffer. +* +* Parameters +* BufferIndex Index of the up buffer. +* +* Return value +* Number of bytes that are free in the selected up buffer. +*/ +unsigned SEGGER_RTT_GetAvailWriteSpace (unsigned BufferIndex) { + SEGGER_RTT_BUFFER_UP* pRing; + + pRing = (SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[BufferIndex] + SEGGER_RTT_UNCACHED_OFF); // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + return _GetAvailWriteSpace(pRing); +} + + +/********************************************************************* +* +* SEGGER_RTT_GetBytesInBuffer() +* +* Function description +* Returns the number of bytes currently used in the up buffer. +* +* Parameters +* BufferIndex Index of the up buffer. +* +* Return value +* Number of bytes that are used in the buffer. +*/ +unsigned SEGGER_RTT_GetBytesInBuffer(unsigned BufferIndex) { + unsigned RdOff; + unsigned WrOff; + unsigned r; + volatile SEGGER_RTT_CB* pRTTCB; + // + // Avoid warnings regarding volatile access order. It's not a problem + // in this case, but dampen compiler enthusiasm. + // + pRTTCB = (volatile SEGGER_RTT_CB*)((unsigned char*)&_SEGGER_RTT + SEGGER_RTT_UNCACHED_OFF); // Access RTTCB uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + RdOff = pRTTCB->aUp[BufferIndex].RdOff; + WrOff = pRTTCB->aUp[BufferIndex].WrOff; + if (RdOff <= WrOff) { + r = WrOff - RdOff; + } else { + r = pRTTCB->aUp[BufferIndex].SizeOfBuffer - (WrOff - RdOff); + } + return r; +} + +/*************************** End of file ****************************/ diff --git a/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT.h b/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT.h new file mode 100644 index 0000000..a636f0a --- /dev/null +++ b/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT.h @@ -0,0 +1,493 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH * +* The Embedded Experts * +********************************************************************** +* * +* (c) 1995 - 2021 SEGGER Microcontroller GmbH * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* condition is met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this condition and the following disclaimer. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 7.58c * +* * +********************************************************************** + +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT.h +Purpose : Implementation of SEGGER real-time transfer which allows + real-time communication on targets which support debugger + memory accesses while the CPU is running. +Revision: $Rev: 24346 $ +---------------------------------------------------------------------- +*/ + +#ifndef SEGGER_RTT_H +#define SEGGER_RTT_H + +#include "../Config/SEGGER_RTT_Conf.h" + +/********************************************************************* +* +* Defines, defaults +* +********************************************************************** +*/ + +#ifndef RTT_USE_ASM + // + // Some cores support out-of-order memory accesses (reordering of memory accesses in the core) + // For such cores, we need to define a memory barrier to guarantee the order of certain accesses to the RTT ring buffers. + // Needed for: + // Cortex-M7 (ARMv7-M) + // Cortex-M23 (ARM-v8M) + // Cortex-M33 (ARM-v8M) + // Cortex-A/R (ARM-v7A/R) + // + // We do not explicitly check for "Embedded Studio" as the compiler in use determines what we support. + // You can use an external toolchain like IAR inside ES. So there is no point in checking for "Embedded Studio" + // + #if (defined __CROSSWORKS_ARM) // Rowley Crossworks + #define _CC_HAS_RTT_ASM_SUPPORT 1 + #if (defined __ARM_ARCH_7M__) // Cortex-M3 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #elif (defined __ARM_ARCH_7EM__) // Cortex-M4/M7 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #elif (defined __ARM_ARCH_8M_BASE__) // Cortex-M23 + #define _CORE_HAS_RTT_ASM_SUPPORT 0 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #elif (defined __ARM_ARCH_8M_MAIN__) // Cortex-M33 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #else + #define _CORE_HAS_RTT_ASM_SUPPORT 0 + #endif + #elif (defined __ARMCC_VERSION) + // + // ARM compiler + // ARM compiler V6.0 and later is clang based. + // Our ASM part is compatible to clang. + // + #if (__ARMCC_VERSION >= 6000000) + #define _CC_HAS_RTT_ASM_SUPPORT 1 + #else + #define _CC_HAS_RTT_ASM_SUPPORT 0 + #endif + #if (defined __ARM_ARCH_6M__) // Cortex-M0 / M1 + #define _CORE_HAS_RTT_ASM_SUPPORT 0 // No ASM support for this architecture + #elif (defined __ARM_ARCH_7M__) // Cortex-M3 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #elif (defined __ARM_ARCH_7EM__) // Cortex-M4/M7 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #elif (defined __ARM_ARCH_8M_BASE__) // Cortex-M23 + #define _CORE_HAS_RTT_ASM_SUPPORT 0 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #elif (defined __ARM_ARCH_8M_MAIN__) // Cortex-M33 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #elif ((defined __ARM_ARCH_7A__) || (defined __ARM_ARCH_7R__)) // Cortex-A/R 32-bit ARMv7-A/R + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #else + #define _CORE_HAS_RTT_ASM_SUPPORT 0 + #endif + #elif ((defined __GNUC__) || (defined __clang__)) + // + // GCC / Clang + // + #define _CC_HAS_RTT_ASM_SUPPORT 1 + // ARM 7/9: __ARM_ARCH_5__ / __ARM_ARCH_5E__ / __ARM_ARCH_5T__ / __ARM_ARCH_5T__ / __ARM_ARCH_5TE__ + #if (defined __ARM_ARCH_7M__) // Cortex-M3 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #elif (defined __ARM_ARCH_7EM__) // Cortex-M4/M7 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #define _CORE_NEEDS_DMB 1 // Only Cortex-M7 needs a DMB but we cannot distinguish M4 and M7 here... + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #elif (defined __ARM_ARCH_8M_BASE__) // Cortex-M23 + #define _CORE_HAS_RTT_ASM_SUPPORT 0 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #elif (defined __ARM_ARCH_8M_MAIN__) // Cortex-M33 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #elif ((defined __ARM_ARCH_7A__) || (defined __ARM_ARCH_7R__)) // Cortex-A/R 32-bit ARMv7-A/R + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() __asm volatile ("dmb\n" : : :); + #else + #define _CORE_HAS_RTT_ASM_SUPPORT 0 + #endif + #elif ((defined __IASMARM__) || (defined __ICCARM__)) + // + // IAR assembler/compiler + // + #define _CC_HAS_RTT_ASM_SUPPORT 1 + #if (__VER__ < 6300000) + #define VOLATILE + #else + #define VOLATILE volatile + #endif + #if (defined __ARM7M__) // Needed for old versions that do not know the define yet + #if (__CORE__ == __ARM7M__) // Cortex-M3 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #endif + #endif + #if (defined __ARM7EM__) + #if (__CORE__ == __ARM7EM__) // Cortex-M4/M7 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() asm VOLATILE ("DMB"); + #endif + #endif + #if (defined __ARM8M_BASELINE__) + #if (__CORE__ == __ARM8M_BASELINE__) // Cortex-M23 + #define _CORE_HAS_RTT_ASM_SUPPORT 0 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() asm VOLATILE ("DMB"); + #endif + #endif + #if (defined __ARM8M_MAINLINE__) + #if (__CORE__ == __ARM8M_MAINLINE__) // Cortex-M33 + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() asm VOLATILE ("DMB"); + #endif + #endif + #if (defined __ARM8EM_MAINLINE__) + #if (__CORE__ == __ARM8EM_MAINLINE__) // Cortex-??? + #define _CORE_HAS_RTT_ASM_SUPPORT 1 + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() asm VOLATILE ("DMB"); + #endif + #endif + #if (defined __ARM7A__) + #if (__CORE__ == __ARM7A__) // Cortex-A 32-bit ARMv7-A + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() asm VOLATILE ("DMB"); + #endif + #endif + #if (defined __ARM7R__) + #if (__CORE__ == __ARM7R__) // Cortex-R 32-bit ARMv7-R + #define _CORE_NEEDS_DMB 1 + #define RTT__DMB() asm VOLATILE ("DMB"); + #endif + #endif +// TBD: __ARM8A__ => Cortex-A 64-bit ARMv8-A +// TBD: __ARM8R__ => Cortex-R 64-bit ARMv8-R + #else + // + // Other compilers + // + #define _CC_HAS_RTT_ASM_SUPPORT 0 + #define _CORE_HAS_RTT_ASM_SUPPORT 0 + #endif + // + // If IDE and core support the ASM version, enable ASM version by default + // + #ifndef _CORE_HAS_RTT_ASM_SUPPORT + #define _CORE_HAS_RTT_ASM_SUPPORT 0 // Default for unknown cores + #endif + #if (_CC_HAS_RTT_ASM_SUPPORT && _CORE_HAS_RTT_ASM_SUPPORT) + #define RTT_USE_ASM (1) + #else + #define RTT_USE_ASM (0) + #endif +#endif + +#ifndef _CORE_NEEDS_DMB + #define _CORE_NEEDS_DMB 0 +#endif + +#ifndef RTT__DMB + #if _CORE_NEEDS_DMB + #error "Don't know how to place inline assembly for DMB" + #else + #define RTT__DMB() + #endif +#endif + +#ifndef SEGGER_RTT_CPU_CACHE_LINE_SIZE + #define SEGGER_RTT_CPU_CACHE_LINE_SIZE (0) // On most target systems where RTT is used, we do not have a CPU cache, therefore 0 is a good default here +#endif + +#ifndef SEGGER_RTT_UNCACHED_OFF + #if SEGGER_RTT_CPU_CACHE_LINE_SIZE + #error "SEGGER_RTT_UNCACHED_OFF must be defined when setting SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0" + #else + #define SEGGER_RTT_UNCACHED_OFF (0) + #endif +#endif +#if RTT_USE_ASM + #if SEGGER_RTT_CPU_CACHE_LINE_SIZE + #error "RTT_USE_ASM is not available if SEGGER_RTT_CPU_CACHE_LINE_SIZE != 0" + #endif +#endif + +#ifndef SEGGER_RTT_ASM // defined when SEGGER_RTT.h is included from assembly file +#include +#include + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ + +// +// Determine how much we must pad the control block to make it a multiple of a cache line in size +// Assuming: U8 = 1B +// U16 = 2B +// U32 = 4B +// U8/U16/U32* = 4B +// +#if SEGGER_RTT_CPU_CACHE_LINE_SIZE // Avoid division by zero in case we do not have any cache + #define SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(NumBytes) (((NumBytes + SEGGER_RTT_CPU_CACHE_LINE_SIZE - 1) / SEGGER_RTT_CPU_CACHE_LINE_SIZE) * SEGGER_RTT_CPU_CACHE_LINE_SIZE) +#else + #define SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(NumBytes) (NumBytes) +#endif +#define SEGGER_RTT__CB_SIZE (16 + 4 + 4 + (SEGGER_RTT_MAX_NUM_UP_BUFFERS * 24) + (SEGGER_RTT_MAX_NUM_DOWN_BUFFERS * 24)) +#define SEGGER_RTT__CB_PADDING (SEGGER_RTT__ROUND_UP_2_CACHE_LINE_SIZE(SEGGER_RTT__CB_SIZE) - SEGGER_RTT__CB_SIZE) + +/********************************************************************* +* +* Types +* +********************************************************************** +*/ + +// +// Description for a circular buffer (also called "ring buffer") +// which is used as up-buffer (T->H) +// +typedef struct { + const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" + char* pBuffer; // Pointer to start of buffer + unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. + unsigned WrOff; // Position of next item to be written by either target. + volatile unsigned RdOff; // Position of next item to be read by host. Must be volatile since it may be modified by host. + unsigned Flags; // Contains configuration flags +} SEGGER_RTT_BUFFER_UP; + +// +// Description for a circular buffer (also called "ring buffer") +// which is used as down-buffer (H->T) +// +typedef struct { + const char* sName; // Optional name. Standard names so far are: "Terminal", "SysView", "J-Scope_t4i4" + char* pBuffer; // Pointer to start of buffer + unsigned SizeOfBuffer; // Buffer size in bytes. Note that one byte is lost, as this implementation does not fill up the buffer in order to avoid the problem of being unable to distinguish between full and empty. + volatile unsigned WrOff; // Position of next item to be written by host. Must be volatile since it may be modified by host. + unsigned RdOff; // Position of next item to be read by target (down-buffer). + unsigned Flags; // Contains configuration flags +} SEGGER_RTT_BUFFER_DOWN; + +// +// RTT control block which describes the number of buffers available +// as well as the configuration for each buffer +// +// +typedef struct { + char acID[16]; // Initialized to "SEGGER RTT" + int MaxNumUpBuffers; // Initialized to SEGGER_RTT_MAX_NUM_UP_BUFFERS (type. 2) + int MaxNumDownBuffers; // Initialized to SEGGER_RTT_MAX_NUM_DOWN_BUFFERS (type. 2) + SEGGER_RTT_BUFFER_UP aUp[SEGGER_RTT_MAX_NUM_UP_BUFFERS]; // Up buffers, transferring information up from target via debug probe to host + SEGGER_RTT_BUFFER_DOWN aDown[SEGGER_RTT_MAX_NUM_DOWN_BUFFERS]; // Down buffers, transferring information down from host via debug probe to target +#if SEGGER_RTT__CB_PADDING + unsigned char aDummy[SEGGER_RTT__CB_PADDING]; +#endif +} SEGGER_RTT_CB; + +/********************************************************************* +* +* Global data +* +********************************************************************** +*/ +extern SEGGER_RTT_CB _SEGGER_RTT; + +/********************************************************************* +* +* RTT API functions +* +********************************************************************** +*/ +#ifdef __cplusplus + extern "C" { +#endif +int SEGGER_RTT_AllocDownBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_AllocUpBuffer (const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_ConfigUpBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_ConfigDownBuffer (unsigned BufferIndex, const char* sName, void* pBuffer, unsigned BufferSize, unsigned Flags); +int SEGGER_RTT_GetKey (void); +unsigned SEGGER_RTT_HasData (unsigned BufferIndex); +int SEGGER_RTT_HasKey (void); +unsigned SEGGER_RTT_HasDataUp (unsigned BufferIndex); +void SEGGER_RTT_Init (void); +unsigned SEGGER_RTT_Read (unsigned BufferIndex, void* pBuffer, unsigned BufferSize); +unsigned SEGGER_RTT_ReadNoLock (unsigned BufferIndex, void* pData, unsigned BufferSize); +int SEGGER_RTT_SetNameDownBuffer (unsigned BufferIndex, const char* sName); +int SEGGER_RTT_SetNameUpBuffer (unsigned BufferIndex, const char* sName); +int SEGGER_RTT_SetFlagsDownBuffer (unsigned BufferIndex, unsigned Flags); +int SEGGER_RTT_SetFlagsUpBuffer (unsigned BufferIndex, unsigned Flags); +int SEGGER_RTT_WaitKey (void); +unsigned SEGGER_RTT_Write (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteSkipNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_ASM_WriteSkipNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteString (unsigned BufferIndex, const char* s); +void SEGGER_RTT_WriteWithOverwriteNoLock(unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_PutChar (unsigned BufferIndex, char c); +unsigned SEGGER_RTT_PutCharSkip (unsigned BufferIndex, char c); +unsigned SEGGER_RTT_PutCharSkipNoLock (unsigned BufferIndex, char c); +unsigned SEGGER_RTT_GetAvailWriteSpace (unsigned BufferIndex); +unsigned SEGGER_RTT_GetBytesInBuffer (unsigned BufferIndex); +// +// Function macro for performance optimization +// +#define SEGGER_RTT_HASDATA(n) (((SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[n] + SEGGER_RTT_UNCACHED_OFF))->WrOff - ((SEGGER_RTT_BUFFER_DOWN*)((char*)&_SEGGER_RTT.aDown[n] + SEGGER_RTT_UNCACHED_OFF))->RdOff) + +#if RTT_USE_ASM + #define SEGGER_RTT_WriteSkipNoLock SEGGER_RTT_ASM_WriteSkipNoLock +#endif + +/********************************************************************* +* +* RTT transfer functions to send RTT data via other channels. +* +********************************************************************** +*/ +unsigned SEGGER_RTT_ReadUpBuffer (unsigned BufferIndex, void* pBuffer, unsigned BufferSize); +unsigned SEGGER_RTT_ReadUpBufferNoLock (unsigned BufferIndex, void* pData, unsigned BufferSize); +unsigned SEGGER_RTT_WriteDownBuffer (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); +unsigned SEGGER_RTT_WriteDownBufferNoLock (unsigned BufferIndex, const void* pBuffer, unsigned NumBytes); + +#define SEGGER_RTT_HASDATA_UP(n) (((SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[n] + SEGGER_RTT_UNCACHED_OFF))->WrOff - ((SEGGER_RTT_BUFFER_UP*)((char*)&_SEGGER_RTT.aUp[n] + SEGGER_RTT_UNCACHED_OFF))->RdOff) // Access uncached to make sure we see changes made by the J-Link side and all of our changes go into HW directly + +/********************************************************************* +* +* RTT "Terminal" API functions +* +********************************************************************** +*/ +int SEGGER_RTT_SetTerminal (unsigned char TerminalId); +int SEGGER_RTT_TerminalOut (unsigned char TerminalId, const char* s); + +/********************************************************************* +* +* RTT printf functions (require SEGGER_RTT_printf.c) +* +********************************************************************** +*/ +int SEGGER_RTT_printf(unsigned BufferIndex, const char * sFormat, ...); +int SEGGER_RTT_vprintf(unsigned BufferIndex, const char * sFormat, va_list * pParamList); + +#ifdef __cplusplus + } +#endif + +#endif // ifndef(SEGGER_RTT_ASM) + +/********************************************************************* +* +* Defines +* +********************************************************************** +*/ + +// +// Operating modes. Define behavior if buffer is full (not enough space for entire message) +// +#define SEGGER_RTT_MODE_NO_BLOCK_SKIP (0) // Skip. Do not block, output nothing. (Default) +#define SEGGER_RTT_MODE_NO_BLOCK_TRIM (1) // Trim: Do not block, output as much as fits. +#define SEGGER_RTT_MODE_BLOCK_IF_FIFO_FULL (2) // Block: Wait until there is space in the buffer. +#define SEGGER_RTT_MODE_MASK (3) + +// +// Control sequences, based on ANSI. +// Can be used to control color, and clear the screen +// +#define RTT_CTRL_RESET "\x1B[0m" // Reset to default colors +#define RTT_CTRL_CLEAR "\x1B[2J" // Clear screen, reposition cursor to top left + +#define RTT_CTRL_TEXT_BLACK "\x1B[2;30m" +#define RTT_CTRL_TEXT_RED "\x1B[2;31m" +#define RTT_CTRL_TEXT_GREEN "\x1B[2;32m" +#define RTT_CTRL_TEXT_YELLOW "\x1B[2;33m" +#define RTT_CTRL_TEXT_BLUE "\x1B[2;34m" +#define RTT_CTRL_TEXT_MAGENTA "\x1B[2;35m" +#define RTT_CTRL_TEXT_CYAN "\x1B[2;36m" +#define RTT_CTRL_TEXT_WHITE "\x1B[2;37m" + +#define RTT_CTRL_TEXT_BRIGHT_BLACK "\x1B[1;30m" +#define RTT_CTRL_TEXT_BRIGHT_RED "\x1B[1;31m" +#define RTT_CTRL_TEXT_BRIGHT_GREEN "\x1B[1;32m" +#define RTT_CTRL_TEXT_BRIGHT_YELLOW "\x1B[1;33m" +#define RTT_CTRL_TEXT_BRIGHT_BLUE "\x1B[1;34m" +#define RTT_CTRL_TEXT_BRIGHT_MAGENTA "\x1B[1;35m" +#define RTT_CTRL_TEXT_BRIGHT_CYAN "\x1B[1;36m" +#define RTT_CTRL_TEXT_BRIGHT_WHITE "\x1B[1;37m" + +#define RTT_CTRL_BG_BLACK "\x1B[24;40m" +#define RTT_CTRL_BG_RED "\x1B[24;41m" +#define RTT_CTRL_BG_GREEN "\x1B[24;42m" +#define RTT_CTRL_BG_YELLOW "\x1B[24;43m" +#define RTT_CTRL_BG_BLUE "\x1B[24;44m" +#define RTT_CTRL_BG_MAGENTA "\x1B[24;45m" +#define RTT_CTRL_BG_CYAN "\x1B[24;46m" +#define RTT_CTRL_BG_WHITE "\x1B[24;47m" + +#define RTT_CTRL_BG_BRIGHT_BLACK "\x1B[4;40m" +#define RTT_CTRL_BG_BRIGHT_RED "\x1B[4;41m" +#define RTT_CTRL_BG_BRIGHT_GREEN "\x1B[4;42m" +#define RTT_CTRL_BG_BRIGHT_YELLOW "\x1B[4;43m" +#define RTT_CTRL_BG_BRIGHT_BLUE "\x1B[4;44m" +#define RTT_CTRL_BG_BRIGHT_MAGENTA "\x1B[4;45m" +#define RTT_CTRL_BG_BRIGHT_CYAN "\x1B[4;46m" +#define RTT_CTRL_BG_BRIGHT_WHITE "\x1B[4;47m" + + +#endif + +/*************************** End of file ****************************/ diff --git a/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT_ASM_ARMv7M.s b/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT_ASM_ARMv7M.s new file mode 100644 index 0000000..cbbc52f --- /dev/null +++ b/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT_ASM_ARMv7M.s @@ -0,0 +1,242 @@ +/********************************************************************* +* (c) SEGGER Microcontroller GmbH * +* The Embedded Experts * +* www.segger.com * +********************************************************************** + +-------------------------- END-OF-HEADER ----------------------------- + +File : SEGGER_RTT_ASM_ARMv7M.S +Purpose : Assembler implementation of RTT functions for ARMv7M + +Additional information: + This module is written to be assembler-independent and works with + GCC and clang (Embedded Studio) and IAR. +*/ + +#define SEGGER_RTT_ASM // Used to control processed input from header file +#include "SEGGER_RTT.h" + +/********************************************************************* +* +* Defines, fixed +* +********************************************************************** +*/ + +#define _CCIAR 0 +#define _CCCLANG 1 + +#if (defined __SES_ARM) || (defined __GNUC__) || (defined __clang__) + #define _CC_TYPE _CCCLANG + #define _PUB_SYM .global + #define _EXT_SYM .extern + #define _END .end + #define _WEAK .weak + #define _THUMB_FUNC .thumb_func + #define _THUMB_CODE .code 16 + #define _WORD .word + #define _SECTION(Sect, Type, AlignExp) .section Sect ##, "ax" + #define _ALIGN(Exp) .align Exp + #define _PLACE_LITS .ltorg + #define _DATA_SECT_START + #define _C_STARTUP _start + #define _STACK_END __stack_end__ + #define _RAMFUNC + // + // .text => Link to flash + // .fast => Link to RAM + // OtherSect => Usually link to RAM + // Alignment is 2^x + // +#elif defined (__IASMARM__) + #define _CC_TYPE _CCIAR + #define _PUB_SYM PUBLIC + #define _EXT_SYM EXTERN + #define _END END + #define _WEAK _WEAK + #define _THUMB_FUNC + #define _THUMB_CODE THUMB + #define _WORD DCD + #define _SECTION(Sect, Type, AlignExp) SECTION Sect ## : ## Type ## :REORDER:NOROOT ## (AlignExp) + #define _ALIGN(Exp) alignrom Exp + #define _PLACE_LITS + #define _DATA_SECT_START DATA + #define _C_STARTUP __iar_program_start + #define _STACK_END sfe(CSTACK) + #define _RAMFUNC SECTION_TYPE SHT_PROGBITS, SHF_WRITE | SHF_EXECINSTR + // + // .text => Link to flash + // .textrw => Link to RAM + // OtherSect => Usually link to RAM + // NOROOT => Allows linker to throw away the function, if not referenced + // Alignment is 2^x + // +#endif + +#if (_CC_TYPE == _CCIAR) + NAME SEGGER_RTT_ASM_ARMv7M +#else + .syntax unified +#endif + +#if defined (RTT_USE_ASM) && (RTT_USE_ASM == 1) + #define SHT_PROGBITS 0x1 + +/********************************************************************* +* +* Public / external symbols +* +********************************************************************** +*/ + + _EXT_SYM __aeabi_memcpy + _EXT_SYM __aeabi_memcpy4 + _EXT_SYM _SEGGER_RTT + + _PUB_SYM SEGGER_RTT_ASM_WriteSkipNoLock + +/********************************************************************* +* +* SEGGER_RTT_WriteSkipNoLock +* +* Function description +* Stores a specified number of characters in SEGGER RTT +* control block which is then read by the host. +* SEGGER_RTT_WriteSkipNoLock does not lock the application and +* skips all data, if the data does not fit into the buffer. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used (e.g. 0 for "Terminal"). +* pBuffer Pointer to character array. Does not need to point to a \0 terminated string. +* NumBytes Number of bytes to be stored in the SEGGER RTT control block. +* MUST be > 0!!! +* This is done for performance reasons, so no initial check has do be done. +* +* Return value +* 1: Data has been copied +* 0: No space, data has not been copied +* +* Notes +* (1) If there is not enough space in the "Up"-buffer, all data is dropped. +* (2) For performance reasons this function does not call Init() +* and may only be called after RTT has been initialized. +* Either by calling SEGGER_RTT_Init() or calling another RTT API function first. +*/ + _SECTION(.text, CODE, 2) + _ALIGN(2) + _THUMB_FUNC +SEGGER_RTT_ASM_WriteSkipNoLock: // unsigned SEGGER_RTT_WriteSkipNoLock(unsigned BufferIndex, const void* pData, unsigned NumBytes) { + // + // Cases: + // 1) RdOff <= WrOff => Space until wrap-around is sufficient + // 2) RdOff <= WrOff => Space after wrap-around needed (copy in 2 chunks) + // 3) RdOff < WrOff => No space in buf + // 4) RdOff > WrOff => Space is sufficient + // 5) RdOff > WrOff => No space in buf + // + // 1) is the most common case for large buffers and assuming that J-Link reads the data fast enough + // + // Register usage: + // R0 Temporary needed as RdOff, register later on + // R1 pData + // R2 + // R3 register. Hold free for subroutine calls + // R4 + // R5 pRing->pBuffer + // R6 pRing (Points to active struct SEGGER_RTT_BUFFER_DOWN) + // R7 WrOff + // + PUSH {R4-R7} + ADD R3,R0,R0, LSL #+1 + LDR.W R0,=_SEGGER_RTT // pRing = &_SEGGER_RTT.aUp[BufferIndex]; + ADD R0,R0,R3, LSL #+3 + ADD R6,R0,#+24 + LDR R0,[R6, #+16] // RdOff = pRing->RdOff; + LDR R7,[R6, #+12] // WrOff = pRing->WrOff; + LDR R5,[R6, #+4] // pRing->pBuffer + CMP R7,R0 + BCC.N _CheckCase4 // if (RdOff <= WrOff) { => Case 1), 2) or 3) + // + // Handling for case 1, later on identical to case 4 + // + LDR R3,[R6, #+8] // Avail = pRing->SizeOfBuffer - WrOff - 1u; => Space until wrap-around (assume 1 byte not usable for case that RdOff == 0) + SUBS R4,R3,R7 // (Used in case we jump into case 2 afterwards) + SUBS R3,R4,#+1 // + CMP R3,R2 + BCC.N _CheckCase2 // if (Avail >= NumBytes) { => Case 1)? +_Case4: + ADDS R5,R7,R5 // pBuffer += WrOff + ADDS R0,R2,R7 // v = WrOff + NumBytes + // + // 2x unrolling for the copy loop that is used most of the time + // This is a special optimization for small SystemView packets and makes them even faster + // + _ALIGN(2) +_LoopCopyStraight: // memcpy(pRing->pBuffer + WrOff, pData, NumBytes); + LDRB R3,[R1], #+1 + STRB R3,[R5], #+1 // *pDest++ = *pSrc++ + SUBS R2,R2,#+1 + BEQ _CSDone + LDRB R3,[R1], #+1 + STRB R3,[R5], #+1 // *pDest++ = *pSrc++ + SUBS R2,R2,#+1 + BNE _LoopCopyStraight +_CSDone: +#if _CORE_NEEDS_DMB // Do not slow down cores that do not need a DMB instruction here + DMB // Cortex-M7 may delay memory writes and also change the order in which the writes happen. Therefore, make sure that all buffer writes are finished, before updating the in the struct +#endif + STR R0,[R6, #+12] // pRing->WrOff = WrOff + NumBytes; + MOVS R0,#+1 + POP {R4-R7} + BX LR // Return 1 +_CheckCase2: + ADDS R0,R0,R3 // Avail += RdOff; => Space incl. wrap-around + CMP R0,R2 + BCC.N _Case3 // if (Avail >= NumBytes) { => Case 2? => If not, we have case 3) (does not fit) + // + // Handling for case 2 + // + ADDS R0,R7,R5 // v = pRing->pBuffer + WrOff => Do not change pRing->pBuffer here because 2nd chunk needs org. value + SUBS R2,R2,R4 // NumBytes -= Rem; (Rem = pRing->SizeOfBuffer - WrOff; => Space until end of buffer) +_LoopCopyBeforeWrapAround: // memcpy(pRing->pBuffer + WrOff, pData, Rem); => Copy 1st chunk + LDRB R3,[R1], #+1 + STRB R3,[R0], #+1 // *pDest++ = *pSrc++ + SUBS R4,R4,#+1 + BNE _LoopCopyBeforeWrapAround + // + // Special case: First check that assumed RdOff == 0 calculated that last element before wrap-around could not be used + // But 2nd check (considering space until wrap-around and until RdOff) revealed that RdOff is not 0, so we can use the last element + // In this case, we may use a copy straight until buffer end anyway without needing to copy 2 chunks + // Therefore, check if 2nd memcpy is necessary at all + // + ADDS R4,R2,#+0 // Save (needed as counter in loop but must be written to after the loop). Also use this inst to update the flags to skip 2nd loop if possible + BEQ.N _No2ChunkNeeded // if (NumBytes) { +_LoopCopyAfterWrapAround: // memcpy(pRing->pBuffer, pData + Rem, NumBytes); + LDRB R3,[R1], #+1 // pData already points to the next src byte due to copy loop increment before this loop + STRB R3,[R5], #+1 // *pDest++ = *pSrc++ + SUBS R2,R2,#+1 + BNE _LoopCopyAfterWrapAround +_No2ChunkNeeded: +#if _CORE_NEEDS_DMB // Do not slow down cores that do not need a DMB instruction here + DMB // Cortex-M7 may delay memory writes and also change the order in which the writes happen. Therefore, make sure that all buffer writes are finished, before updating the in the struct +#endif + STR R4,[R6, #+12] // pRing->WrOff = NumBytes; => Must be written after copying data because J-Link may read control block asynchronously while writing into buffer + MOVS R0,#+1 + POP {R4-R7} + BX LR // Return 1 +_CheckCase4: + SUBS R0,R0,R7 + SUBS R0,R0,#+1 // Avail = RdOff - WrOff - 1u; + CMP R0,R2 + BCS.N _Case4 // if (Avail >= NumBytes) { => Case 4) == 1) ? => If not, we have case 5) == 3) (does not fit) +_Case3: + MOVS R0,#+0 + POP {R4-R7} + BX LR // Return 0 + _PLACE_LITS + +#endif // defined (RTT_USE_ASM) && (RTT_USE_ASM == 1) + _END + +/*************************** End of file ****************************/ diff --git a/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT_printf.c b/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT_printf.c new file mode 100644 index 0000000..23fc445 --- /dev/null +++ b/Middlewares/Third_Party/SEGGER/RTT/SEGGER_RTT_printf.c @@ -0,0 +1,505 @@ +/********************************************************************* +* SEGGER Microcontroller GmbH * +* The Embedded Experts * +********************************************************************** +* * +* (c) 1995 - 2021 SEGGER Microcontroller GmbH * +* * +* www.segger.com Support: support@segger.com * +* * +********************************************************************** +* * +* SEGGER RTT * Real Time Transfer for embedded targets * +* * +********************************************************************** +* * +* All rights reserved. * +* * +* SEGGER strongly recommends to not make any changes * +* to or modify the source code of this software in order to stay * +* compatible with the RTT protocol and J-Link. * +* * +* Redistribution and use in source and binary forms, with or * +* without modification, are permitted provided that the following * +* condition is met: * +* * +* o Redistributions of source code must retain the above copyright * +* notice, this condition and the following disclaimer. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * +* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * +* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * +* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * +* DISCLAIMED. IN NO EVENT SHALL SEGGER Microcontroller BE LIABLE FOR * +* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * +* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * +* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * +* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * +* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * +* DAMAGE. * +* * +********************************************************************** +* * +* RTT version: 7.58c * +* * +********************************************************************** + +---------------------------END-OF-HEADER------------------------------ +File : SEGGER_RTT_printf.c +Purpose : Replacement for printf to write formatted data via RTT +Revision: $Rev: 17697 $ +---------------------------------------------------------------------- +*/ +#include "SEGGER_RTT.h" +#include "SEGGER_RTT_Conf.h" + +/********************************************************************* +* +* Defines, configurable +* +********************************************************************** +*/ + +#ifndef SEGGER_RTT_PRINTF_BUFFER_SIZE + #define SEGGER_RTT_PRINTF_BUFFER_SIZE (64) +#endif + +#include +#include + + +#define FORMAT_FLAG_LEFT_JUSTIFY (1u << 0) +#define FORMAT_FLAG_PAD_ZERO (1u << 1) +#define FORMAT_FLAG_PRINT_SIGN (1u << 2) +#define FORMAT_FLAG_ALTERNATE (1u << 3) + +/********************************************************************* +* +* Types +* +********************************************************************** +*/ + +typedef struct { + char* pBuffer; + unsigned BufferSize; + unsigned Cnt; + + int ReturnValue; + + unsigned RTTBufferIndex; +} SEGGER_RTT_PRINTF_DESC; + +/********************************************************************* +* +* Function prototypes +* +********************************************************************** +*/ + +/********************************************************************* +* +* Static code +* +********************************************************************** +*/ +/********************************************************************* +* +* _StoreChar +*/ +static void _StoreChar(SEGGER_RTT_PRINTF_DESC * p, char c) { + unsigned Cnt; + + Cnt = p->Cnt; + if ((Cnt + 1u) <= p->BufferSize) { + *(p->pBuffer + Cnt) = c; + p->Cnt = Cnt + 1u; + p->ReturnValue++; + } + // + // Write part of string, when the buffer is full + // + if (p->Cnt == p->BufferSize) { + if (SEGGER_RTT_Write(p->RTTBufferIndex, p->pBuffer, p->Cnt) != p->Cnt) { + p->ReturnValue = -1; + } else { + p->Cnt = 0u; + } + } +} + +/********************************************************************* +* +* _PrintUnsigned +*/ +static void _PrintUnsigned(SEGGER_RTT_PRINTF_DESC * pBufferDesc, unsigned v, unsigned Base, unsigned NumDigits, unsigned FieldWidth, unsigned FormatFlags) { + static const char _aV2C[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; + unsigned Div; + unsigned Digit; + unsigned Number; + unsigned Width; + char c; + + Number = v; + Digit = 1u; + // + // Get actual field width + // + Width = 1u; + while (Number >= Base) { + Number = (Number / Base); + Width++; + } + if (NumDigits > Width) { + Width = NumDigits; + } + // + // Print leading chars if necessary + // + if ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u) { + if (FieldWidth != 0u) { + if (((FormatFlags & FORMAT_FLAG_PAD_ZERO) == FORMAT_FLAG_PAD_ZERO) && (NumDigits == 0u)) { + c = '0'; + } else { + c = ' '; + } + while ((FieldWidth != 0u) && (Width < FieldWidth)) { + FieldWidth--; + _StoreChar(pBufferDesc, c); + if (pBufferDesc->ReturnValue < 0) { + break; + } + } + } + } + if (pBufferDesc->ReturnValue >= 0) { + // + // Compute Digit. + // Loop until Digit has the value of the highest digit required. + // Example: If the output is 345 (Base 10), loop 2 times until Digit is 100. + // + while (1) { + if (NumDigits > 1u) { // User specified a min number of digits to print? => Make sure we loop at least that often, before checking anything else (> 1 check avoids problems with NumDigits being signed / unsigned) + NumDigits--; + } else { + Div = v / Digit; + if (Div < Base) { // Is our divider big enough to extract the highest digit from value? => Done + break; + } + } + Digit *= Base; + } + // + // Output digits + // + do { + Div = v / Digit; + v -= Div * Digit; + _StoreChar(pBufferDesc, _aV2C[Div]); + if (pBufferDesc->ReturnValue < 0) { + break; + } + Digit /= Base; + } while (Digit); + // + // Print trailing spaces if necessary + // + if ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == FORMAT_FLAG_LEFT_JUSTIFY) { + if (FieldWidth != 0u) { + while ((FieldWidth != 0u) && (Width < FieldWidth)) { + FieldWidth--; + _StoreChar(pBufferDesc, ' '); + if (pBufferDesc->ReturnValue < 0) { + break; + } + } + } + } + } +} + +/********************************************************************* +* +* _PrintInt +*/ +static void _PrintInt(SEGGER_RTT_PRINTF_DESC * pBufferDesc, int v, unsigned Base, unsigned NumDigits, unsigned FieldWidth, unsigned FormatFlags) { + unsigned Width; + int Number; + + Number = (v < 0) ? -v : v; + + // + // Get actual field width + // + Width = 1u; + while (Number >= (int)Base) { + Number = (Number / (int)Base); + Width++; + } + if (NumDigits > Width) { + Width = NumDigits; + } + if ((FieldWidth > 0u) && ((v < 0) || ((FormatFlags & FORMAT_FLAG_PRINT_SIGN) == FORMAT_FLAG_PRINT_SIGN))) { + FieldWidth--; + } + + // + // Print leading spaces if necessary + // + if ((((FormatFlags & FORMAT_FLAG_PAD_ZERO) == 0u) || (NumDigits != 0u)) && ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u)) { + if (FieldWidth != 0u) { + while ((FieldWidth != 0u) && (Width < FieldWidth)) { + FieldWidth--; + _StoreChar(pBufferDesc, ' '); + if (pBufferDesc->ReturnValue < 0) { + break; + } + } + } + } + // + // Print sign if necessary + // + if (pBufferDesc->ReturnValue >= 0) { + if (v < 0) { + v = -v; + _StoreChar(pBufferDesc, '-'); + } else if ((FormatFlags & FORMAT_FLAG_PRINT_SIGN) == FORMAT_FLAG_PRINT_SIGN) { + _StoreChar(pBufferDesc, '+'); + } else { + + } + if (pBufferDesc->ReturnValue >= 0) { + // + // Print leading zeros if necessary + // + if (((FormatFlags & FORMAT_FLAG_PAD_ZERO) == FORMAT_FLAG_PAD_ZERO) && ((FormatFlags & FORMAT_FLAG_LEFT_JUSTIFY) == 0u) && (NumDigits == 0u)) { + if (FieldWidth != 0u) { + while ((FieldWidth != 0u) && (Width < FieldWidth)) { + FieldWidth--; + _StoreChar(pBufferDesc, '0'); + if (pBufferDesc->ReturnValue < 0) { + break; + } + } + } + } + if (pBufferDesc->ReturnValue >= 0) { + // + // Print number without sign + // + _PrintUnsigned(pBufferDesc, (unsigned)v, Base, NumDigits, FieldWidth, FormatFlags); + } + } + } +} + +/********************************************************************* +* +* Public code +* +********************************************************************** +*/ +/********************************************************************* +* +* SEGGER_RTT_vprintf +* +* Function description +* Stores a formatted string in SEGGER RTT control block. +* This data is read by the host. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used. (e.g. 0 for "Terminal") +* sFormat Pointer to format string +* pParamList Pointer to the list of arguments for the format string +* +* Return values +* >= 0: Number of bytes which have been stored in the "Up"-buffer. +* < 0: Error +*/ +int SEGGER_RTT_vprintf(unsigned BufferIndex, const char * sFormat, va_list * pParamList) { + char c; + SEGGER_RTT_PRINTF_DESC BufferDesc; + int v; + unsigned NumDigits; + unsigned FormatFlags; + unsigned FieldWidth; + char acBuffer[SEGGER_RTT_PRINTF_BUFFER_SIZE]; + + BufferDesc.pBuffer = acBuffer; + BufferDesc.BufferSize = SEGGER_RTT_PRINTF_BUFFER_SIZE; + BufferDesc.Cnt = 0u; + BufferDesc.RTTBufferIndex = BufferIndex; + BufferDesc.ReturnValue = 0; + + do { + c = *sFormat; + sFormat++; + if (c == 0u) { + break; + } + if (c == '%') { + // + // Filter out flags + // + FormatFlags = 0u; + v = 1; + do { + c = *sFormat; + switch (c) { + case '-': FormatFlags |= FORMAT_FLAG_LEFT_JUSTIFY; sFormat++; break; + case '0': FormatFlags |= FORMAT_FLAG_PAD_ZERO; sFormat++; break; + case '+': FormatFlags |= FORMAT_FLAG_PRINT_SIGN; sFormat++; break; + case '#': FormatFlags |= FORMAT_FLAG_ALTERNATE; sFormat++; break; + default: v = 0; break; + } + } while (v); + // + // filter out field with + // + FieldWidth = 0u; + do { + c = *sFormat; + if ((c < '0') || (c > '9')) { + break; + } + sFormat++; + FieldWidth = (FieldWidth * 10u) + ((unsigned)c - '0'); + } while (1); + + // + // Filter out precision (number of digits to display) + // + NumDigits = 0u; + c = *sFormat; + if (c == '.') { + sFormat++; + do { + c = *sFormat; + if ((c < '0') || (c > '9')) { + break; + } + sFormat++; + NumDigits = NumDigits * 10u + ((unsigned)c - '0'); + } while (1); + } + // + // Filter out length modifier + // + c = *sFormat; + do { + if ((c == 'l') || (c == 'h')) { + sFormat++; + c = *sFormat; + } else { + break; + } + } while (1); + // + // Handle specifiers + // + switch (c) { + case 'c': { + char c0; + v = va_arg(*pParamList, int); + c0 = (char)v; + _StoreChar(&BufferDesc, c0); + break; + } + case 'd': + v = va_arg(*pParamList, int); + _PrintInt(&BufferDesc, v, 10u, NumDigits, FieldWidth, FormatFlags); + break; + case 'u': + v = va_arg(*pParamList, int); + _PrintUnsigned(&BufferDesc, (unsigned)v, 10u, NumDigits, FieldWidth, FormatFlags); + break; + case 'x': + case 'X': + v = va_arg(*pParamList, int); + _PrintUnsigned(&BufferDesc, (unsigned)v, 16u, NumDigits, FieldWidth, FormatFlags); + break; + case 's': + { + const char * s = va_arg(*pParamList, const char *); + do { + c = *s; + s++; + if (c == '\0') { + break; + } + _StoreChar(&BufferDesc, c); + } while (BufferDesc.ReturnValue >= 0); + } + break; + case 'p': + v = va_arg(*pParamList, int); + _PrintUnsigned(&BufferDesc, (unsigned)v, 16u, 8u, 8u, 0u); + break; + case '%': + _StoreChar(&BufferDesc, '%'); + break; + default: + break; + } + sFormat++; + } else { + _StoreChar(&BufferDesc, c); + } + } while (BufferDesc.ReturnValue >= 0); + + if (BufferDesc.ReturnValue > 0) { + // + // Write remaining data, if any + // + if (BufferDesc.Cnt != 0u) { + SEGGER_RTT_Write(BufferIndex, acBuffer, BufferDesc.Cnt); + } + BufferDesc.ReturnValue += (int)BufferDesc.Cnt; + } + return BufferDesc.ReturnValue; +} + +/********************************************************************* +* +* SEGGER_RTT_printf +* +* Function description +* Stores a formatted string in SEGGER RTT control block. +* This data is read by the host. +* +* Parameters +* BufferIndex Index of "Up"-buffer to be used. (e.g. 0 for "Terminal") +* sFormat Pointer to format string, followed by the arguments for conversion +* +* Return values +* >= 0: Number of bytes which have been stored in the "Up"-buffer. +* < 0: Error +* +* Notes +* (1) Conversion specifications have following syntax: +* %[flags][FieldWidth][.Precision]ConversionSpecifier +* (2) Supported flags: +* -: Left justify within the field width +* +: Always print sign extension for signed conversions +* 0: Pad with 0 instead of spaces. Ignored when using '-'-flag or precision +* Supported conversion specifiers: +* c: Print the argument as one char +* d: Print the argument as a signed integer +* u: Print the argument as an unsigned integer +* x: Print the argument as an hexadecimal integer +* s: Print the string pointed to by the argument +* p: Print the argument as an 8-digit hexadecimal integer. (Argument shall be a pointer to void.) +*/ +int SEGGER_RTT_printf(unsigned BufferIndex, const char * sFormat, ...) { + int r; + va_list ParamList; + + va_start(ParamList, sFormat); + r = SEGGER_RTT_vprintf(BufferIndex, sFormat, &ParamList); + va_end(ParamList); + return r; +} +/*************************** End of file ****************************/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..9032354 --- /dev/null +++ b/README.md @@ -0,0 +1,342 @@ +# YueLu2022/2023 EC basic_framework-dev + +湖南大学RoboMaster跃鹿战队2022-2023电控通用嵌入式框架。 + + ++ + + +> ***也许不是最好的?但一定是最完整最详细最适合上手的电控开源!*** + +[TOC] + +***==别忘了仓库根目录下的`.Doc`文件夹中有关于配置环境和开发更详尽的说明!==*** + +- 若无法访问github,戳[gitee仓库](https://gitee.com/hnuyuelurm/basic_framework) +- 若gitee内容被屏蔽,戳[github仓库](https://github.com/HNUYueLuRM/basic_framework) + +> 基于basic_framework打造的C++进阶重构版本[***powerful_framework***](https://gitee.com/hnuyuelurm/powerful_framework)现已发布!增加全新的消息交互机制和严格的跨任务数据读写保护,采用了现代构建系统CMake+Ninja以追求极致的编译速度,各种针对嵌入式的编译优化全开,DIY程度进一步提升,更有自定义CMSIS-DSP和Eigen等扩展库支持!快来加入试用/和我们一起开发吧😋 + + + +--- + + + +## 功能介绍和展示 + +### 起源 + +这是湖南大学RoboMaster跃鹿战队电控组2022-2023赛季的通用嵌入式控制框架,可用于**机器人主控**、自研模组(imu/测距等各种传感器)、超级电容控制器等。 + +从目前的RoboMaster开源社区来看,大部分队伍都没有一套规则统一,符合较大规模软件开发原则的框架,有些学校连不同兵种代码都相去甚远,甚至连队伍用于传承的代码注释都寥寥无几,全靠师傅带徒弟言传身教。当然,不乏有广东工业大学DynamicX开源的rm_control这样规范且先进的系统,但基于Linux、ROS、C++的这套软件栈对于新人来说还是过于复杂(但我们很推荐熟悉基本工具的同学使用!)。 + +### 优势 + +为此,basic_framework应运而生。该框架旨在打造上手简单、易于移植、高代码复用、层级分明、结构清晰的一套SDK,供队内使用&RM参赛队伍&嵌入式开发者交流学习。通过精心设计的bsp和module支持以及成熟的app示例,该框架可以在短时间内为不同类型和结构的机器人**轻松构建**电控程序,**可扩展性**和**可维护性**相较目前的大部分开源代码和本队的老代码提升巨大。 + +同时,相较于传统的基于KEIL MDK开发的工作流,我们推出了基于arm-gnu工具链+VSCode/Clion+Ozone&Systemviewer/FreeMaster的**现代化开发工作流**和非**常完善配套教程**,你再也不用面对上个世纪的UI,忍受没有补全和高亮的代码了!在现代化开发工具支持下,将**极大提高电控开发效率和调试效率**。硬件模块测试和整车联调从未**如此简单方便**! + +> 用软件开发的思想设计嵌入式系统是一种降维打击 +> +>+
+
++
+
+
+
++
+
Best RoboMaster embedded EC open-source code ever?
+—— 沃兹基·烁德
+ +### 效果展示 + + + +搭载basic_framework的机器人阵容 + +实战展示: + +1. 400HP双云台哨兵30m/s弹速**对抗**2台200HP 15m/s弹速步兵,120w底盘功率 +2. 100HP步兵,120w功率,15m/s弹速**对射**,限制射频0.5发/s + + + +展示中的视觉识别与预测算法是基于rm_vision打造的 + +3. 工程机器人流程化抓取矿石/兑换矿石/救援’ + +  + +4. 平衡步兵机器人 + +  + +这些机器人的程序均基于basic_framework打造,已在我们的仓库中提供:[HNUYueLuRM](https://gitee.com/hnuyuelurm) + +> 更多测试视频可以关注我们的bilibili账号:[湖南大学跃鹿战队](https://space.bilibili.com/522795884),或在bilibili搜索跃鹿战队,观看我们的比赛视频。 + +### 可用功能 + +你可以基于这些良好抽象的功能打造自己的模块或应用。 + +#### bsp封装 + +| 功能类别 | 模块 | +| ---------- | ----------------------- | +| 通信类外设 | usart spi i2c can usb | +| 日志 | log flash | +| 功能型 | gpio(exti) pwm adc | +| 辅助 | dwt | + +#### 模块封装 + +| 功能类别 | 模块 | +| -------- | ------------------------------------------------------------ | +| 电机 | DJI、HT海泰04、瓴控LK、步进电机、舵机 | +| 通信 | 多板通信(基于CAN)、seasky协议上位机通信、裁判系统数据/UI/多机、vofa协议、DT7-DR16遥控器 | +| 功能模块 | 蜂鸣器、oled、bmi088、ist8310、超级电容、TFminiPlus、 | +| 应用支持 | 常用算法库、守护线程、消息中心 | + +#### 应用封装 + +作为命令发布主体的robot_cmd + +用于步兵、英雄、哨兵、无人机的gimbal + +麦克纳姆轮/全向轮底盘的chassis + +平衡步兵的底盘balance_chassis + +装配了发射机构的机器人的shoot + + + +--- + + + +## 架构 + +总览。 + +### 软件栈 + ++ +在CubeMX初始化生成的依赖文件基础之上新增了可选的CMSIS-DSP和Segger RTT。 + +### 设计思想 + +1. ***首先,总览框架的设计模式。*** + + 框架在结构上分为三层:bsp/module/app。整体使用的设计模式是**结构层级模式**,即每个“类”包含需要使用的底层“类”,通过组装不同的基础模实现更强大的功能。而最顶层的app之间则通过**pub-sub消息机制**进行解耦,使得在编写代码时不会出现相互包含的情况。 + + 我们希望通过bsp对硬件的抽象使得module的编写更为轻松,不需要考虑底层的硬件具体是如何运作的;再通过module的外接模块的抽象,使得app的编写可以通过完全硬件无关的方式考虑,达到*”只阅读module的说明文档就能迅速开发应用 ”*的程度。bsp和module的设计愿景,就是成为人们常说的***中间件**。* + + **pub-sub机制的体现**:以本仓库的app层为例,包含了chassis,gimbal,shoot,cmd四个应用,每个应用都对应了机器人上的不同模组。cmd应用负责从机器人控制信号来源(遥控器/上位机/环境传感器)处获取信息并解析成各个**执行单元的实际动作**(电机/舵机/气缸/阀门等的扭矩/速度/位置/角度/开度等),并将此信息**发布**出去。chassis、gimbal、shoot等包含了执行单元的应用则**订阅**这些消息,并通过自己包含的子模块,调用它们的接口实现动作。 + + **结构层级模式的体现**:以chassis应用为例,chassis中包含了4个底盘电机模块。当chassis收到cmd应用的信息,希望让底盘以1m/s的速度前进。chassis首先根据底盘的类型(舵轮/麦克纳姆轮/全向轮/平衡底盘)以及对应的动力学/运动学解算函数,计算得到每个电机的输目标输入值,此时chassis将输入通过电机模块(motor module)的接口将设定值告知电机。而每个电机模块又有各自的PID计算模块和自身电流&速度&角度传感器的信息,可以计算出最终需要的电流设定值。假设该电机使用CAN协议与电调通信,则电机通过自身包含的CANInstance(bsp_can提供)用于和实际硬件交互,电机模块将设定值电流值或其他指令按照通信协议组织在CAN报文中,通过CANInstance提供的接口,把最终控制数据发送给电调,实现控制闭环。从调用来看,三个层级的**包含关系为chassis∈motor∈bspcan**。 + +2. ***有了上面的大体认知,我们分别介绍框架的三层结构。*** + + - **bsp**即板级支持包,提供对开发板外设的软件抽象,让module层能使用和硬件无关的接口(由bsp提供)进行数据处理与交互。 + + bsp层和ST的HAL为强耦合,与硬件直接绑定。若要向其他的ST芯片移植,基本不需要修改bsp层;若是其他单片机则建议保留**接口设计**,对接口调用进行重现实现。每一种外设的头文件中都定义了一个**XXXInstance**(xxx为外设名),其中包含了使用该外设所需要的所有数据,如发送/接收的数据,长度,id(如果有),父指针(指向module实例的指针,用于回调)等。由于C没有`class`,因此所有bsp的接口都需要传入一个额外的参数:XXXInstance*,用于实现c++的`this`指针以区分具体是哪一个实例调用了接口。 + + - **module**即模块层,包括了需要开发板硬件外设支持的(一般用于通信)真实**硬件模组**如电机、舵机、imu、测距传感器,和通过软件实现的**算法**如PID、滤波器、状态观测器;还有用于兼容不同控制信息模块(遥控器/ps手柄/图传链路/上位机)的统一接口模块,以及为app层提供数据交互的message center。 + + module层仍然是基于实例的,一个app会包含多个module的instance。当app便可以用硬件无关的接口使用module,如要求电机以一定速度运动、关闭气阀、给超级电容或上位机发送一些反馈数据等。在有了方便的bsp之后,只需要在你构建的module中包含必须的bsp,然后为app提供合理易用的接口即可。 + + - **app**是框架层级中最高的部分。目前的框架设计里,会有多个app任务运行在freertos中,当然你也可以根据需要启动一些事件驱动的任务,所有的任务安排都放在`app/robot_task`中。当前的app层仅是一个机器人开发的示例,有了封装程度极高的module,你可以在app完成任何事情。 + + 目前的app设计里,可以兼容多块开发板的情况,通过**条件编译**切换开发板的位置。如步兵机器人可以将主控MCU放在云台上,而超级电容控制板同时作为底盘板。使用CAN/SPI/UART将两者连接,便可以通过**`app/robot_def.h`**中的宏完成设置。可以根据需要,设置更多的开发板(双云台哨兵、工程机器人)。 + + 这套框架可以轻松扩展到所有机器人上,在我们的仓库中,有步兵机器人、平衡步兵机器人、哨兵机器人、英雄机器人、工程机器人以及空中机器人的代码实例,皆按照本框架中的三层结构开发。若设计了新的机器人,只需要在robot_def.h中修改传感器的位置、底盘轮距轴距、拨弹盘容量、弹舱载弹量等参数便可以**立刻实现部署**。 + +3. ***知道了每个层级的结构之后,我们再谈谈如何进行每层的开发。*** + + 对于bsp和module中每个instance的设计,我们采用了**面向对象**的C风格代码,整个框架也统一了变量和函数命名方式,调用层级和数据流十分清晰(下一个章节也有插图阐述)。 + + 为了避免出现”底层代码包含上层头文件“的情况,我们让bsp层instance在注册时要求module提供数据发送/接收的回调函数指针,从而在发生对应中断或事件时完成对module函数的”反向调用“。事实上,你也可以进一步将这套思想放入app的设计中,当某个事件发生时触发app的任务,而不是将app的任务定时运行(这可以提高运行效率,降低cpu占用)。 + + bsp和module的instance在初始化时接口皆为**`XXXInstance* XXXRegister(XXX_Init_Config_s* conf)`**,传入该实例所需的config参数,返回一个实例指针(看作this指针),之后要调用模块的功能,传入该指针即可。我们还提供了守护线程,以供module选用,当异常情况发生时在LOG中发送warning、触发蜂鸣器或LED进行声光报警以及错误/离线回调函数,保证系统的鲁棒性和安全性。 + + 而对于app的开发,由于底层接口已经设计的较为完善,不同的机器人可以直接**`fork`** basic_framework的代码,开发app层。当bsp和module有功能更新时,只需要通过git的cherry-pick-commit功能将更新拉取到自己的仓库,**获得动态的热更新而无需手动合并分支!** + + + +--- + + + +## 执行顺序与数据流 + +### 初始化 + + + +### 任务结构 + +app、module和bsp都有相应的rtos任务。其中bsp为创建任务提供了封装工具bsp_tools,旨在将复杂的回调函数转移到任务中而不是在中断内执行,以保证系统响应的实时性和数据完整性。有一些module和app根据功能需要会创建定时任务或事件驱动的任务,这些任务都在初始化时注册,并在特定的时刻被唤醒或周期执行。 + +
+ +### 数据流 + + + +
建议浏览器打开SVG查看 + + + +--- + + + +## 开发工具 + +介绍完整的工作流。 + +### 工具链 + +强烈推荐使用arm-gnu工具链进行编译(arm-none-eabi-xxx)。 + +官方下载地址:[Arm GNU Toolchain Downloads – Arm Developer](https://developer.arm.com/downloads/-/arm-gnu-toolchain-downloads) + +我们更推荐使用Msys2进行库和开发工具管理,关于如何使用Msys2请参考:[如何使用本框架](##如何使用本框架) + +> 仍然支持使用arm-cc工具链(即keil默认的工具链)进行开发,在cubemx初始化时生成MDK项目即可,然后再手动添加basic_framework的所有头文件和源文件。但非常不建议这样做,arm-cc仅支持单线程编译且编译优化选项远不如arm-gnu多,自定义程度同样不比。~~若你一定要这样做,则可以在VSCode中安装keil assistant插件。~~ + +### IDE? + +使用**VSCode**作为“IDE”,也支持Clion/Visual Studio等现代化IDE(需要自行配置)。需要的插件支持均已经在[VSCode+Ozone使用方法.md](.Doc/VSCode+Ozone使用方法.md)中给出。通过VSCode强大的插件系统、language server以及代码补全高亮助力效率倍增。编译则使用集成的task进行,还可以将开发环境终端加入VSCode进一步提升体验。基本的调试如变量&寄存器查看均已在插件中提供支持,`launch.json`可以进行高自由度的自定义。 + +`Git`集成与gitlens/gitgraph/githistory额外插件补充让版本管理和协作从未如此简单,`live share`把你的伙伴们聚在一起集思广益,一同对抗困难的bug。更多好用的插件、特性和开发技巧请参考"**如何使用本框架**"章节。 + +> **不论如何,请不要使用KEIL作为你的代码编辑器。** + +### 调试和性能分析 + +- 基础的调试可以在VSCode中完成。cortex-debug插件的最新版本已经支持多个gdb-server(jlink/stlink/openocd/pyocd)的live watch(动态变量监视)和变量示波器(可视化)。若不是有特别的需求,*请勿使用串口调试器*。 + +- 有高速变量查看和数据记录、多路数据可视化的需求(如进行pid参数整定、查找难以定位的bug)时,使用**Segger Ozone**。 +- FreeMaster也可以作为调试的备选项。 +- 基本的、日常性能分析可以通过`bsp_dwt`完成。若要分析关于任务运行和每个函数执行的详细信息和时间,推荐使用**Segger Systemviewer**。 + + + +--- + + + +## 如何使用本框架 + +仓库中有各种各样的说明文档和使用帮助。 + +### 编译烧录 + +本项目是基于RoboMaster开发板C型的示例,MCU为STM32F407IG,使用了板载的imu bmi-088,驱动标准的步兵机器人:2自由度GM6020云台、m2006电机拨盘+2*m3508电机摩擦轮的发射机构和MG90舵机弹舱盖,以及带有超级电容控制器的4轮麦克纳姆底盘。 + +首先在`app/robot_def.h`中根据注释修改开发板和机器人配置,再在各个app中修改初始化配置(如电机id,上位机通信波特率/使用串口或VCP,imu速率,超级电容id等)。 + +接着根据[VSCode+Ozone使用方法.md](.Doc/VSCode+Ozone使用方法.md)配置好编译下载环境之后(***再次建议使用Msys2+mingw64/ucrt64/clang64的方式配置环境!***),在VSCode中打开项目,点击上方tab页的终端(terminal)->运行构建任务(run build task),便启动编译,若没有问题,最终会在终端中输出如下信息: + + + +工具链会预测ram,ccram以及flash的使用情况,并报告最终二进制文件的大小和存放位置。 + +随后,通过调试器将开发板连接至你的电脑,点击上方tab页的终端(terminal)->运行任务(run task),选择download_dap or download_jlink(或你自己编写的stlink/ulink/...),便会开始下载,终端或jFlash中会提示擦除、下载、验证的进度。 + +想要调试,在左侧tab页选择合适的调试选项,按F5或图形界面的绿色小三角形按钮,开始调试。当然,调试器的设置也请参考配置文档,主要是将可执行文件路劲加入环境变量的PATH。 + +**更详细的开发流程和本仓库工作流的最佳实践,请参照`.Doc/VSCode+Ozone使用方法.md`**,里面介绍了开发所需的前置知识、环境配置,以及工具链原理、使用方法等。 + +要对本仓库进行开发,务必先阅读`.Doc/架构介绍与开发指南.md`,内含本仓库组织结构的**文件树**。若你希望使用其他工具链或IDE,里面也有相关说明。 + +### 基本文档 + +根目录下的README.md即本说明文档,帮助开发者速览本项目。 + +`.Doc`目录下有**8**个markdown文档,分别为: + +- [Bug_Report](.Doc/Bug_Report.md) :提供了一些提交issues的模板范例,若在使用中出现问题请按照模板提供信息。 +- [TODO](.Doc/TODO.md) :框架后续开发计划和维护说明 +- **[VSCode+Ozone使用方法](.Doc/VSCode+Ozone使用方法.md)** :**重要**,上手必看。介绍了当前开发工作流和传统KEIL开发的不同,先讲解一些与工具链有关的基础知识,然后说明了如何配置开发环境,安装必要的软件和一些”操作“。还涉及了VSCode编辑调试和Ozone示波器&trace功能的使用指南。 +- [合理地进行PID参数整定](.Doc/合理地进行PID参数整定.md) :介绍了如何为PID控制器进行参数整定,包括简单的经验准则和基于模型的前馈控制、扰动消除等方法。 +- [如何定位bug](.Doc/如何定位bug.md) :当嵌入式开发出现bug时,以更高效地方法进行错误定位和复现。简单的调试器使用技巧。 +- [必须做&禁止做](.Doc/必须做&禁止做.md) :字如其名 +- **[架构介绍与开发指南](.Doc/架构介绍与开发指南.md)** : **重要**,开发必看。若你希望为bsp或module增添新的模块,组装新的app,请参照此文档的编码和命名规范进行。阅读该文档有助于理解并写出和框架代码风格一致的程序。内含该项目的**文件树**,以框架的工作目录。 +- [让VSCode成为更称手的IDE](.Doc/让VSCode成为更称手的IDE.md) :安装好用的插件,对编辑器进行个性化配置,提升开发效率 + +### 阅读代码 + +框架中的三层结构都有详尽的注释帮助阅读和二次开发,三个抽象层都有各自总览的说明文档,而每个bsp/module/app都配有对应的个性化说明文档,提供了接口说明和改进或进一步开发的建议。 + +建议以自上而下的方式阅读代码,app-》module-》bsp,为此我们还提供了框架的说明视频,分别讲解每个抽象层和总体的设计思路,介绍了bsp的依赖HAL,还有一些杂碎的开发相关知识:[basic_framework教程](https://space.bilibili.com/522795884/channel/collectiondetail) + +### 运行单个bsp/module测试 + +**每个bsp和module的文件夹中都有各自的说明文档**,测试用例和使用方法都在文档中给出,非常方便。 + +想要进行硬件查错、连线检查或测试,如测试开发板功能(外设)是否完好,电机电调能否正常使用,或给新人提供教学,只要: + +1. 将main.c中的`RoboInit()`函数删除,然后包含`bsp_init.h`头文件,在原`RoboInit()`的位置添加一个`BSPInit()` +2. 包含用于测试的bsp或module头文件,根据说明文档的用例初始化对应的支持包或模块即可。 +3. 同时可以将实时系统的初始化注释或删除,在`main.c`的`while(1)`主循环中进行测试,也可以使用`bsp_tim.h`提供的定时任务。 +4. 编译,下载,运行,调试。 + +我们为机械和视觉的同学能方便测试硬件模块的好坏,设计了一套通过串口和遥控器控制的**硬件功能测试程序**,使得其他技术组成员可以操作这个”黑箱“,在没有电控组成员的时候也不会卡住其他队员的进度。 + +### VSCode集成工具 + +我们在`.vscode`下提供了编写好的一些任务,包括编译,烧录,启动RTT终端(LOG),启动Ozone调试等。有些功能需要配置vscode的插件设置或将一些可执行文件加入环境变量,这些步骤已经在[VSCode+Ozone使用方法.md](.Doc/VSCode+Ozone使用方法.md)中给出;`launch.json`里包含了最常见的四种调试任务:使用jlink-server/openocd,启动或附加调试。 + +### for pro-user + +Makefile提供了脚本化的Makefile.upgrade,使用后者可以获取更好的开发体验。 + +可以自行添加需要的编译优化,进行更高级别的定制。 + +ST官方现在将HAL放入github维护。想要获取最新的支持,可以自行下载,加入本项目编译。 + +若希望纯开源使用,可以自定义openocd调试和烧录选项,参考根目录的openocd_dap.cfg和openocd_jlink.cfg。 + +若希望自己编译特定版本的cmsis-dsp或cmsis-os,请前往官方的github仓库下载,将构建规则加入makefile。 + +我们还增加了CMakeLists.txt以融入更现代化的构建系统,若你希望使用cmake,相信你有能力配置相关的开发环境。可以参考我们的[***powerful_framework***](https://gitee.com/hnuyuelurm/powerful_framework). + +如果实时系统任务需要的栈空间不够,请在CubeMX初始化配置中增大任务栈。一些freertos支持的高级功能请自行在配置页开启宏定义后重新生成。 + +... + + + +--- + + + +## 后续计划 + +- `.Doc/TODO.md`中列举了一些可能的功能增强和优化。 +- 将所有配置移动到一处,方便修改(统一放入`app/robot_def.h`中?) +- 为三个层级都增加入门级培训教程,可以单独运行各个模块以方便上手。 +- 优化pub-sub消息机制的性能,同时将app的任务尽可能修改为**状态机+事件驱动**的回调机制。 +- 使用Qt或命令行为机器人配置(主要是robot_def和各个任务中的module初始化配置)编写UI界面,实现无代码机器人部署。 +- 为框架编写ROSdriver,通过usb连接到上位机(NUC),合并视觉/算法和电控的工作流。 + + + +--- + + + +## 致谢 + +本框架设计参考了哈尔滨工业大学(深圳)南工骁鹰🦅战队的EC_framework以及RoboMaster官方的RoboRTS-firmware🤖。姿态解算改进自哈尔滨工程大学创梦之翼🛩️的四元数EKF姿态解算。裁判系统数据解析移植了深圳大学RoboPilot2021年电控英雄开源代码。 + +感谢2022-2023赛季跃鹿战队电控组参与新框架测试和开发的队员们,包括设计出机器人平台的机械组队员,还有一起联调的视觉组队员,以及负责拍摄、记录、宣传的运营组成员。 diff --git a/STM32F407.svd b/STM32F407.svd new file mode 100644 index 0000000..6aa360b --- /dev/null +++ b/STM32F407.svd @@ -0,0 +1,61681 @@ + + + \ No newline at end of file diff --git a/STM32F407IGHx_FLASH.ld b/STM32F407IGHx_FLASH.ld new file mode 100644 index 0000000..8f8f3b6 --- /dev/null +++ b/STM32F407IGHx_FLASH.ld @@ -0,0 +1,209 @@ +/* +****************************************************************************** +** + +** File : LinkerScript.ld +** +** Author : STM32CubeMX +** +** Abstract : Linker script for STM32F407IGHx series +** 1024Kbytes FLASH and 192Kbytes RAM +** +** Set heap size, stack size and stack location according +** to application requirements. +** +** Set memory bank area and size if external memory is used. +** +** Target : STMicroelectronics STM32 +** +** Distribution: The file is distributed “as is,” without any warranty +** of any kind. +** +***************************************************************************** +** @attention +** +**STM32F407 +1.2 +STM32F407 + ++ + + +CM4 +r1p0 +little +false +false +3 +false +8 + +32 + +0x20 +0x0 +0xFFFFFFFF ++ ++ +RNG +Random number generator +RNG +0x50060800 ++ +0x0 +0x400 +registers ++ +FPU +FPU interrupt +81 ++ ++ +CR +CR +control register +0x0 +0x20 +read-write +0x00000000 ++ ++ +IE +Interrupt enable +3 +1 ++ +RNGEN +Random number generator + enable +2 +1 ++ +SR +SR +status register +0x4 +0x20 +0x00000000 ++ ++ +SEIS +Seed error interrupt + status +6 +1 +read-write ++ +CEIS +Clock error interrupt + status +5 +1 +read-write ++ +SECS +Seed error current status +2 +1 +read-only ++ +CECS +Clock error current status +1 +1 +read-only ++ +DRDY +Data ready +0 +1 +read-only ++ +DR +DR +data register +0x8 +0x20 +read-only +0x00000000 ++ ++ +RNDATA +Random data +0 +32 ++ +DCMI +Digital camera interface +DCMI +0x50050000 ++ +0x0 +0x400 +registers ++ +DCMI +DCMI global interrupt +78 ++ ++ +CR +CR +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +ENABLE +DCMI enable +14 +1 ++ +EDM +Extended data mode +10 +2 ++ +FCRC +Frame capture rate control +8 +2 ++ +VSPOL +Vertical synchronization + polarity +7 +1 ++ +HSPOL +Horizontal synchronization + polarity +6 +1 ++ +PCKPOL +Pixel clock polarity +5 +1 ++ +ESS +Embedded synchronization + select +4 +1 ++ +JPEG +JPEG format +3 +1 ++ +CROP +Crop feature +2 +1 ++ +CM +Capture mode +1 +1 ++ +CAPTURE +Capture enable +0 +1 ++ +SR +SR +status register +0x4 +0x20 +read-only +0x0000 ++ ++ +FNE +FIFO not empty +2 +1 ++ +VSYNC +VSYNC +1 +1 ++ +HSYNC +HSYNC +0 +1 ++ +RIS +RIS +raw interrupt status register +0x8 +0x20 +read-only +0x0000 ++ ++ +LINE_RIS +Line raw interrupt status +4 +1 ++ +VSYNC_RIS +VSYNC raw interrupt status +3 +1 ++ +ERR_RIS +Synchronization error raw interrupt + status +2 +1 ++ +OVR_RIS +Overrun raw interrupt + status +1 +1 ++ +FRAME_RIS +Capture complete raw interrupt + status +0 +1 ++ +IER +IER +interrupt enable register +0xC +0x20 +read-write +0x0000 ++ ++ +LINE_IE +Line interrupt enable +4 +1 ++ +VSYNC_IE +VSYNC interrupt enable +3 +1 ++ +ERR_IE +Synchronization error interrupt + enable +2 +1 ++ +OVR_IE +Overrun interrupt enable +1 +1 ++ +FRAME_IE +Capture complete interrupt + enable +0 +1 ++ +MIS +MIS +masked interrupt status + register +0x10 +0x20 +read-only +0x0000 ++ ++ +LINE_MIS +Line masked interrupt + status +4 +1 ++ +VSYNC_MIS +VSYNC masked interrupt + status +3 +1 ++ +ERR_MIS +Synchronization error masked interrupt + status +2 +1 ++ +OVR_MIS +Overrun masked interrupt + status +1 +1 ++ +FRAME_MIS +Capture complete masked interrupt + status +0 +1 ++ +ICR +ICR +interrupt clear register +0x14 +0x20 +write-only +0x0000 ++ ++ +LINE_ISC +line interrupt status + clear +4 +1 ++ +VSYNC_ISC +Vertical synch interrupt status + clear +3 +1 ++ +ERR_ISC +Synchronization error interrupt status + clear +2 +1 ++ +OVR_ISC +Overrun interrupt status + clear +1 +1 ++ +FRAME_ISC +Capture complete interrupt status + clear +0 +1 ++ +ESCR +ESCR +embedded synchronization code + register +0x18 +0x20 +read-write +0x0000 ++ ++ +FEC +Frame end delimiter code +24 +8 ++ +LEC +Line end delimiter code +16 +8 ++ +LSC +Line start delimiter code +8 +8 ++ +FSC +Frame start delimiter code +0 +8 ++ +ESUR +ESUR +embedded synchronization unmask + register +0x1C +0x20 +read-write +0x0000 ++ ++ +FEU +Frame end delimiter unmask +24 +8 ++ +LEU +Line end delimiter unmask +16 +8 ++ +LSU +Line start delimiter + unmask +8 +8 ++ +FSU +Frame start delimiter + unmask +0 +8 ++ +CWSTRT +CWSTRT +crop window start +0x20 +0x20 +read-write +0x0000 ++ ++ +VST +Vertical start line count +16 +13 ++ +HOFFCNT +Horizontal offset count +0 +14 ++ +CWSIZE +CWSIZE +crop window size +0x24 +0x20 +read-write +0x0000 ++ ++ +VLINE +Vertical line count +16 +14 ++ +CAPCNT +Capture count +0 +14 ++ +DR +DR +data register +0x28 +0x20 +read-only +0x0000 ++ ++ +Byte3 +Data byte 3 +24 +8 ++ +Byte2 +Data byte 2 +16 +8 ++ +Byte1 +Data byte 1 +8 +8 ++ +Byte0 +Data byte 0 +0 +8 ++ +FSMC +Flexible static memory controller +FSMC +0xA0000000 ++ +0x0 +0x400 +registers ++ +FSMC +FSMC global interrupt +48 ++ ++ +BCR1 +BCR1 +SRAM/NOR-Flash chip-select control register + 1 +0x0 +0x20 +read-write +0x000030D0 ++ ++ +CBURSTRW +CBURSTRW +19 +1 ++ +ASYNCWAIT +ASYNCWAIT +15 +1 ++ +EXTMOD +EXTMOD +14 +1 ++ +WAITEN +WAITEN +13 +1 ++ +WREN +WREN +12 +1 ++ +WAITCFG +WAITCFG +11 +1 ++ +WAITPOL +WAITPOL +9 +1 ++ +BURSTEN +BURSTEN +8 +1 ++ +FACCEN +FACCEN +6 +1 ++ +MWID +MWID +4 +2 ++ +MTYP +MTYP +2 +2 ++ +MUXEN +MUXEN +1 +1 ++ +MBKEN +MBKEN +0 +1 ++ +BTR1 +BTR1 +SRAM/NOR-Flash chip-select timing register + 1 +0x4 +0x20 +read-write +0xFFFFFFFF ++ ++ +ACCMOD +ACCMOD +28 +2 ++ +DATLAT +DATLAT +24 +4 ++ +CLKDIV +CLKDIV +20 +4 ++ +BUSTURN +BUSTURN +16 +4 ++ +DATAST +DATAST +8 +8 ++ +ADDHLD +ADDHLD +4 +4 ++ +ADDSET +ADDSET +0 +4 ++ +BCR2 +BCR2 +SRAM/NOR-Flash chip-select control register + 2 +0x8 +0x20 +read-write +0x000030D0 ++ ++ +CBURSTRW +CBURSTRW +19 +1 ++ +ASYNCWAIT +ASYNCWAIT +15 +1 ++ +EXTMOD +EXTMOD +14 +1 ++ +WAITEN +WAITEN +13 +1 ++ +WREN +WREN +12 +1 ++ +WAITCFG +WAITCFG +11 +1 ++ +WRAPMOD +WRAPMOD +10 +1 ++ +WAITPOL +WAITPOL +9 +1 ++ +BURSTEN +BURSTEN +8 +1 ++ +FACCEN +FACCEN +6 +1 ++ +MWID +MWID +4 +2 ++ +MTYP +MTYP +2 +2 ++ +MUXEN +MUXEN +1 +1 ++ +MBKEN +MBKEN +0 +1 ++ +BTR2 +BTR2 +SRAM/NOR-Flash chip-select timing register + 2 +0xC +0x20 +read-write +0xFFFFFFFF ++ ++ +ACCMOD +ACCMOD +28 +2 ++ +DATLAT +DATLAT +24 +4 ++ +CLKDIV +CLKDIV +20 +4 ++ +BUSTURN +BUSTURN +16 +4 ++ +DATAST +DATAST +8 +8 ++ +ADDHLD +ADDHLD +4 +4 ++ +ADDSET +ADDSET +0 +4 ++ +BCR3 +BCR3 +SRAM/NOR-Flash chip-select control register + 3 +0x10 +0x20 +read-write +0x000030D0 ++ ++ +CBURSTRW +CBURSTRW +19 +1 ++ +ASYNCWAIT +ASYNCWAIT +15 +1 ++ +EXTMOD +EXTMOD +14 +1 ++ +WAITEN +WAITEN +13 +1 ++ +WREN +WREN +12 +1 ++ +WAITCFG +WAITCFG +11 +1 ++ +WRAPMOD +WRAPMOD +10 +1 ++ +WAITPOL +WAITPOL +9 +1 ++ +BURSTEN +BURSTEN +8 +1 ++ +FACCEN +FACCEN +6 +1 ++ +MWID +MWID +4 +2 ++ +MTYP +MTYP +2 +2 ++ +MUXEN +MUXEN +1 +1 ++ +MBKEN +MBKEN +0 +1 ++ +BTR3 +BTR3 +SRAM/NOR-Flash chip-select timing register + 3 +0x14 +0x20 +read-write +0xFFFFFFFF ++ ++ +ACCMOD +ACCMOD +28 +2 ++ +DATLAT +DATLAT +24 +4 ++ +CLKDIV +CLKDIV +20 +4 ++ +BUSTURN +BUSTURN +16 +4 ++ +DATAST +DATAST +8 +8 ++ +ADDHLD +ADDHLD +4 +4 ++ +ADDSET +ADDSET +0 +4 ++ +BCR4 +BCR4 +SRAM/NOR-Flash chip-select control register + 4 +0x18 +0x20 +read-write +0x000030D0 ++ ++ +CBURSTRW +CBURSTRW +19 +1 ++ +ASYNCWAIT +ASYNCWAIT +15 +1 ++ +EXTMOD +EXTMOD +14 +1 ++ +WAITEN +WAITEN +13 +1 ++ +WREN +WREN +12 +1 ++ +WAITCFG +WAITCFG +11 +1 ++ +WRAPMOD +WRAPMOD +10 +1 ++ +WAITPOL +WAITPOL +9 +1 ++ +BURSTEN +BURSTEN +8 +1 ++ +FACCEN +FACCEN +6 +1 ++ +MWID +MWID +4 +2 ++ +MTYP +MTYP +2 +2 ++ +MUXEN +MUXEN +1 +1 ++ +MBKEN +MBKEN +0 +1 ++ +BTR4 +BTR4 +SRAM/NOR-Flash chip-select timing register + 4 +0x1C +0x20 +read-write +0xFFFFFFFF ++ ++ +ACCMOD +ACCMOD +28 +2 ++ +DATLAT +DATLAT +24 +4 ++ +CLKDIV +CLKDIV +20 +4 ++ +BUSTURN +BUSTURN +16 +4 ++ +DATAST +DATAST +8 +8 ++ +ADDHLD +ADDHLD +4 +4 ++ +ADDSET +ADDSET +0 +4 ++ +PCR2 +PCR2 +PC Card/NAND Flash control register + 2 +0x60 +0x20 +read-write +0x00000018 ++ ++ +ECCPS +ECCPS +17 +3 ++ +TAR +TAR +13 +4 ++ +TCLR +TCLR +9 +4 ++ +ECCEN +ECCEN +6 +1 ++ +PWID +PWID +4 +2 ++ +PTYP +PTYP +3 +1 ++ +PBKEN +PBKEN +2 +1 ++ +PWAITEN +PWAITEN +1 +1 ++ +SR2 +SR2 +FIFO status and interrupt register + 2 +0x64 +0x20 +0x00000040 ++ ++ +FEMPT +FEMPT +6 +1 +read-only ++ +IFEN +IFEN +5 +1 +read-write ++ +ILEN +ILEN +4 +1 +read-write ++ +IREN +IREN +3 +1 +read-write ++ +IFS +IFS +2 +1 +read-write ++ +ILS +ILS +1 +1 +read-write ++ +IRS +IRS +0 +1 +read-write ++ +PMEM2 +PMEM2 +Common memory space timing register + 2 +0x68 +0x20 +read-write +0xFCFCFCFC ++ ++ +MEMHIZx +MEMHIZx +24 +8 ++ +MEMHOLDx +MEMHOLDx +16 +8 ++ +MEMWAITx +MEMWAITx +8 +8 ++ +MEMSETx +MEMSETx +0 +8 ++ +PATT2 +PATT2 +Attribute memory space timing register + 2 +0x6C +0x20 +read-write +0xFCFCFCFC ++ ++ +ATTHIZx +ATTHIZx +24 +8 ++ +ATTHOLDx +ATTHOLDx +16 +8 ++ +ATTWAITx +ATTWAITx +8 +8 ++ +ATTSETx +ATTSETx +0 +8 ++ +ECCR2 +ECCR2 +ECC result register 2 +0x74 +0x20 +read-only +0x00000000 ++ ++ +ECCx +ECCx +0 +32 ++ +PCR3 +PCR3 +PC Card/NAND Flash control register + 3 +0x80 +0x20 +read-write +0x00000018 ++ ++ +ECCPS +ECCPS +17 +3 ++ +TAR +TAR +13 +4 ++ +TCLR +TCLR +9 +4 ++ +ECCEN +ECCEN +6 +1 ++ +PWID +PWID +4 +2 ++ +PTYP +PTYP +3 +1 ++ +PBKEN +PBKEN +2 +1 ++ +PWAITEN +PWAITEN +1 +1 ++ +SR3 +SR3 +FIFO status and interrupt register + 3 +0x84 +0x20 +0x00000040 ++ ++ +FEMPT +FEMPT +6 +1 +read-only ++ +IFEN +IFEN +5 +1 +read-write ++ +ILEN +ILEN +4 +1 +read-write ++ +IREN +IREN +3 +1 +read-write ++ +IFS +IFS +2 +1 +read-write ++ +ILS +ILS +1 +1 +read-write ++ +IRS +IRS +0 +1 +read-write ++ +PMEM3 +PMEM3 +Common memory space timing register + 3 +0x88 +0x20 +read-write +0xFCFCFCFC ++ ++ +MEMHIZx +MEMHIZx +24 +8 ++ +MEMHOLDx +MEMHOLDx +16 +8 ++ +MEMWAITx +MEMWAITx +8 +8 ++ +MEMSETx +MEMSETx +0 +8 ++ +PATT3 +PATT3 +Attribute memory space timing register + 3 +0x8C +0x20 +read-write +0xFCFCFCFC ++ ++ +ATTHIZx +ATTHIZx +24 +8 ++ +ATTHOLDx +ATTHOLDx +16 +8 ++ +ATTWAITx +ATTWAITx +8 +8 ++ +ATTSETx +ATTSETx +0 +8 ++ +ECCR3 +ECCR3 +ECC result register 3 +0x94 +0x20 +read-only +0x00000000 ++ ++ +ECCx +ECCx +0 +32 ++ +PCR4 +PCR4 +PC Card/NAND Flash control register + 4 +0xA0 +0x20 +read-write +0x00000018 ++ ++ +ECCPS +ECCPS +17 +3 ++ +TAR +TAR +13 +4 ++ +TCLR +TCLR +9 +4 ++ +ECCEN +ECCEN +6 +1 ++ +PWID +PWID +4 +2 ++ +PTYP +PTYP +3 +1 ++ +PBKEN +PBKEN +2 +1 ++ +PWAITEN +PWAITEN +1 +1 ++ +SR4 +SR4 +FIFO status and interrupt register + 4 +0xA4 +0x20 +0x00000040 ++ ++ +FEMPT +FEMPT +6 +1 +read-only ++ +IFEN +IFEN +5 +1 +read-write ++ +ILEN +ILEN +4 +1 +read-write ++ +IREN +IREN +3 +1 +read-write ++ +IFS +IFS +2 +1 +read-write ++ +ILS +ILS +1 +1 +read-write ++ +IRS +IRS +0 +1 +read-write ++ +PMEM4 +PMEM4 +Common memory space timing register + 4 +0xA8 +0x20 +read-write +0xFCFCFCFC ++ ++ +MEMHIZx +MEMHIZx +24 +8 ++ +MEMHOLDx +MEMHOLDx +16 +8 ++ +MEMWAITx +MEMWAITx +8 +8 ++ +MEMSETx +MEMSETx +0 +8 ++ +PATT4 +PATT4 +Attribute memory space timing register + 4 +0xAC +0x20 +read-write +0xFCFCFCFC ++ ++ +ATTHIZx +ATTHIZx +24 +8 ++ +ATTHOLDx +ATTHOLDx +16 +8 ++ +ATTWAITx +ATTWAITx +8 +8 ++ +ATTSETx +ATTSETx +0 +8 ++ +PIO4 +PIO4 +I/O space timing register 4 +0xB0 +0x20 +read-write +0xFCFCFCFC ++ ++ +IOHIZx +IOHIZx +24 +8 ++ +IOHOLDx +IOHOLDx +16 +8 ++ +IOWAITx +IOWAITx +8 +8 ++ +IOSETx +IOSETx +0 +8 ++ +BWTR1 +BWTR1 +SRAM/NOR-Flash write timing registers + 1 +0x104 +0x20 +read-write +0x0FFFFFFF ++ ++ +ACCMOD +ACCMOD +28 +2 ++ +DATLAT +DATLAT +24 +4 ++ +CLKDIV +CLKDIV +20 +4 ++ +DATAST +DATAST +8 +8 ++ +ADDHLD +ADDHLD +4 +4 ++ +ADDSET +ADDSET +0 +4 ++ +BWTR2 +BWTR2 +SRAM/NOR-Flash write timing registers + 2 +0x10C +0x20 +read-write +0x0FFFFFFF ++ ++ +ACCMOD +ACCMOD +28 +2 ++ +DATLAT +DATLAT +24 +4 ++ +CLKDIV +CLKDIV +20 +4 ++ +DATAST +DATAST +8 +8 ++ +ADDHLD +ADDHLD +4 +4 ++ +ADDSET +ADDSET +0 +4 ++ +BWTR3 +BWTR3 +SRAM/NOR-Flash write timing registers + 3 +0x114 +0x20 +read-write +0x0FFFFFFF ++ ++ +ACCMOD +ACCMOD +28 +2 ++ +DATLAT +DATLAT +24 +4 ++ +CLKDIV +CLKDIV +20 +4 ++ +DATAST +DATAST +8 +8 ++ +ADDHLD +ADDHLD +4 +4 ++ +ADDSET +ADDSET +0 +4 ++ +BWTR4 +BWTR4 +SRAM/NOR-Flash write timing registers + 4 +0x11C +0x20 +read-write +0x0FFFFFFF ++ ++ +ACCMOD +ACCMOD +28 +2 ++ +DATLAT +DATLAT +24 +4 ++ +CLKDIV +CLKDIV +20 +4 ++ +DATAST +DATAST +8 +8 ++ +ADDHLD +ADDHLD +4 +4 ++ +ADDSET +ADDSET +0 +4 ++ +DBG +Debug support +DBG +0xE0042000 ++ +0x0 +0x400 +registers ++ ++ +DBGMCU_IDCODE +DBGMCU_IDCODE +IDCODE +0x0 +0x20 +read-only +0x10006411 ++ ++ +DEV_ID +DEV_ID +0 +12 ++ +REV_ID +REV_ID +16 +16 ++ +DBGMCU_CR +DBGMCU_CR +Control Register +0x4 +0x20 +read-write +0x00000000 ++ ++ +DBG_SLEEP +DBG_SLEEP +0 +1 ++ +DBG_STOP +DBG_STOP +1 +1 ++ +DBG_STANDBY +DBG_STANDBY +2 +1 ++ +TRACE_IOEN +TRACE_IOEN +5 +1 ++ +TRACE_MODE +TRACE_MODE +6 +2 ++ +DBG_I2C2_SMBUS_TIMEOUT +DBG_I2C2_SMBUS_TIMEOUT +16 +1 ++ +DBG_TIM8_STOP +DBG_TIM8_STOP +17 +1 ++ +DBG_TIM5_STOP +DBG_TIM5_STOP +18 +1 ++ +DBG_TIM6_STOP +DBG_TIM6_STOP +19 +1 ++ +DBG_TIM7_STOP +DBG_TIM7_STOP +20 +1 ++ +DBGMCU_APB1_FZ +DBGMCU_APB1_FZ +Debug MCU APB1 Freeze registe +0x8 +0x20 +read-write +0x00000000 ++ ++ +DBG_TIM2_STOP +DBG_TIM2_STOP +0 +1 ++ +DBG_TIM3_STOP +DBG_TIM3 _STOP +1 +1 ++ +DBG_TIM4_STOP +DBG_TIM4_STOP +2 +1 ++ +DBG_TIM5_STOP +DBG_TIM5_STOP +3 +1 ++ +DBG_TIM6_STOP +DBG_TIM6_STOP +4 +1 ++ +DBG_TIM7_STOP +DBG_TIM7_STOP +5 +1 ++ +DBG_TIM12_STOP +DBG_TIM12_STOP +6 +1 ++ +DBG_TIM13_STOP +DBG_TIM13_STOP +7 +1 ++ +DBG_TIM14_STOP +DBG_TIM14_STOP +8 +1 ++ +DBG_WWDG_STOP +DBG_WWDG_STOP +11 +1 ++ +DBG_IWDEG_STOP +DBG_IWDEG_STOP +12 +1 ++ +DBG_J2C1_SMBUS_TIMEOUT +DBG_J2C1_SMBUS_TIMEOUT +21 +1 ++ +DBG_J2C2_SMBUS_TIMEOUT +DBG_J2C2_SMBUS_TIMEOUT +22 +1 ++ +DBG_J2C3SMBUS_TIMEOUT +DBG_J2C3SMBUS_TIMEOUT +23 +1 ++ +DBG_CAN1_STOP +DBG_CAN1_STOP +25 +1 ++ +DBG_CAN2_STOP +DBG_CAN2_STOP +26 +1 ++ +DBGMCU_APB2_FZ +DBGMCU_APB2_FZ +Debug MCU APB2 Freeze registe +0xC +0x20 +read-write +0x00000000 ++ ++ +DBG_TIM1_STOP +TIM1 counter stopped when core is + halted +0 +1 ++ +DBG_TIM8_STOP +TIM8 counter stopped when core is + halted +1 +1 ++ +DBG_TIM9_STOP +TIM9 counter stopped when core is + halted +16 +1 ++ +DBG_TIM10_STOP +TIM10 counter stopped when core is + halted +17 +1 ++ +DBG_TIM11_STOP +TIM11 counter stopped when core is + halted +18 +1 ++ +DMA2 +DMA controller +DMA +0x40026400 ++ +0x0 +0x400 +registers ++ +DMA2_Stream0 +DMA2 Stream0 global interrupt +56 ++ +DMA2_Stream1 +DMA2 Stream1 global interrupt +57 ++ +DMA2_Stream2 +DMA2 Stream2 global interrupt +58 ++ +DMA2_Stream3 +DMA2 Stream3 global interrupt +59 ++ +DMA2_Stream4 +DMA2 Stream4 global interrupt +60 ++ +DMA2_Stream5 +DMA2 Stream5 global interrupt +68 ++ +DMA2_Stream6 +DMA2 Stream6 global interrupt +69 ++ +DMA2_Stream7 +DMA2 Stream7 global interrupt +70 ++ ++ +LISR +LISR +low interrupt status register +0x0 +0x20 +read-only +0x00000000 ++ ++ +TCIF3 +Stream x transfer complete interrupt + flag (x = 3..0) +27 +1 ++ +HTIF3 +Stream x half transfer interrupt flag + (x=3..0) +26 +1 ++ +TEIF3 +Stream x transfer error interrupt flag + (x=3..0) +25 +1 ++ +DMEIF3 +Stream x direct mode error interrupt + flag (x=3..0) +24 +1 ++ +FEIF3 +Stream x FIFO error interrupt flag + (x=3..0) +22 +1 ++ +TCIF2 +Stream x transfer complete interrupt + flag (x = 3..0) +21 +1 ++ +HTIF2 +Stream x half transfer interrupt flag + (x=3..0) +20 +1 ++ +TEIF2 +Stream x transfer error interrupt flag + (x=3..0) +19 +1 ++ +DMEIF2 +Stream x direct mode error interrupt + flag (x=3..0) +18 +1 ++ +FEIF2 +Stream x FIFO error interrupt flag + (x=3..0) +16 +1 ++ +TCIF1 +Stream x transfer complete interrupt + flag (x = 3..0) +11 +1 ++ +HTIF1 +Stream x half transfer interrupt flag + (x=3..0) +10 +1 ++ +TEIF1 +Stream x transfer error interrupt flag + (x=3..0) +9 +1 ++ +DMEIF1 +Stream x direct mode error interrupt + flag (x=3..0) +8 +1 ++ +FEIF1 +Stream x FIFO error interrupt flag + (x=3..0) +6 +1 ++ +TCIF0 +Stream x transfer complete interrupt + flag (x = 3..0) +5 +1 ++ +HTIF0 +Stream x half transfer interrupt flag + (x=3..0) +4 +1 ++ +TEIF0 +Stream x transfer error interrupt flag + (x=3..0) +3 +1 ++ +DMEIF0 +Stream x direct mode error interrupt + flag (x=3..0) +2 +1 ++ +FEIF0 +Stream x FIFO error interrupt flag + (x=3..0) +0 +1 ++ +HISR +HISR +high interrupt status register +0x4 +0x20 +read-only +0x00000000 ++ ++ +TCIF7 +Stream x transfer complete interrupt + flag (x=7..4) +27 +1 ++ +HTIF7 +Stream x half transfer interrupt flag + (x=7..4) +26 +1 ++ +TEIF7 +Stream x transfer error interrupt flag + (x=7..4) +25 +1 ++ +DMEIF7 +Stream x direct mode error interrupt + flag (x=7..4) +24 +1 ++ +FEIF7 +Stream x FIFO error interrupt flag + (x=7..4) +22 +1 ++ +TCIF6 +Stream x transfer complete interrupt + flag (x=7..4) +21 +1 ++ +HTIF6 +Stream x half transfer interrupt flag + (x=7..4) +20 +1 ++ +TEIF6 +Stream x transfer error interrupt flag + (x=7..4) +19 +1 ++ +DMEIF6 +Stream x direct mode error interrupt + flag (x=7..4) +18 +1 ++ +FEIF6 +Stream x FIFO error interrupt flag + (x=7..4) +16 +1 ++ +TCIF5 +Stream x transfer complete interrupt + flag (x=7..4) +11 +1 ++ +HTIF5 +Stream x half transfer interrupt flag + (x=7..4) +10 +1 ++ +TEIF5 +Stream x transfer error interrupt flag + (x=7..4) +9 +1 ++ +DMEIF5 +Stream x direct mode error interrupt + flag (x=7..4) +8 +1 ++ +FEIF5 +Stream x FIFO error interrupt flag + (x=7..4) +6 +1 ++ +TCIF4 +Stream x transfer complete interrupt + flag (x=7..4) +5 +1 ++ +HTIF4 +Stream x half transfer interrupt flag + (x=7..4) +4 +1 ++ +TEIF4 +Stream x transfer error interrupt flag + (x=7..4) +3 +1 ++ +DMEIF4 +Stream x direct mode error interrupt + flag (x=7..4) +2 +1 ++ +FEIF4 +Stream x FIFO error interrupt flag + (x=7..4) +0 +1 ++ +LIFCR +LIFCR +low interrupt flag clear + register +0x8 +0x20 +read-write +0x00000000 ++ ++ +CTCIF3 +Stream x clear transfer complete + interrupt flag (x = 3..0) +27 +1 ++ +CHTIF3 +Stream x clear half transfer interrupt + flag (x = 3..0) +26 +1 ++ +CTEIF3 +Stream x clear transfer error interrupt + flag (x = 3..0) +25 +1 ++ +CDMEIF3 +Stream x clear direct mode error + interrupt flag (x = 3..0) +24 +1 ++ +CFEIF3 +Stream x clear FIFO error interrupt flag + (x = 3..0) +22 +1 ++ +CTCIF2 +Stream x clear transfer complete + interrupt flag (x = 3..0) +21 +1 ++ +CHTIF2 +Stream x clear half transfer interrupt + flag (x = 3..0) +20 +1 ++ +CTEIF2 +Stream x clear transfer error interrupt + flag (x = 3..0) +19 +1 ++ +CDMEIF2 +Stream x clear direct mode error + interrupt flag (x = 3..0) +18 +1 ++ +CFEIF2 +Stream x clear FIFO error interrupt flag + (x = 3..0) +16 +1 ++ +CTCIF1 +Stream x clear transfer complete + interrupt flag (x = 3..0) +11 +1 ++ +CHTIF1 +Stream x clear half transfer interrupt + flag (x = 3..0) +10 +1 ++ +CTEIF1 +Stream x clear transfer error interrupt + flag (x = 3..0) +9 +1 ++ +CDMEIF1 +Stream x clear direct mode error + interrupt flag (x = 3..0) +8 +1 ++ +CFEIF1 +Stream x clear FIFO error interrupt flag + (x = 3..0) +6 +1 ++ +CTCIF0 +Stream x clear transfer complete + interrupt flag (x = 3..0) +5 +1 ++ +CHTIF0 +Stream x clear half transfer interrupt + flag (x = 3..0) +4 +1 ++ +CTEIF0 +Stream x clear transfer error interrupt + flag (x = 3..0) +3 +1 ++ +CDMEIF0 +Stream x clear direct mode error + interrupt flag (x = 3..0) +2 +1 ++ +CFEIF0 +Stream x clear FIFO error interrupt flag + (x = 3..0) +0 +1 ++ +HIFCR +HIFCR +high interrupt flag clear + register +0xC +0x20 +read-write +0x00000000 ++ ++ +CTCIF7 +Stream x clear transfer complete + interrupt flag (x = 7..4) +27 +1 ++ +CHTIF7 +Stream x clear half transfer interrupt + flag (x = 7..4) +26 +1 ++ +CTEIF7 +Stream x clear transfer error interrupt + flag (x = 7..4) +25 +1 ++ +CDMEIF7 +Stream x clear direct mode error + interrupt flag (x = 7..4) +24 +1 ++ +CFEIF7 +Stream x clear FIFO error interrupt flag + (x = 7..4) +22 +1 ++ +CTCIF6 +Stream x clear transfer complete + interrupt flag (x = 7..4) +21 +1 ++ +CHTIF6 +Stream x clear half transfer interrupt + flag (x = 7..4) +20 +1 ++ +CTEIF6 +Stream x clear transfer error interrupt + flag (x = 7..4) +19 +1 ++ +CDMEIF6 +Stream x clear direct mode error + interrupt flag (x = 7..4) +18 +1 ++ +CFEIF6 +Stream x clear FIFO error interrupt flag + (x = 7..4) +16 +1 ++ +CTCIF5 +Stream x clear transfer complete + interrupt flag (x = 7..4) +11 +1 ++ +CHTIF5 +Stream x clear half transfer interrupt + flag (x = 7..4) +10 +1 ++ +CTEIF5 +Stream x clear transfer error interrupt + flag (x = 7..4) +9 +1 ++ +CDMEIF5 +Stream x clear direct mode error + interrupt flag (x = 7..4) +8 +1 ++ +CFEIF5 +Stream x clear FIFO error interrupt flag + (x = 7..4) +6 +1 ++ +CTCIF4 +Stream x clear transfer complete + interrupt flag (x = 7..4) +5 +1 ++ +CHTIF4 +Stream x clear half transfer interrupt + flag (x = 7..4) +4 +1 ++ +CTEIF4 +Stream x clear transfer error interrupt + flag (x = 7..4) +3 +1 ++ +CDMEIF4 +Stream x clear direct mode error + interrupt flag (x = 7..4) +2 +1 ++ +CFEIF4 +Stream x clear FIFO error interrupt flag + (x = 7..4) +0 +1 ++ +S0CR +S0CR +stream x configuration + register +0x10 +0x20 +read-write +0x00000000 ++ ++ +CHSEL +Channel selection +25 +3 ++ +MBURST +Memory burst transfer + configuration +23 +2 ++ +PBURST +Peripheral burst transfer + configuration +21 +2 ++ +CT +Current target (only in double buffer + mode) +19 +1 ++ +DBM +Double buffer mode +18 +1 ++ +PL +Priority level +16 +2 ++ +PINCOS +Peripheral increment offset + size +15 +1 ++ +MSIZE +Memory data size +13 +2 ++ +PSIZE +Peripheral data size +11 +2 ++ +MINC +Memory increment mode +10 +1 ++ +PINC +Peripheral increment mode +9 +1 ++ +CIRC +Circular mode +8 +1 ++ +DIR +Data transfer direction +6 +2 ++ +PFCTRL +Peripheral flow controller +5 +1 ++ +TCIE +Transfer complete interrupt + enable +4 +1 ++ +HTIE +Half transfer interrupt + enable +3 +1 ++ +TEIE +Transfer error interrupt + enable +2 +1 ++ +DMEIE +Direct mode error interrupt + enable +1 +1 ++ +EN +Stream enable / flag stream ready when + read low +0 +1 ++ +S0NDTR +S0NDTR +stream x number of data + register +0x14 +0x20 +read-write +0x00000000 ++ ++ +NDT +Number of data items to + transfer +0 +16 ++ +S0PAR +S0PAR +stream x peripheral address + register +0x18 +0x20 +read-write +0x00000000 ++ ++ +PA +Peripheral address +0 +32 ++ +S0M0AR +S0M0AR +stream x memory 0 address + register +0x1C +0x20 +read-write +0x00000000 ++ ++ +M0A +Memory 0 address +0 +32 ++ +S0M1AR +S0M1AR +stream x memory 1 address + register +0x20 +0x20 +read-write +0x00000000 ++ ++ +M1A +Memory 1 address (used in case of Double + buffer mode) +0 +32 ++ +S0FCR +S0FCR +stream x FIFO control register +0x24 +0x20 +0x00000021 ++ ++ +FEIE +FIFO error interrupt + enable +7 +1 +read-write ++ +FS +FIFO status +3 +3 +read-only ++ +DMDIS +Direct mode disable +2 +1 +read-write ++ +FTH +FIFO threshold selection +0 +2 +read-write ++ +S1CR +S1CR +stream x configuration + register +0x28 +0x20 +read-write +0x00000000 ++ ++ +CHSEL +Channel selection +25 +3 ++ +MBURST +Memory burst transfer + configuration +23 +2 ++ +PBURST +Peripheral burst transfer + configuration +21 +2 ++ +ACK +ACK +20 +1 ++ +CT +Current target (only in double buffer + mode) +19 +1 ++ +DBM +Double buffer mode +18 +1 ++ +PL +Priority level +16 +2 ++ +PINCOS +Peripheral increment offset + size +15 +1 ++ +MSIZE +Memory data size +13 +2 ++ +PSIZE +Peripheral data size +11 +2 ++ +MINC +Memory increment mode +10 +1 ++ +PINC +Peripheral increment mode +9 +1 ++ +CIRC +Circular mode +8 +1 ++ +DIR +Data transfer direction +6 +2 ++ +PFCTRL +Peripheral flow controller +5 +1 ++ +TCIE +Transfer complete interrupt + enable +4 +1 ++ +HTIE +Half transfer interrupt + enable +3 +1 ++ +TEIE +Transfer error interrupt + enable +2 +1 ++ +DMEIE +Direct mode error interrupt + enable +1 +1 ++ +EN +Stream enable / flag stream ready when + read low +0 +1 ++ +S1NDTR +S1NDTR +stream x number of data + register +0x2C +0x20 +read-write +0x00000000 ++ ++ +NDT +Number of data items to + transfer +0 +16 ++ +S1PAR +S1PAR +stream x peripheral address + register +0x30 +0x20 +read-write +0x00000000 ++ ++ +PA +Peripheral address +0 +32 ++ +S1M0AR +S1M0AR +stream x memory 0 address + register +0x34 +0x20 +read-write +0x00000000 ++ ++ +M0A +Memory 0 address +0 +32 ++ +S1M1AR +S1M1AR +stream x memory 1 address + register +0x38 +0x20 +read-write +0x00000000 ++ ++ +M1A +Memory 1 address (used in case of Double + buffer mode) +0 +32 ++ +S1FCR +S1FCR +stream x FIFO control register +0x3C +0x20 +0x00000021 ++ ++ +FEIE +FIFO error interrupt + enable +7 +1 +read-write ++ +FS +FIFO status +3 +3 +read-only ++ +DMDIS +Direct mode disable +2 +1 +read-write ++ +FTH +FIFO threshold selection +0 +2 +read-write ++ +S2CR +S2CR +stream x configuration + register +0x40 +0x20 +read-write +0x00000000 ++ ++ +CHSEL +Channel selection +25 +3 ++ +MBURST +Memory burst transfer + configuration +23 +2 ++ +PBURST +Peripheral burst transfer + configuration +21 +2 ++ +ACK +ACK +20 +1 ++ +CT +Current target (only in double buffer + mode) +19 +1 ++ +DBM +Double buffer mode +18 +1 ++ +PL +Priority level +16 +2 ++ +PINCOS +Peripheral increment offset + size +15 +1 ++ +MSIZE +Memory data size +13 +2 ++ +PSIZE +Peripheral data size +11 +2 ++ +MINC +Memory increment mode +10 +1 ++ +PINC +Peripheral increment mode +9 +1 ++ +CIRC +Circular mode +8 +1 ++ +DIR +Data transfer direction +6 +2 ++ +PFCTRL +Peripheral flow controller +5 +1 ++ +TCIE +Transfer complete interrupt + enable +4 +1 ++ +HTIE +Half transfer interrupt + enable +3 +1 ++ +TEIE +Transfer error interrupt + enable +2 +1 ++ +DMEIE +Direct mode error interrupt + enable +1 +1 ++ +EN +Stream enable / flag stream ready when + read low +0 +1 ++ +S2NDTR +S2NDTR +stream x number of data + register +0x44 +0x20 +read-write +0x00000000 ++ ++ +NDT +Number of data items to + transfer +0 +16 ++ +S2PAR +S2PAR +stream x peripheral address + register +0x48 +0x20 +read-write +0x00000000 ++ ++ +PA +Peripheral address +0 +32 ++ +S2M0AR +S2M0AR +stream x memory 0 address + register +0x4C +0x20 +read-write +0x00000000 ++ ++ +M0A +Memory 0 address +0 +32 ++ +S2M1AR +S2M1AR +stream x memory 1 address + register +0x50 +0x20 +read-write +0x00000000 ++ ++ +M1A +Memory 1 address (used in case of Double + buffer mode) +0 +32 ++ +S2FCR +S2FCR +stream x FIFO control register +0x54 +0x20 +0x00000021 ++ ++ +FEIE +FIFO error interrupt + enable +7 +1 +read-write ++ +FS +FIFO status +3 +3 +read-only ++ +DMDIS +Direct mode disable +2 +1 +read-write ++ +FTH +FIFO threshold selection +0 +2 +read-write ++ +S3CR +S3CR +stream x configuration + register +0x58 +0x20 +read-write +0x00000000 ++ ++ +CHSEL +Channel selection +25 +3 ++ +MBURST +Memory burst transfer + configuration +23 +2 ++ +PBURST +Peripheral burst transfer + configuration +21 +2 ++ +ACK +ACK +20 +1 ++ +CT +Current target (only in double buffer + mode) +19 +1 ++ +DBM +Double buffer mode +18 +1 ++ +PL +Priority level +16 +2 ++ +PINCOS +Peripheral increment offset + size +15 +1 ++ +MSIZE +Memory data size +13 +2 ++ +PSIZE +Peripheral data size +11 +2 ++ +MINC +Memory increment mode +10 +1 ++ +PINC +Peripheral increment mode +9 +1 ++ +CIRC +Circular mode +8 +1 ++ +DIR +Data transfer direction +6 +2 ++ +PFCTRL +Peripheral flow controller +5 +1 ++ +TCIE +Transfer complete interrupt + enable +4 +1 ++ +HTIE +Half transfer interrupt + enable +3 +1 ++ +TEIE +Transfer error interrupt + enable +2 +1 ++ +DMEIE +Direct mode error interrupt + enable +1 +1 ++ +EN +Stream enable / flag stream ready when + read low +0 +1 ++ +S3NDTR +S3NDTR +stream x number of data + register +0x5C +0x20 +read-write +0x00000000 ++ ++ +NDT +Number of data items to + transfer +0 +16 ++ +S3PAR +S3PAR +stream x peripheral address + register +0x60 +0x20 +read-write +0x00000000 ++ ++ +PA +Peripheral address +0 +32 ++ +S3M0AR +S3M0AR +stream x memory 0 address + register +0x64 +0x20 +read-write +0x00000000 ++ ++ +M0A +Memory 0 address +0 +32 ++ +S3M1AR +S3M1AR +stream x memory 1 address + register +0x68 +0x20 +read-write +0x00000000 ++ ++ +M1A +Memory 1 address (used in case of Double + buffer mode) +0 +32 ++ +S3FCR +S3FCR +stream x FIFO control register +0x6C +0x20 +0x00000021 ++ ++ +FEIE +FIFO error interrupt + enable +7 +1 +read-write ++ +FS +FIFO status +3 +3 +read-only ++ +DMDIS +Direct mode disable +2 +1 +read-write ++ +FTH +FIFO threshold selection +0 +2 +read-write ++ +S4CR +S4CR +stream x configuration + register +0x70 +0x20 +read-write +0x00000000 ++ ++ +CHSEL +Channel selection +25 +3 ++ +MBURST +Memory burst transfer + configuration +23 +2 ++ +PBURST +Peripheral burst transfer + configuration +21 +2 ++ +ACK +ACK +20 +1 ++ +CT +Current target (only in double buffer + mode) +19 +1 ++ +DBM +Double buffer mode +18 +1 ++ +PL +Priority level +16 +2 ++ +PINCOS +Peripheral increment offset + size +15 +1 ++ +MSIZE +Memory data size +13 +2 ++ +PSIZE +Peripheral data size +11 +2 ++ +MINC +Memory increment mode +10 +1 ++ +PINC +Peripheral increment mode +9 +1 ++ +CIRC +Circular mode +8 +1 ++ +DIR +Data transfer direction +6 +2 ++ +PFCTRL +Peripheral flow controller +5 +1 ++ +TCIE +Transfer complete interrupt + enable +4 +1 ++ +HTIE +Half transfer interrupt + enable +3 +1 ++ +TEIE +Transfer error interrupt + enable +2 +1 ++ +DMEIE +Direct mode error interrupt + enable +1 +1 ++ +EN +Stream enable / flag stream ready when + read low +0 +1 ++ +S4NDTR +S4NDTR +stream x number of data + register +0x74 +0x20 +read-write +0x00000000 ++ ++ +NDT +Number of data items to + transfer +0 +16 ++ +S4PAR +S4PAR +stream x peripheral address + register +0x78 +0x20 +read-write +0x00000000 ++ ++ +PA +Peripheral address +0 +32 ++ +S4M0AR +S4M0AR +stream x memory 0 address + register +0x7C +0x20 +read-write +0x00000000 ++ ++ +M0A +Memory 0 address +0 +32 ++ +S4M1AR +S4M1AR +stream x memory 1 address + register +0x80 +0x20 +read-write +0x00000000 ++ ++ +M1A +Memory 1 address (used in case of Double + buffer mode) +0 +32 ++ +S4FCR +S4FCR +stream x FIFO control register +0x84 +0x20 +0x00000021 ++ ++ +FEIE +FIFO error interrupt + enable +7 +1 +read-write ++ +FS +FIFO status +3 +3 +read-only ++ +DMDIS +Direct mode disable +2 +1 +read-write ++ +FTH +FIFO threshold selection +0 +2 +read-write ++ +S5CR +S5CR +stream x configuration + register +0x88 +0x20 +read-write +0x00000000 ++ ++ +CHSEL +Channel selection +25 +3 ++ +MBURST +Memory burst transfer + configuration +23 +2 ++ +PBURST +Peripheral burst transfer + configuration +21 +2 ++ +ACK +ACK +20 +1 ++ +CT +Current target (only in double buffer + mode) +19 +1 ++ +DBM +Double buffer mode +18 +1 ++ +PL +Priority level +16 +2 ++ +PINCOS +Peripheral increment offset + size +15 +1 ++ +MSIZE +Memory data size +13 +2 ++ +PSIZE +Peripheral data size +11 +2 ++ +MINC +Memory increment mode +10 +1 ++ +PINC +Peripheral increment mode +9 +1 ++ +CIRC +Circular mode +8 +1 ++ +DIR +Data transfer direction +6 +2 ++ +PFCTRL +Peripheral flow controller +5 +1 ++ +TCIE +Transfer complete interrupt + enable +4 +1 ++ +HTIE +Half transfer interrupt + enable +3 +1 ++ +TEIE +Transfer error interrupt + enable +2 +1 ++ +DMEIE +Direct mode error interrupt + enable +1 +1 ++ +EN +Stream enable / flag stream ready when + read low +0 +1 ++ +S5NDTR +S5NDTR +stream x number of data + register +0x8C +0x20 +read-write +0x00000000 ++ ++ +NDT +Number of data items to + transfer +0 +16 ++ +S5PAR +S5PAR +stream x peripheral address + register +0x90 +0x20 +read-write +0x00000000 ++ ++ +PA +Peripheral address +0 +32 ++ +S5M0AR +S5M0AR +stream x memory 0 address + register +0x94 +0x20 +read-write +0x00000000 ++ ++ +M0A +Memory 0 address +0 +32 ++ +S5M1AR +S5M1AR +stream x memory 1 address + register +0x98 +0x20 +read-write +0x00000000 ++ ++ +M1A +Memory 1 address (used in case of Double + buffer mode) +0 +32 ++ +S5FCR +S5FCR +stream x FIFO control register +0x9C +0x20 +0x00000021 ++ ++ +FEIE +FIFO error interrupt + enable +7 +1 +read-write ++ +FS +FIFO status +3 +3 +read-only ++ +DMDIS +Direct mode disable +2 +1 +read-write ++ +FTH +FIFO threshold selection +0 +2 +read-write ++ +S6CR +S6CR +stream x configuration + register +0xA0 +0x20 +read-write +0x00000000 ++ ++ +CHSEL +Channel selection +25 +3 ++ +MBURST +Memory burst transfer + configuration +23 +2 ++ +PBURST +Peripheral burst transfer + configuration +21 +2 ++ +ACK +ACK +20 +1 ++ +CT +Current target (only in double buffer + mode) +19 +1 ++ +DBM +Double buffer mode +18 +1 ++ +PL +Priority level +16 +2 ++ +PINCOS +Peripheral increment offset + size +15 +1 ++ +MSIZE +Memory data size +13 +2 ++ +PSIZE +Peripheral data size +11 +2 ++ +MINC +Memory increment mode +10 +1 ++ +PINC +Peripheral increment mode +9 +1 ++ +CIRC +Circular mode +8 +1 ++ +DIR +Data transfer direction +6 +2 ++ +PFCTRL +Peripheral flow controller +5 +1 ++ +TCIE +Transfer complete interrupt + enable +4 +1 ++ +HTIE +Half transfer interrupt + enable +3 +1 ++ +TEIE +Transfer error interrupt + enable +2 +1 ++ +DMEIE +Direct mode error interrupt + enable +1 +1 ++ +EN +Stream enable / flag stream ready when + read low +0 +1 ++ +S6NDTR +S6NDTR +stream x number of data + register +0xA4 +0x20 +read-write +0x00000000 ++ ++ +NDT +Number of data items to + transfer +0 +16 ++ +S6PAR +S6PAR +stream x peripheral address + register +0xA8 +0x20 +read-write +0x00000000 ++ ++ +PA +Peripheral address +0 +32 ++ +S6M0AR +S6M0AR +stream x memory 0 address + register +0xAC +0x20 +read-write +0x00000000 ++ ++ +M0A +Memory 0 address +0 +32 ++ +S6M1AR +S6M1AR +stream x memory 1 address + register +0xB0 +0x20 +read-write +0x00000000 ++ ++ +M1A +Memory 1 address (used in case of Double + buffer mode) +0 +32 ++ +S6FCR +S6FCR +stream x FIFO control register +0xB4 +0x20 +0x00000021 ++ ++ +FEIE +FIFO error interrupt + enable +7 +1 +read-write ++ +FS +FIFO status +3 +3 +read-only ++ +DMDIS +Direct mode disable +2 +1 +read-write ++ +FTH +FIFO threshold selection +0 +2 +read-write ++ +S7CR +S7CR +stream x configuration + register +0xB8 +0x20 +read-write +0x00000000 ++ ++ +CHSEL +Channel selection +25 +3 ++ +MBURST +Memory burst transfer + configuration +23 +2 ++ +PBURST +Peripheral burst transfer + configuration +21 +2 ++ +ACK +ACK +20 +1 ++ +CT +Current target (only in double buffer + mode) +19 +1 ++ +DBM +Double buffer mode +18 +1 ++ +PL +Priority level +16 +2 ++ +PINCOS +Peripheral increment offset + size +15 +1 ++ +MSIZE +Memory data size +13 +2 ++ +PSIZE +Peripheral data size +11 +2 ++ +MINC +Memory increment mode +10 +1 ++ +PINC +Peripheral increment mode +9 +1 ++ +CIRC +Circular mode +8 +1 ++ +DIR +Data transfer direction +6 +2 ++ +PFCTRL +Peripheral flow controller +5 +1 ++ +TCIE +Transfer complete interrupt + enable +4 +1 ++ +HTIE +Half transfer interrupt + enable +3 +1 ++ +TEIE +Transfer error interrupt + enable +2 +1 ++ +DMEIE +Direct mode error interrupt + enable +1 +1 ++ +EN +Stream enable / flag stream ready when + read low +0 +1 ++ +S7NDTR +S7NDTR +stream x number of data + register +0xBC +0x20 +read-write +0x00000000 ++ ++ +NDT +Number of data items to + transfer +0 +16 ++ +S7PAR +S7PAR +stream x peripheral address + register +0xC0 +0x20 +read-write +0x00000000 ++ ++ +PA +Peripheral address +0 +32 ++ +S7M0AR +S7M0AR +stream x memory 0 address + register +0xC4 +0x20 +read-write +0x00000000 ++ ++ +M0A +Memory 0 address +0 +32 ++ +S7M1AR +S7M1AR +stream x memory 1 address + register +0xC8 +0x20 +read-write +0x00000000 ++ ++ +M1A +Memory 1 address (used in case of Double + buffer mode) +0 +32 ++ +S7FCR +S7FCR +stream x FIFO control register +0xCC +0x20 +0x00000021 ++ ++ +FEIE +FIFO error interrupt + enable +7 +1 +read-write ++ +FS +FIFO status +3 +3 +read-only ++ +DMDIS +Direct mode disable +2 +1 +read-write ++ +FTH +FIFO threshold selection +0 +2 +read-write ++ +DMA1 +0x40026000 ++ +DMA1_Stream0 +DMA1 Stream0 global interrupt +11 ++ +DMA1_Stream1 +DMA1 Stream1 global interrupt +12 ++ +DMA1_Stream2 +DMA1 Stream2 global interrupt +13 ++ +DMA1_Stream3 +DMA1 Stream3 global interrupt +14 ++ +DMA1_Stream4 +DMA1 Stream4 global interrupt +15 ++ +DMA1_Stream5 +DMA1 Stream5 global interrupt +16 ++ +DMA1_Stream6 +DMA1 Stream6 global interrupt +17 ++ +DMA1_Stream7 +DMA1 Stream7 global interrupt +47 ++ +RCC +Reset and clock control +RCC +0x40023800 ++ +0x0 +0x400 +registers ++ +RCC +RCC global interrupt +5 ++ ++ +CR +CR +clock control register +0x0 +0x20 +0x00000083 ++ ++ +PLLI2SRDY +PLLI2S clock ready flag +27 +1 +read-only ++ +PLLI2SON +PLLI2S enable +26 +1 +read-write ++ +PLLRDY +Main PLL (PLL) clock ready + flag +25 +1 +read-only ++ +PLLON +Main PLL (PLL) enable +24 +1 +read-write ++ +CSSON +Clock security system + enable +19 +1 +read-write ++ +HSEBYP +HSE clock bypass +18 +1 +read-write ++ +HSERDY +HSE clock ready flag +17 +1 +read-only ++ +HSEON +HSE clock enable +16 +1 +read-write ++ +HSICAL +Internal high-speed clock + calibration +8 +8 +read-only ++ +HSITRIM +Internal high-speed clock + trimming +3 +5 +read-write ++ +HSIRDY +Internal high-speed clock ready + flag +1 +1 +read-only ++ +HSION +Internal high-speed clock + enable +0 +1 +read-write ++ +PLLCFGR +PLLCFGR +PLL configuration register +0x4 +0x20 +read-write +0x24003010 ++ ++ +PLLQ3 +Main PLL (PLL) division factor for USB + OTG FS, SDIO and random number generator + clocks +27 +1 ++ +PLLQ2 +Main PLL (PLL) division factor for USB + OTG FS, SDIO and random number generator + clocks +26 +1 ++ +PLLQ1 +Main PLL (PLL) division factor for USB + OTG FS, SDIO and random number generator + clocks +25 +1 ++ +PLLQ0 +Main PLL (PLL) division factor for USB + OTG FS, SDIO and random number generator + clocks +24 +1 ++ +PLLSRC +Main PLL(PLL) and audio PLL (PLLI2S) + entry clock source +22 +1 ++ +PLLP1 +Main PLL (PLL) division factor for main + system clock +17 +1 ++ +PLLP0 +Main PLL (PLL) division factor for main + system clock +16 +1 ++ +PLLN8 +Main PLL (PLL) multiplication factor for + VCO +14 +1 ++ +PLLN7 +Main PLL (PLL) multiplication factor for + VCO +13 +1 ++ +PLLN6 +Main PLL (PLL) multiplication factor for + VCO +12 +1 ++ +PLLN5 +Main PLL (PLL) multiplication factor for + VCO +11 +1 ++ +PLLN4 +Main PLL (PLL) multiplication factor for + VCO +10 +1 ++ +PLLN3 +Main PLL (PLL) multiplication factor for + VCO +9 +1 ++ +PLLN2 +Main PLL (PLL) multiplication factor for + VCO +8 +1 ++ +PLLN1 +Main PLL (PLL) multiplication factor for + VCO +7 +1 ++ +PLLN0 +Main PLL (PLL) multiplication factor for + VCO +6 +1 ++ +PLLM5 +Division factor for the main PLL (PLL) + and audio PLL (PLLI2S) input clock +5 +1 ++ +PLLM4 +Division factor for the main PLL (PLL) + and audio PLL (PLLI2S) input clock +4 +1 ++ +PLLM3 +Division factor for the main PLL (PLL) + and audio PLL (PLLI2S) input clock +3 +1 ++ +PLLM2 +Division factor for the main PLL (PLL) + and audio PLL (PLLI2S) input clock +2 +1 ++ +PLLM1 +Division factor for the main PLL (PLL) + and audio PLL (PLLI2S) input clock +1 +1 ++ +PLLM0 +Division factor for the main PLL (PLL) + and audio PLL (PLLI2S) input clock +0 +1 ++ +CFGR +CFGR +clock configuration register +0x8 +0x20 +0x00000000 ++ ++ +MCO2 +Microcontroller clock output + 2 +30 +2 +read-write ++ +MCO2PRE +MCO2 prescaler +27 +3 +read-write ++ +MCO1PRE +MCO1 prescaler +24 +3 +read-write ++ +I2SSRC +I2S clock selection +23 +1 +read-write ++ +MCO1 +Microcontroller clock output + 1 +21 +2 +read-write ++ +RTCPRE +HSE division factor for RTC + clock +16 +5 +read-write ++ +PPRE2 +APB high-speed prescaler + (APB2) +13 +3 +read-write ++ +PPRE1 +APB Low speed prescaler + (APB1) +10 +3 +read-write ++ +HPRE +AHB prescaler +4 +4 +read-write ++ +SWS1 +System clock switch status +3 +1 +read-only ++ +SWS0 +System clock switch status +2 +1 +read-only ++ +SW1 +System clock switch +1 +1 +read-write ++ +SW0 +System clock switch +0 +1 +read-write ++ +CIR +CIR +clock interrupt register +0xC +0x20 +0x00000000 ++ ++ +CSSC +Clock security system interrupt + clear +23 +1 +write-only ++ +PLLI2SRDYC +PLLI2S ready interrupt + clear +21 +1 +write-only ++ +PLLRDYC +Main PLL(PLL) ready interrupt + clear +20 +1 +write-only ++ +HSERDYC +HSE ready interrupt clear +19 +1 +write-only ++ +HSIRDYC +HSI ready interrupt clear +18 +1 +write-only ++ +LSERDYC +LSE ready interrupt clear +17 +1 +write-only ++ +LSIRDYC +LSI ready interrupt clear +16 +1 +write-only ++ +PLLI2SRDYIE +PLLI2S ready interrupt + enable +13 +1 +read-write ++ +PLLRDYIE +Main PLL (PLL) ready interrupt + enable +12 +1 +read-write ++ +HSERDYIE +HSE ready interrupt enable +11 +1 +read-write ++ +HSIRDYIE +HSI ready interrupt enable +10 +1 +read-write ++ +LSERDYIE +LSE ready interrupt enable +9 +1 +read-write ++ +LSIRDYIE +LSI ready interrupt enable +8 +1 +read-write ++ +CSSF +Clock security system interrupt + flag +7 +1 +read-only ++ +PLLI2SRDYF +PLLI2S ready interrupt + flag +5 +1 +read-only ++ +PLLRDYF +Main PLL (PLL) ready interrupt + flag +4 +1 +read-only ++ +HSERDYF +HSE ready interrupt flag +3 +1 +read-only ++ +HSIRDYF +HSI ready interrupt flag +2 +1 +read-only ++ +LSERDYF +LSE ready interrupt flag +1 +1 +read-only ++ +LSIRDYF +LSI ready interrupt flag +0 +1 +read-only ++ +AHB1RSTR +AHB1RSTR +AHB1 peripheral reset register +0x10 +0x20 +read-write +0x00000000 ++ ++ +OTGHSRST +USB OTG HS module reset +29 +1 ++ +ETHMACRST +Ethernet MAC reset +25 +1 ++ +DMA2RST +DMA2 reset +22 +1 ++ +DMA1RST +DMA2 reset +21 +1 ++ +CRCRST +CRC reset +12 +1 ++ +GPIOIRST +IO port I reset +8 +1 ++ +GPIOHRST +IO port H reset +7 +1 ++ +GPIOGRST +IO port G reset +6 +1 ++ +GPIOFRST +IO port F reset +5 +1 ++ +GPIOERST +IO port E reset +4 +1 ++ +GPIODRST +IO port D reset +3 +1 ++ +GPIOCRST +IO port C reset +2 +1 ++ +GPIOBRST +IO port B reset +1 +1 ++ +GPIOARST +IO port A reset +0 +1 ++ +AHB2RSTR +AHB2RSTR +AHB2 peripheral reset register +0x14 +0x20 +read-write +0x00000000 ++ ++ +OTGFSRST +USB OTG FS module reset +7 +1 ++ +RNGRST +Random number generator module + reset +6 +1 ++ +DCMIRST +Camera interface reset +0 +1 ++ +AHB3RSTR +AHB3RSTR +AHB3 peripheral reset register +0x18 +0x20 +read-write +0x00000000 ++ ++ +FSMCRST +Flexible static memory controller module + reset +0 +1 ++ +APB1RSTR +APB1RSTR +APB1 peripheral reset register +0x20 +0x20 +read-write +0x00000000 ++ ++ +DACRST +DAC reset +29 +1 ++ +PWRRST +Power interface reset +28 +1 ++ +CAN2RST +CAN2 reset +26 +1 ++ +CAN1RST +CAN1 reset +25 +1 ++ +I2C3RST +I2C3 reset +23 +1 ++ +I2C2RST +I2C 2 reset +22 +1 ++ +I2C1RST +I2C 1 reset +21 +1 ++ +UART5RST +USART 5 reset +20 +1 ++ +UART4RST +USART 4 reset +19 +1 ++ +UART3RST +USART 3 reset +18 +1 ++ +UART2RST +USART 2 reset +17 +1 ++ +SPI3RST +SPI 3 reset +15 +1 ++ +SPI2RST +SPI 2 reset +14 +1 ++ +WWDGRST +Window watchdog reset +11 +1 ++ +TIM14RST +TIM14 reset +8 +1 ++ +TIM13RST +TIM13 reset +7 +1 ++ +TIM12RST +TIM12 reset +6 +1 ++ +TIM7RST +TIM7 reset +5 +1 ++ +TIM6RST +TIM6 reset +4 +1 ++ +TIM5RST +TIM5 reset +3 +1 ++ +TIM4RST +TIM4 reset +2 +1 ++ +TIM3RST +TIM3 reset +1 +1 ++ +TIM2RST +TIM2 reset +0 +1 ++ +APB2RSTR +APB2RSTR +APB2 peripheral reset register +0x24 +0x20 +read-write +0x00000000 ++ ++ +TIM11RST +TIM11 reset +18 +1 ++ +TIM10RST +TIM10 reset +17 +1 ++ +TIM9RST +TIM9 reset +16 +1 ++ +SYSCFGRST +System configuration controller + reset +14 +1 ++ +SPI1RST +SPI 1 reset +12 +1 ++ +SDIORST +SDIO reset +11 +1 ++ +ADCRST +ADC interface reset (common to all + ADCs) +8 +1 ++ +USART6RST +USART6 reset +5 +1 ++ +USART1RST +USART1 reset +4 +1 ++ +TIM8RST +TIM8 reset +1 +1 ++ +TIM1RST +TIM1 reset +0 +1 ++ +AHB1ENR +AHB1ENR +AHB1 peripheral clock register +0x30 +0x20 +read-write +0x00100000 ++ ++ +OTGHSULPIEN +USB OTG HSULPI clock + enable +30 +1 ++ +OTGHSEN +USB OTG HS clock enable +29 +1 ++ +ETHMACPTPEN +Ethernet PTP clock enable +28 +1 ++ +ETHMACRXEN +Ethernet Reception clock + enable +27 +1 ++ +ETHMACTXEN +Ethernet Transmission clock + enable +26 +1 ++ +ETHMACEN +Ethernet MAC clock enable +25 +1 ++ +DMA2EN +DMA2 clock enable +22 +1 ++ +DMA1EN +DMA1 clock enable +21 +1 ++ +BKPSRAMEN +Backup SRAM interface clock + enable +18 +1 ++ +CRCEN +CRC clock enable +12 +1 ++ +GPIOIEN +IO port I clock enable +8 +1 ++ +GPIOHEN +IO port H clock enable +7 +1 ++ +GPIOGEN +IO port G clock enable +6 +1 ++ +GPIOFEN +IO port F clock enable +5 +1 ++ +GPIOEEN +IO port E clock enable +4 +1 ++ +GPIODEN +IO port D clock enable +3 +1 ++ +GPIOCEN +IO port C clock enable +2 +1 ++ +GPIOBEN +IO port B clock enable +1 +1 ++ +GPIOAEN +IO port A clock enable +0 +1 ++ +AHB2ENR +AHB2ENR +AHB2 peripheral clock enable + register +0x34 +0x20 +read-write +0x00000000 ++ ++ +OTGFSEN +USB OTG FS clock enable +7 +1 ++ +RNGEN +Random number generator clock + enable +6 +1 ++ +DCMIEN +Camera interface enable +0 +1 ++ +AHB3ENR +AHB3ENR +AHB3 peripheral clock enable + register +0x38 +0x20 +read-write +0x00000000 ++ ++ +FSMCEN +Flexible static memory controller module + clock enable +0 +1 ++ +APB1ENR +APB1ENR +APB1 peripheral clock enable + register +0x40 +0x20 +read-write +0x00000000 ++ ++ +DACEN +DAC interface clock enable +29 +1 ++ +PWREN +Power interface clock + enable +28 +1 ++ +CAN2EN +CAN 2 clock enable +26 +1 ++ +CAN1EN +CAN 1 clock enable +25 +1 ++ +I2C3EN +I2C3 clock enable +23 +1 ++ +I2C2EN +I2C2 clock enable +22 +1 ++ +I2C1EN +I2C1 clock enable +21 +1 ++ +UART5EN +UART5 clock enable +20 +1 ++ +UART4EN +UART4 clock enable +19 +1 ++ +USART3EN +USART3 clock enable +18 +1 ++ +USART2EN +USART 2 clock enable +17 +1 ++ +SPI3EN +SPI3 clock enable +15 +1 ++ +SPI2EN +SPI2 clock enable +14 +1 ++ +WWDGEN +Window watchdog clock + enable +11 +1 ++ +TIM14EN +TIM14 clock enable +8 +1 ++ +TIM13EN +TIM13 clock enable +7 +1 ++ +TIM12EN +TIM12 clock enable +6 +1 ++ +TIM7EN +TIM7 clock enable +5 +1 ++ +TIM6EN +TIM6 clock enable +4 +1 ++ +TIM5EN +TIM5 clock enable +3 +1 ++ +TIM4EN +TIM4 clock enable +2 +1 ++ +TIM3EN +TIM3 clock enable +1 +1 ++ +TIM2EN +TIM2 clock enable +0 +1 ++ +APB2ENR +APB2ENR +APB2 peripheral clock enable + register +0x44 +0x20 +read-write +0x00000000 ++ ++ +TIM11EN +TIM11 clock enable +18 +1 ++ +TIM10EN +TIM10 clock enable +17 +1 ++ +TIM9EN +TIM9 clock enable +16 +1 ++ +SYSCFGEN +System configuration controller clock + enable +14 +1 ++ +SPI1EN +SPI1 clock enable +12 +1 ++ +SDIOEN +SDIO clock enable +11 +1 ++ +ADC3EN +ADC3 clock enable +10 +1 ++ +ADC2EN +ADC2 clock enable +9 +1 ++ +ADC1EN +ADC1 clock enable +8 +1 ++ +USART6EN +USART6 clock enable +5 +1 ++ +USART1EN +USART1 clock enable +4 +1 ++ +TIM8EN +TIM8 clock enable +1 +1 ++ +TIM1EN +TIM1 clock enable +0 +1 ++ +AHB1LPENR +AHB1LPENR +AHB1 peripheral clock enable in low power + mode register +0x50 +0x20 +read-write +0x7E6791FF ++ ++ +OTGHSULPILPEN +USB OTG HS ULPI clock enable during + Sleep mode +30 +1 ++ +OTGHSLPEN +USB OTG HS clock enable during Sleep + mode +29 +1 ++ +ETHMACPTPLPEN +Ethernet PTP clock enable during Sleep + mode +28 +1 ++ +ETHMACRXLPEN +Ethernet reception clock enable during + Sleep mode +27 +1 ++ +ETHMACTXLPEN +Ethernet transmission clock enable + during Sleep mode +26 +1 ++ +ETHMACLPEN +Ethernet MAC clock enable during Sleep + mode +25 +1 ++ +DMA2LPEN +DMA2 clock enable during Sleep + mode +22 +1 ++ +DMA1LPEN +DMA1 clock enable during Sleep + mode +21 +1 ++ +BKPSRAMLPEN +Backup SRAM interface clock enable + during Sleep mode +18 +1 ++ +SRAM2LPEN +SRAM 2 interface clock enable during + Sleep mode +17 +1 ++ +SRAM1LPEN +SRAM 1interface clock enable during + Sleep mode +16 +1 ++ +FLITFLPEN +Flash interface clock enable during + Sleep mode +15 +1 ++ +CRCLPEN +CRC clock enable during Sleep + mode +12 +1 ++ +GPIOILPEN +IO port I clock enable during Sleep + mode +8 +1 ++ +GPIOHLPEN +IO port H clock enable during Sleep + mode +7 +1 ++ +GPIOGLPEN +IO port G clock enable during Sleep + mode +6 +1 ++ +GPIOFLPEN +IO port F clock enable during Sleep + mode +5 +1 ++ +GPIOELPEN +IO port E clock enable during Sleep + mode +4 +1 ++ +GPIODLPEN +IO port D clock enable during Sleep + mode +3 +1 ++ +GPIOCLPEN +IO port C clock enable during Sleep + mode +2 +1 ++ +GPIOBLPEN +IO port B clock enable during Sleep + mode +1 +1 ++ +GPIOALPEN +IO port A clock enable during sleep + mode +0 +1 ++ +AHB2LPENR +AHB2LPENR +AHB2 peripheral clock enable in low power + mode register +0x54 +0x20 +read-write +0x000000F1 ++ ++ +OTGFSLPEN +USB OTG FS clock enable during Sleep + mode +7 +1 ++ +RNGLPEN +Random number generator clock enable + during Sleep mode +6 +1 ++ +DCMILPEN +Camera interface enable during Sleep + mode +0 +1 ++ +AHB3LPENR +AHB3LPENR +AHB3 peripheral clock enable in low power + mode register +0x58 +0x20 +read-write +0x00000001 ++ ++ +FSMCLPEN +Flexible static memory controller module + clock enable during Sleep mode +0 +1 ++ +APB1LPENR +APB1LPENR +APB1 peripheral clock enable in low power + mode register +0x60 +0x20 +read-write +0x36FEC9FF ++ ++ +DACLPEN +DAC interface clock enable during Sleep + mode +29 +1 ++ +PWRLPEN +Power interface clock enable during + Sleep mode +28 +1 ++ +CAN2LPEN +CAN 2 clock enable during Sleep + mode +26 +1 ++ +CAN1LPEN +CAN 1 clock enable during Sleep + mode +25 +1 ++ +I2C3LPEN +I2C3 clock enable during Sleep + mode +23 +1 ++ +I2C2LPEN +I2C2 clock enable during Sleep + mode +22 +1 ++ +I2C1LPEN +I2C1 clock enable during Sleep + mode +21 +1 ++ +UART5LPEN +UART5 clock enable during Sleep + mode +20 +1 ++ +UART4LPEN +UART4 clock enable during Sleep + mode +19 +1 ++ +USART3LPEN +USART3 clock enable during Sleep + mode +18 +1 ++ +USART2LPEN +USART2 clock enable during Sleep + mode +17 +1 ++ +SPI3LPEN +SPI3 clock enable during Sleep + mode +15 +1 ++ +SPI2LPEN +SPI2 clock enable during Sleep + mode +14 +1 ++ +WWDGLPEN +Window watchdog clock enable during + Sleep mode +11 +1 ++ +TIM14LPEN +TIM14 clock enable during Sleep + mode +8 +1 ++ +TIM13LPEN +TIM13 clock enable during Sleep + mode +7 +1 ++ +TIM12LPEN +TIM12 clock enable during Sleep + mode +6 +1 ++ +TIM7LPEN +TIM7 clock enable during Sleep + mode +5 +1 ++ +TIM6LPEN +TIM6 clock enable during Sleep + mode +4 +1 ++ +TIM5LPEN +TIM5 clock enable during Sleep + mode +3 +1 ++ +TIM4LPEN +TIM4 clock enable during Sleep + mode +2 +1 ++ +TIM3LPEN +TIM3 clock enable during Sleep + mode +1 +1 ++ +TIM2LPEN +TIM2 clock enable during Sleep + mode +0 +1 ++ +APB2LPENR +APB2LPENR +APB2 peripheral clock enabled in low power + mode register +0x64 +0x20 +read-write +0x00075F33 ++ ++ +TIM11LPEN +TIM11 clock enable during Sleep + mode +18 +1 ++ +TIM10LPEN +TIM10 clock enable during Sleep + mode +17 +1 ++ +TIM9LPEN +TIM9 clock enable during sleep + mode +16 +1 ++ +SYSCFGLPEN +System configuration controller clock + enable during Sleep mode +14 +1 ++ +SPI1LPEN +SPI 1 clock enable during Sleep + mode +12 +1 ++ +SDIOLPEN +SDIO clock enable during Sleep + mode +11 +1 ++ +ADC3LPEN +ADC 3 clock enable during Sleep + mode +10 +1 ++ +ADC2LPEN +ADC2 clock enable during Sleep + mode +9 +1 ++ +ADC1LPEN +ADC1 clock enable during Sleep + mode +8 +1 ++ +USART6LPEN +USART6 clock enable during Sleep + mode +5 +1 ++ +USART1LPEN +USART1 clock enable during Sleep + mode +4 +1 ++ +TIM8LPEN +TIM8 clock enable during Sleep + mode +1 +1 ++ +TIM1LPEN +TIM1 clock enable during Sleep + mode +0 +1 ++ +BDCR +BDCR +Backup domain control register +0x70 +0x20 +0x00000000 ++ ++ +BDRST +Backup domain software + reset +16 +1 +read-write ++ +RTCEN +RTC clock enable +15 +1 +read-write ++ +RTCSEL1 +RTC clock source selection +9 +1 +read-write ++ +RTCSEL0 +RTC clock source selection +8 +1 +read-write ++ +LSEBYP +External low-speed oscillator + bypass +2 +1 +read-write ++ +LSERDY +External low-speed oscillator + ready +1 +1 +read-only ++ +LSEON +External low-speed oscillator + enable +0 +1 +read-write ++ +CSR +CSR +clock control & status + register +0x74 +0x20 +0x0E000000 ++ ++ +LPWRRSTF +Low-power reset flag +31 +1 +read-write ++ +WWDGRSTF +Window watchdog reset flag +30 +1 +read-write ++ +WDGRSTF +Independent watchdog reset + flag +29 +1 +read-write ++ +SFTRSTF +Software reset flag +28 +1 +read-write ++ +PORRSTF +POR/PDR reset flag +27 +1 +read-write ++ +PADRSTF +PIN reset flag +26 +1 +read-write ++ +BORRSTF +BOR reset flag +25 +1 +read-write ++ +RMVF +Remove reset flag +24 +1 +read-write ++ +LSIRDY +Internal low-speed oscillator + ready +1 +1 +read-only ++ +LSION +Internal low-speed oscillator + enable +0 +1 +read-write ++ +SSCGR +SSCGR +spread spectrum clock generation + register +0x80 +0x20 +read-write +0x00000000 ++ ++ +SSCGEN +Spread spectrum modulation + enable +31 +1 ++ +SPREADSEL +Spread Select +30 +1 ++ +INCSTEP +Incrementation step +13 +15 ++ +MODPER +Modulation period +0 +13 ++ +PLLI2SCFGR +PLLI2SCFGR +PLLI2S configuration register +0x84 +0x20 +read-write +0x20003000 ++ ++ +PLLI2SRx +PLLI2S division factor for I2S + clocks +28 +3 ++ +PLLI2SNx +PLLI2S multiplication factor for + VCO +6 +9 ++ +GPIOI +General-purpose I/Os +GPIO +0x40022000 ++ +0x0 +0x400 +registers ++ ++ +MODER +MODER +GPIO port mode register +0x0 +0x20 +read-write +0x00000000 ++ ++ +MODER15 +Port x configuration bits (y = + 0..15) +30 +2 ++ +MODER14 +Port x configuration bits (y = + 0..15) +28 +2 ++ +MODER13 +Port x configuration bits (y = + 0..15) +26 +2 ++ +MODER12 +Port x configuration bits (y = + 0..15) +24 +2 ++ +MODER11 +Port x configuration bits (y = + 0..15) +22 +2 ++ +MODER10 +Port x configuration bits (y = + 0..15) +20 +2 ++ +MODER9 +Port x configuration bits (y = + 0..15) +18 +2 ++ +MODER8 +Port x configuration bits (y = + 0..15) +16 +2 ++ +MODER7 +Port x configuration bits (y = + 0..15) +14 +2 ++ +MODER6 +Port x configuration bits (y = + 0..15) +12 +2 ++ +MODER5 +Port x configuration bits (y = + 0..15) +10 +2 ++ +MODER4 +Port x configuration bits (y = + 0..15) +8 +2 ++ +MODER3 +Port x configuration bits (y = + 0..15) +6 +2 ++ +MODER2 +Port x configuration bits (y = + 0..15) +4 +2 ++ +MODER1 +Port x configuration bits (y = + 0..15) +2 +2 ++ +MODER0 +Port x configuration bits (y = + 0..15) +0 +2 ++ +OTYPER +OTYPER +GPIO port output type register +0x4 +0x20 +read-write +0x00000000 ++ ++ +OT15 +Port x configuration bits (y = + 0..15) +15 +1 ++ +OT14 +Port x configuration bits (y = + 0..15) +14 +1 ++ +OT13 +Port x configuration bits (y = + 0..15) +13 +1 ++ +OT12 +Port x configuration bits (y = + 0..15) +12 +1 ++ +OT11 +Port x configuration bits (y = + 0..15) +11 +1 ++ +OT10 +Port x configuration bits (y = + 0..15) +10 +1 ++ +OT9 +Port x configuration bits (y = + 0..15) +9 +1 ++ +OT8 +Port x configuration bits (y = + 0..15) +8 +1 ++ +OT7 +Port x configuration bits (y = + 0..15) +7 +1 ++ +OT6 +Port x configuration bits (y = + 0..15) +6 +1 ++ +OT5 +Port x configuration bits (y = + 0..15) +5 +1 ++ +OT4 +Port x configuration bits (y = + 0..15) +4 +1 ++ +OT3 +Port x configuration bits (y = + 0..15) +3 +1 ++ +OT2 +Port x configuration bits (y = + 0..15) +2 +1 ++ +OT1 +Port x configuration bits (y = + 0..15) +1 +1 ++ +OT0 +Port x configuration bits (y = + 0..15) +0 +1 ++ +OSPEEDR +OSPEEDR +GPIO port output speed + register +0x8 +0x20 +read-write +0x00000000 ++ ++ +OSPEEDR15 +Port x configuration bits (y = + 0..15) +30 +2 ++ +OSPEEDR14 +Port x configuration bits (y = + 0..15) +28 +2 ++ +OSPEEDR13 +Port x configuration bits (y = + 0..15) +26 +2 ++ +OSPEEDR12 +Port x configuration bits (y = + 0..15) +24 +2 ++ +OSPEEDR11 +Port x configuration bits (y = + 0..15) +22 +2 ++ +OSPEEDR10 +Port x configuration bits (y = + 0..15) +20 +2 ++ +OSPEEDR9 +Port x configuration bits (y = + 0..15) +18 +2 ++ +OSPEEDR8 +Port x configuration bits (y = + 0..15) +16 +2 ++ +OSPEEDR7 +Port x configuration bits (y = + 0..15) +14 +2 ++ +OSPEEDR6 +Port x configuration bits (y = + 0..15) +12 +2 ++ +OSPEEDR5 +Port x configuration bits (y = + 0..15) +10 +2 ++ +OSPEEDR4 +Port x configuration bits (y = + 0..15) +8 +2 ++ +OSPEEDR3 +Port x configuration bits (y = + 0..15) +6 +2 ++ +OSPEEDR2 +Port x configuration bits (y = + 0..15) +4 +2 ++ +OSPEEDR1 +Port x configuration bits (y = + 0..15) +2 +2 ++ +OSPEEDR0 +Port x configuration bits (y = + 0..15) +0 +2 ++ +PUPDR +PUPDR +GPIO port pull-up/pull-down + register +0xC +0x20 +read-write +0x00000000 ++ ++ +PUPDR15 +Port x configuration bits (y = + 0..15) +30 +2 ++ +PUPDR14 +Port x configuration bits (y = + 0..15) +28 +2 ++ +PUPDR13 +Port x configuration bits (y = + 0..15) +26 +2 ++ +PUPDR12 +Port x configuration bits (y = + 0..15) +24 +2 ++ +PUPDR11 +Port x configuration bits (y = + 0..15) +22 +2 ++ +PUPDR10 +Port x configuration bits (y = + 0..15) +20 +2 ++ +PUPDR9 +Port x configuration bits (y = + 0..15) +18 +2 ++ +PUPDR8 +Port x configuration bits (y = + 0..15) +16 +2 ++ +PUPDR7 +Port x configuration bits (y = + 0..15) +14 +2 ++ +PUPDR6 +Port x configuration bits (y = + 0..15) +12 +2 ++ +PUPDR5 +Port x configuration bits (y = + 0..15) +10 +2 ++ +PUPDR4 +Port x configuration bits (y = + 0..15) +8 +2 ++ +PUPDR3 +Port x configuration bits (y = + 0..15) +6 +2 ++ +PUPDR2 +Port x configuration bits (y = + 0..15) +4 +2 ++ +PUPDR1 +Port x configuration bits (y = + 0..15) +2 +2 ++ +PUPDR0 +Port x configuration bits (y = + 0..15) +0 +2 ++ +IDR +IDR +GPIO port input data register +0x10 +0x20 +read-only +0x00000000 ++ ++ +IDR15 +Port input data (y = + 0..15) +15 +1 ++ +IDR14 +Port input data (y = + 0..15) +14 +1 ++ +IDR13 +Port input data (y = + 0..15) +13 +1 ++ +IDR12 +Port input data (y = + 0..15) +12 +1 ++ +IDR11 +Port input data (y = + 0..15) +11 +1 ++ +IDR10 +Port input data (y = + 0..15) +10 +1 ++ +IDR9 +Port input data (y = + 0..15) +9 +1 ++ +IDR8 +Port input data (y = + 0..15) +8 +1 ++ +IDR7 +Port input data (y = + 0..15) +7 +1 ++ +IDR6 +Port input data (y = + 0..15) +6 +1 ++ +IDR5 +Port input data (y = + 0..15) +5 +1 ++ +IDR4 +Port input data (y = + 0..15) +4 +1 ++ +IDR3 +Port input data (y = + 0..15) +3 +1 ++ +IDR2 +Port input data (y = + 0..15) +2 +1 ++ +IDR1 +Port input data (y = + 0..15) +1 +1 ++ +IDR0 +Port input data (y = + 0..15) +0 +1 ++ +ODR +ODR +GPIO port output data register +0x14 +0x20 +read-write +0x00000000 ++ ++ +ODR15 +Port output data (y = + 0..15) +15 +1 ++ +ODR14 +Port output data (y = + 0..15) +14 +1 ++ +ODR13 +Port output data (y = + 0..15) +13 +1 ++ +ODR12 +Port output data (y = + 0..15) +12 +1 ++ +ODR11 +Port output data (y = + 0..15) +11 +1 ++ +ODR10 +Port output data (y = + 0..15) +10 +1 ++ +ODR9 +Port output data (y = + 0..15) +9 +1 ++ +ODR8 +Port output data (y = + 0..15) +8 +1 ++ +ODR7 +Port output data (y = + 0..15) +7 +1 ++ +ODR6 +Port output data (y = + 0..15) +6 +1 ++ +ODR5 +Port output data (y = + 0..15) +5 +1 ++ +ODR4 +Port output data (y = + 0..15) +4 +1 ++ +ODR3 +Port output data (y = + 0..15) +3 +1 ++ +ODR2 +Port output data (y = + 0..15) +2 +1 ++ +ODR1 +Port output data (y = + 0..15) +1 +1 ++ +ODR0 +Port output data (y = + 0..15) +0 +1 ++ +BSRR +BSRR +GPIO port bit set/reset + register +0x18 +0x20 +write-only +0x00000000 ++ ++ +BR15 +Port x reset bit y (y = + 0..15) +31 +1 ++ +BR14 +Port x reset bit y (y = + 0..15) +30 +1 ++ +BR13 +Port x reset bit y (y = + 0..15) +29 +1 ++ +BR12 +Port x reset bit y (y = + 0..15) +28 +1 ++ +BR11 +Port x reset bit y (y = + 0..15) +27 +1 ++ +BR10 +Port x reset bit y (y = + 0..15) +26 +1 ++ +BR9 +Port x reset bit y (y = + 0..15) +25 +1 ++ +BR8 +Port x reset bit y (y = + 0..15) +24 +1 ++ +BR7 +Port x reset bit y (y = + 0..15) +23 +1 ++ +BR6 +Port x reset bit y (y = + 0..15) +22 +1 ++ +BR5 +Port x reset bit y (y = + 0..15) +21 +1 ++ +BR4 +Port x reset bit y (y = + 0..15) +20 +1 ++ +BR3 +Port x reset bit y (y = + 0..15) +19 +1 ++ +BR2 +Port x reset bit y (y = + 0..15) +18 +1 ++ +BR1 +Port x reset bit y (y = + 0..15) +17 +1 ++ +BR0 +Port x set bit y (y= + 0..15) +16 +1 ++ +BS15 +Port x set bit y (y= + 0..15) +15 +1 ++ +BS14 +Port x set bit y (y= + 0..15) +14 +1 ++ +BS13 +Port x set bit y (y= + 0..15) +13 +1 ++ +BS12 +Port x set bit y (y= + 0..15) +12 +1 ++ +BS11 +Port x set bit y (y= + 0..15) +11 +1 ++ +BS10 +Port x set bit y (y= + 0..15) +10 +1 ++ +BS9 +Port x set bit y (y= + 0..15) +9 +1 ++ +BS8 +Port x set bit y (y= + 0..15) +8 +1 ++ +BS7 +Port x set bit y (y= + 0..15) +7 +1 ++ +BS6 +Port x set bit y (y= + 0..15) +6 +1 ++ +BS5 +Port x set bit y (y= + 0..15) +5 +1 ++ +BS4 +Port x set bit y (y= + 0..15) +4 +1 ++ +BS3 +Port x set bit y (y= + 0..15) +3 +1 ++ +BS2 +Port x set bit y (y= + 0..15) +2 +1 ++ +BS1 +Port x set bit y (y= + 0..15) +1 +1 ++ +BS0 +Port x set bit y (y= + 0..15) +0 +1 ++ +LCKR +LCKR +GPIO port configuration lock + register +0x1C +0x20 +read-write +0x00000000 ++ ++ +LCKK +Port x lock bit y (y= + 0..15) +16 +1 ++ +LCK15 +Port x lock bit y (y= + 0..15) +15 +1 ++ +LCK14 +Port x lock bit y (y= + 0..15) +14 +1 ++ +LCK13 +Port x lock bit y (y= + 0..15) +13 +1 ++ +LCK12 +Port x lock bit y (y= + 0..15) +12 +1 ++ +LCK11 +Port x lock bit y (y= + 0..15) +11 +1 ++ +LCK10 +Port x lock bit y (y= + 0..15) +10 +1 ++ +LCK9 +Port x lock bit y (y= + 0..15) +9 +1 ++ +LCK8 +Port x lock bit y (y= + 0..15) +8 +1 ++ +LCK7 +Port x lock bit y (y= + 0..15) +7 +1 ++ +LCK6 +Port x lock bit y (y= + 0..15) +6 +1 ++ +LCK5 +Port x lock bit y (y= + 0..15) +5 +1 ++ +LCK4 +Port x lock bit y (y= + 0..15) +4 +1 ++ +LCK3 +Port x lock bit y (y= + 0..15) +3 +1 ++ +LCK2 +Port x lock bit y (y= + 0..15) +2 +1 ++ +LCK1 +Port x lock bit y (y= + 0..15) +1 +1 ++ +LCK0 +Port x lock bit y (y= + 0..15) +0 +1 ++ +AFRL +AFRL +GPIO alternate function low + register +0x20 +0x20 +read-write +0x00000000 ++ ++ +AFRL7 +Alternate function selection for port x + bit y (y = 0..7) +28 +4 ++ +AFRL6 +Alternate function selection for port x + bit y (y = 0..7) +24 +4 ++ +AFRL5 +Alternate function selection for port x + bit y (y = 0..7) +20 +4 ++ +AFRL4 +Alternate function selection for port x + bit y (y = 0..7) +16 +4 ++ +AFRL3 +Alternate function selection for port x + bit y (y = 0..7) +12 +4 ++ +AFRL2 +Alternate function selection for port x + bit y (y = 0..7) +8 +4 ++ +AFRL1 +Alternate function selection for port x + bit y (y = 0..7) +4 +4 ++ +AFRL0 +Alternate function selection for port x + bit y (y = 0..7) +0 +4 ++ +AFRH +AFRH +GPIO alternate function high + register +0x24 +0x20 +read-write +0x00000000 ++ ++ +AFRH15 +Alternate function selection for port x + bit y (y = 8..15) +28 +4 ++ +AFRH14 +Alternate function selection for port x + bit y (y = 8..15) +24 +4 ++ +AFRH13 +Alternate function selection for port x + bit y (y = 8..15) +20 +4 ++ +AFRH12 +Alternate function selection for port x + bit y (y = 8..15) +16 +4 ++ +AFRH11 +Alternate function selection for port x + bit y (y = 8..15) +12 +4 ++ +AFRH10 +Alternate function selection for port x + bit y (y = 8..15) +8 +4 ++ +AFRH9 +Alternate function selection for port x + bit y (y = 8..15) +4 +4 ++ +AFRH8 +Alternate function selection for port x + bit y (y = 8..15) +0 +4 ++ +GPIOH +0x40021C00 ++ +GPIOG +0x40021800 ++ +GPIOF +0x40021400 ++ +GPIOE +0x40021000 ++ +GPIOD +0X40020C00 ++ +GPIOC +0x40020800 ++ +GPIOJ +0x40022400 ++ +GPIOK +0x40022800 ++ +GPIOB +General-purpose I/Os +GPIO +0x40020400 ++ +0x0 +0x400 +registers ++ ++ +MODER +MODER +GPIO port mode register +0x0 +0x20 +read-write +0x00000280 ++ ++ +MODER15 +Port x configuration bits (y = + 0..15) +30 +2 ++ +MODER14 +Port x configuration bits (y = + 0..15) +28 +2 ++ +MODER13 +Port x configuration bits (y = + 0..15) +26 +2 ++ +MODER12 +Port x configuration bits (y = + 0..15) +24 +2 ++ +MODER11 +Port x configuration bits (y = + 0..15) +22 +2 ++ +MODER10 +Port x configuration bits (y = + 0..15) +20 +2 ++ +MODER9 +Port x configuration bits (y = + 0..15) +18 +2 ++ +MODER8 +Port x configuration bits (y = + 0..15) +16 +2 ++ +MODER7 +Port x configuration bits (y = + 0..15) +14 +2 ++ +MODER6 +Port x configuration bits (y = + 0..15) +12 +2 ++ +MODER5 +Port x configuration bits (y = + 0..15) +10 +2 ++ +MODER4 +Port x configuration bits (y = + 0..15) +8 +2 ++ +MODER3 +Port x configuration bits (y = + 0..15) +6 +2 ++ +MODER2 +Port x configuration bits (y = + 0..15) +4 +2 ++ +MODER1 +Port x configuration bits (y = + 0..15) +2 +2 ++ +MODER0 +Port x configuration bits (y = + 0..15) +0 +2 ++ +OTYPER +OTYPER +GPIO port output type register +0x4 +0x20 +read-write +0x00000000 ++ ++ +OT15 +Port x configuration bits (y = + 0..15) +15 +1 ++ +OT14 +Port x configuration bits (y = + 0..15) +14 +1 ++ +OT13 +Port x configuration bits (y = + 0..15) +13 +1 ++ +OT12 +Port x configuration bits (y = + 0..15) +12 +1 ++ +OT11 +Port x configuration bits (y = + 0..15) +11 +1 ++ +OT10 +Port x configuration bits (y = + 0..15) +10 +1 ++ +OT9 +Port x configuration bits (y = + 0..15) +9 +1 ++ +OT8 +Port x configuration bits (y = + 0..15) +8 +1 ++ +OT7 +Port x configuration bits (y = + 0..15) +7 +1 ++ +OT6 +Port x configuration bits (y = + 0..15) +6 +1 ++ +OT5 +Port x configuration bits (y = + 0..15) +5 +1 ++ +OT4 +Port x configuration bits (y = + 0..15) +4 +1 ++ +OT3 +Port x configuration bits (y = + 0..15) +3 +1 ++ +OT2 +Port x configuration bits (y = + 0..15) +2 +1 ++ +OT1 +Port x configuration bits (y = + 0..15) +1 +1 ++ +OT0 +Port x configuration bits (y = + 0..15) +0 +1 ++ +OSPEEDR +OSPEEDR +GPIO port output speed + register +0x8 +0x20 +read-write +0x000000C0 ++ ++ +OSPEEDR15 +Port x configuration bits (y = + 0..15) +30 +2 ++ +OSPEEDR14 +Port x configuration bits (y = + 0..15) +28 +2 ++ +OSPEEDR13 +Port x configuration bits (y = + 0..15) +26 +2 ++ +OSPEEDR12 +Port x configuration bits (y = + 0..15) +24 +2 ++ +OSPEEDR11 +Port x configuration bits (y = + 0..15) +22 +2 ++ +OSPEEDR10 +Port x configuration bits (y = + 0..15) +20 +2 ++ +OSPEEDR9 +Port x configuration bits (y = + 0..15) +18 +2 ++ +OSPEEDR8 +Port x configuration bits (y = + 0..15) +16 +2 ++ +OSPEEDR7 +Port x configuration bits (y = + 0..15) +14 +2 ++ +OSPEEDR6 +Port x configuration bits (y = + 0..15) +12 +2 ++ +OSPEEDR5 +Port x configuration bits (y = + 0..15) +10 +2 ++ +OSPEEDR4 +Port x configuration bits (y = + 0..15) +8 +2 ++ +OSPEEDR3 +Port x configuration bits (y = + 0..15) +6 +2 ++ +OSPEEDR2 +Port x configuration bits (y = + 0..15) +4 +2 ++ +OSPEEDR1 +Port x configuration bits (y = + 0..15) +2 +2 ++ +OSPEEDR0 +Port x configuration bits (y = + 0..15) +0 +2 ++ +PUPDR +PUPDR +GPIO port pull-up/pull-down + register +0xC +0x20 +read-write +0x00000100 ++ ++ +PUPDR15 +Port x configuration bits (y = + 0..15) +30 +2 ++ +PUPDR14 +Port x configuration bits (y = + 0..15) +28 +2 ++ +PUPDR13 +Port x configuration bits (y = + 0..15) +26 +2 ++ +PUPDR12 +Port x configuration bits (y = + 0..15) +24 +2 ++ +PUPDR11 +Port x configuration bits (y = + 0..15) +22 +2 ++ +PUPDR10 +Port x configuration bits (y = + 0..15) +20 +2 ++ +PUPDR9 +Port x configuration bits (y = + 0..15) +18 +2 ++ +PUPDR8 +Port x configuration bits (y = + 0..15) +16 +2 ++ +PUPDR7 +Port x configuration bits (y = + 0..15) +14 +2 ++ +PUPDR6 +Port x configuration bits (y = + 0..15) +12 +2 ++ +PUPDR5 +Port x configuration bits (y = + 0..15) +10 +2 ++ +PUPDR4 +Port x configuration bits (y = + 0..15) +8 +2 ++ +PUPDR3 +Port x configuration bits (y = + 0..15) +6 +2 ++ +PUPDR2 +Port x configuration bits (y = + 0..15) +4 +2 ++ +PUPDR1 +Port x configuration bits (y = + 0..15) +2 +2 ++ +PUPDR0 +Port x configuration bits (y = + 0..15) +0 +2 ++ +IDR +IDR +GPIO port input data register +0x10 +0x20 +read-only +0x00000000 ++ ++ +IDR15 +Port input data (y = + 0..15) +15 +1 ++ +IDR14 +Port input data (y = + 0..15) +14 +1 ++ +IDR13 +Port input data (y = + 0..15) +13 +1 ++ +IDR12 +Port input data (y = + 0..15) +12 +1 ++ +IDR11 +Port input data (y = + 0..15) +11 +1 ++ +IDR10 +Port input data (y = + 0..15) +10 +1 ++ +IDR9 +Port input data (y = + 0..15) +9 +1 ++ +IDR8 +Port input data (y = + 0..15) +8 +1 ++ +IDR7 +Port input data (y = + 0..15) +7 +1 ++ +IDR6 +Port input data (y = + 0..15) +6 +1 ++ +IDR5 +Port input data (y = + 0..15) +5 +1 ++ +IDR4 +Port input data (y = + 0..15) +4 +1 ++ +IDR3 +Port input data (y = + 0..15) +3 +1 ++ +IDR2 +Port input data (y = + 0..15) +2 +1 ++ +IDR1 +Port input data (y = + 0..15) +1 +1 ++ +IDR0 +Port input data (y = + 0..15) +0 +1 ++ +ODR +ODR +GPIO port output data register +0x14 +0x20 +read-write +0x00000000 ++ ++ +ODR15 +Port output data (y = + 0..15) +15 +1 ++ +ODR14 +Port output data (y = + 0..15) +14 +1 ++ +ODR13 +Port output data (y = + 0..15) +13 +1 ++ +ODR12 +Port output data (y = + 0..15) +12 +1 ++ +ODR11 +Port output data (y = + 0..15) +11 +1 ++ +ODR10 +Port output data (y = + 0..15) +10 +1 ++ +ODR9 +Port output data (y = + 0..15) +9 +1 ++ +ODR8 +Port output data (y = + 0..15) +8 +1 ++ +ODR7 +Port output data (y = + 0..15) +7 +1 ++ +ODR6 +Port output data (y = + 0..15) +6 +1 ++ +ODR5 +Port output data (y = + 0..15) +5 +1 ++ +ODR4 +Port output data (y = + 0..15) +4 +1 ++ +ODR3 +Port output data (y = + 0..15) +3 +1 ++ +ODR2 +Port output data (y = + 0..15) +2 +1 ++ +ODR1 +Port output data (y = + 0..15) +1 +1 ++ +ODR0 +Port output data (y = + 0..15) +0 +1 ++ +BSRR +BSRR +GPIO port bit set/reset + register +0x18 +0x20 +write-only +0x00000000 ++ ++ +BR15 +Port x reset bit y (y = + 0..15) +31 +1 ++ +BR14 +Port x reset bit y (y = + 0..15) +30 +1 ++ +BR13 +Port x reset bit y (y = + 0..15) +29 +1 ++ +BR12 +Port x reset bit y (y = + 0..15) +28 +1 ++ +BR11 +Port x reset bit y (y = + 0..15) +27 +1 ++ +BR10 +Port x reset bit y (y = + 0..15) +26 +1 ++ +BR9 +Port x reset bit y (y = + 0..15) +25 +1 ++ +BR8 +Port x reset bit y (y = + 0..15) +24 +1 ++ +BR7 +Port x reset bit y (y = + 0..15) +23 +1 ++ +BR6 +Port x reset bit y (y = + 0..15) +22 +1 ++ +BR5 +Port x reset bit y (y = + 0..15) +21 +1 ++ +BR4 +Port x reset bit y (y = + 0..15) +20 +1 ++ +BR3 +Port x reset bit y (y = + 0..15) +19 +1 ++ +BR2 +Port x reset bit y (y = + 0..15) +18 +1 ++ +BR1 +Port x reset bit y (y = + 0..15) +17 +1 ++ +BR0 +Port x set bit y (y= + 0..15) +16 +1 ++ +BS15 +Port x set bit y (y= + 0..15) +15 +1 ++ +BS14 +Port x set bit y (y= + 0..15) +14 +1 ++ +BS13 +Port x set bit y (y= + 0..15) +13 +1 ++ +BS12 +Port x set bit y (y= + 0..15) +12 +1 ++ +BS11 +Port x set bit y (y= + 0..15) +11 +1 ++ +BS10 +Port x set bit y (y= + 0..15) +10 +1 ++ +BS9 +Port x set bit y (y= + 0..15) +9 +1 ++ +BS8 +Port x set bit y (y= + 0..15) +8 +1 ++ +BS7 +Port x set bit y (y= + 0..15) +7 +1 ++ +BS6 +Port x set bit y (y= + 0..15) +6 +1 ++ +BS5 +Port x set bit y (y= + 0..15) +5 +1 ++ +BS4 +Port x set bit y (y= + 0..15) +4 +1 ++ +BS3 +Port x set bit y (y= + 0..15) +3 +1 ++ +BS2 +Port x set bit y (y= + 0..15) +2 +1 ++ +BS1 +Port x set bit y (y= + 0..15) +1 +1 ++ +BS0 +Port x set bit y (y= + 0..15) +0 +1 ++ +LCKR +LCKR +GPIO port configuration lock + register +0x1C +0x20 +read-write +0x00000000 ++ ++ +LCKK +Port x lock bit y (y= + 0..15) +16 +1 ++ +LCK15 +Port x lock bit y (y= + 0..15) +15 +1 ++ +LCK14 +Port x lock bit y (y= + 0..15) +14 +1 ++ +LCK13 +Port x lock bit y (y= + 0..15) +13 +1 ++ +LCK12 +Port x lock bit y (y= + 0..15) +12 +1 ++ +LCK11 +Port x lock bit y (y= + 0..15) +11 +1 ++ +LCK10 +Port x lock bit y (y= + 0..15) +10 +1 ++ +LCK9 +Port x lock bit y (y= + 0..15) +9 +1 ++ +LCK8 +Port x lock bit y (y= + 0..15) +8 +1 ++ +LCK7 +Port x lock bit y (y= + 0..15) +7 +1 ++ +LCK6 +Port x lock bit y (y= + 0..15) +6 +1 ++ +LCK5 +Port x lock bit y (y= + 0..15) +5 +1 ++ +LCK4 +Port x lock bit y (y= + 0..15) +4 +1 ++ +LCK3 +Port x lock bit y (y= + 0..15) +3 +1 ++ +LCK2 +Port x lock bit y (y= + 0..15) +2 +1 ++ +LCK1 +Port x lock bit y (y= + 0..15) +1 +1 ++ +LCK0 +Port x lock bit y (y= + 0..15) +0 +1 ++ +AFRL +AFRL +GPIO alternate function low + register +0x20 +0x20 +read-write +0x00000000 ++ ++ +AFRL7 +Alternate function selection for port x + bit y (y = 0..7) +28 +4 ++ +AFRL6 +Alternate function selection for port x + bit y (y = 0..7) +24 +4 ++ +AFRL5 +Alternate function selection for port x + bit y (y = 0..7) +20 +4 ++ +AFRL4 +Alternate function selection for port x + bit y (y = 0..7) +16 +4 ++ +AFRL3 +Alternate function selection for port x + bit y (y = 0..7) +12 +4 ++ +AFRL2 +Alternate function selection for port x + bit y (y = 0..7) +8 +4 ++ +AFRL1 +Alternate function selection for port x + bit y (y = 0..7) +4 +4 ++ +AFRL0 +Alternate function selection for port x + bit y (y = 0..7) +0 +4 ++ +AFRH +AFRH +GPIO alternate function high + register +0x24 +0x20 +read-write +0x00000000 ++ ++ +AFRH15 +Alternate function selection for port x + bit y (y = 8..15) +28 +4 ++ +AFRH14 +Alternate function selection for port x + bit y (y = 8..15) +24 +4 ++ +AFRH13 +Alternate function selection for port x + bit y (y = 8..15) +20 +4 ++ +AFRH12 +Alternate function selection for port x + bit y (y = 8..15) +16 +4 ++ +AFRH11 +Alternate function selection for port x + bit y (y = 8..15) +12 +4 ++ +AFRH10 +Alternate function selection for port x + bit y (y = 8..15) +8 +4 ++ +AFRH9 +Alternate function selection for port x + bit y (y = 8..15) +4 +4 ++ +AFRH8 +Alternate function selection for port x + bit y (y = 8..15) +0 +4 ++ +GPIOA +General-purpose I/Os +GPIO +0x40020000 ++ +0x0 +0x400 +registers ++ ++ +MODER +MODER +GPIO port mode register +0x0 +0x20 +read-write +0xA8000000 ++ ++ +MODER15 +Port x configuration bits (y = + 0..15) +30 +2 ++ +MODER14 +Port x configuration bits (y = + 0..15) +28 +2 ++ +MODER13 +Port x configuration bits (y = + 0..15) +26 +2 ++ +MODER12 +Port x configuration bits (y = + 0..15) +24 +2 ++ +MODER11 +Port x configuration bits (y = + 0..15) +22 +2 ++ +MODER10 +Port x configuration bits (y = + 0..15) +20 +2 ++ +MODER9 +Port x configuration bits (y = + 0..15) +18 +2 ++ +MODER8 +Port x configuration bits (y = + 0..15) +16 +2 ++ +MODER7 +Port x configuration bits (y = + 0..15) +14 +2 ++ +MODER6 +Port x configuration bits (y = + 0..15) +12 +2 ++ +MODER5 +Port x configuration bits (y = + 0..15) +10 +2 ++ +MODER4 +Port x configuration bits (y = + 0..15) +8 +2 ++ +MODER3 +Port x configuration bits (y = + 0..15) +6 +2 ++ +MODER2 +Port x configuration bits (y = + 0..15) +4 +2 ++ +MODER1 +Port x configuration bits (y = + 0..15) +2 +2 ++ +MODER0 +Port x configuration bits (y = + 0..15) +0 +2 ++ +OTYPER +OTYPER +GPIO port output type register +0x4 +0x20 +read-write +0x00000000 ++ ++ +OT15 +Port x configuration bits (y = + 0..15) +15 +1 ++ +OT14 +Port x configuration bits (y = + 0..15) +14 +1 ++ +OT13 +Port x configuration bits (y = + 0..15) +13 +1 ++ +OT12 +Port x configuration bits (y = + 0..15) +12 +1 ++ +OT11 +Port x configuration bits (y = + 0..15) +11 +1 ++ +OT10 +Port x configuration bits (y = + 0..15) +10 +1 ++ +OT9 +Port x configuration bits (y = + 0..15) +9 +1 ++ +OT8 +Port x configuration bits (y = + 0..15) +8 +1 ++ +OT7 +Port x configuration bits (y = + 0..15) +7 +1 ++ +OT6 +Port x configuration bits (y = + 0..15) +6 +1 ++ +OT5 +Port x configuration bits (y = + 0..15) +5 +1 ++ +OT4 +Port x configuration bits (y = + 0..15) +4 +1 ++ +OT3 +Port x configuration bits (y = + 0..15) +3 +1 ++ +OT2 +Port x configuration bits (y = + 0..15) +2 +1 ++ +OT1 +Port x configuration bits (y = + 0..15) +1 +1 ++ +OT0 +Port x configuration bits (y = + 0..15) +0 +1 ++ +OSPEEDR +OSPEEDR +GPIO port output speed + register +0x8 +0x20 +read-write +0x00000000 ++ ++ +OSPEEDR15 +Port x configuration bits (y = + 0..15) +30 +2 ++ +OSPEEDR14 +Port x configuration bits (y = + 0..15) +28 +2 ++ +OSPEEDR13 +Port x configuration bits (y = + 0..15) +26 +2 ++ +OSPEEDR12 +Port x configuration bits (y = + 0..15) +24 +2 ++ +OSPEEDR11 +Port x configuration bits (y = + 0..15) +22 +2 ++ +OSPEEDR10 +Port x configuration bits (y = + 0..15) +20 +2 ++ +OSPEEDR9 +Port x configuration bits (y = + 0..15) +18 +2 ++ +OSPEEDR8 +Port x configuration bits (y = + 0..15) +16 +2 ++ +OSPEEDR7 +Port x configuration bits (y = + 0..15) +14 +2 ++ +OSPEEDR6 +Port x configuration bits (y = + 0..15) +12 +2 ++ +OSPEEDR5 +Port x configuration bits (y = + 0..15) +10 +2 ++ +OSPEEDR4 +Port x configuration bits (y = + 0..15) +8 +2 ++ +OSPEEDR3 +Port x configuration bits (y = + 0..15) +6 +2 ++ +OSPEEDR2 +Port x configuration bits (y = + 0..15) +4 +2 ++ +OSPEEDR1 +Port x configuration bits (y = + 0..15) +2 +2 ++ +OSPEEDR0 +Port x configuration bits (y = + 0..15) +0 +2 ++ +PUPDR +PUPDR +GPIO port pull-up/pull-down + register +0xC +0x20 +read-write +0x64000000 ++ ++ +PUPDR15 +Port x configuration bits (y = + 0..15) +30 +2 ++ +PUPDR14 +Port x configuration bits (y = + 0..15) +28 +2 ++ +PUPDR13 +Port x configuration bits (y = + 0..15) +26 +2 ++ +PUPDR12 +Port x configuration bits (y = + 0..15) +24 +2 ++ +PUPDR11 +Port x configuration bits (y = + 0..15) +22 +2 ++ +PUPDR10 +Port x configuration bits (y = + 0..15) +20 +2 ++ +PUPDR9 +Port x configuration bits (y = + 0..15) +18 +2 ++ +PUPDR8 +Port x configuration bits (y = + 0..15) +16 +2 ++ +PUPDR7 +Port x configuration bits (y = + 0..15) +14 +2 ++ +PUPDR6 +Port x configuration bits (y = + 0..15) +12 +2 ++ +PUPDR5 +Port x configuration bits (y = + 0..15) +10 +2 ++ +PUPDR4 +Port x configuration bits (y = + 0..15) +8 +2 ++ +PUPDR3 +Port x configuration bits (y = + 0..15) +6 +2 ++ +PUPDR2 +Port x configuration bits (y = + 0..15) +4 +2 ++ +PUPDR1 +Port x configuration bits (y = + 0..15) +2 +2 ++ +PUPDR0 +Port x configuration bits (y = + 0..15) +0 +2 ++ +IDR +IDR +GPIO port input data register +0x10 +0x20 +read-only +0x00000000 ++ ++ +IDR15 +Port input data (y = + 0..15) +15 +1 ++ +IDR14 +Port input data (y = + 0..15) +14 +1 ++ +IDR13 +Port input data (y = + 0..15) +13 +1 ++ +IDR12 +Port input data (y = + 0..15) +12 +1 ++ +IDR11 +Port input data (y = + 0..15) +11 +1 ++ +IDR10 +Port input data (y = + 0..15) +10 +1 ++ +IDR9 +Port input data (y = + 0..15) +9 +1 ++ +IDR8 +Port input data (y = + 0..15) +8 +1 ++ +IDR7 +Port input data (y = + 0..15) +7 +1 ++ +IDR6 +Port input data (y = + 0..15) +6 +1 ++ +IDR5 +Port input data (y = + 0..15) +5 +1 ++ +IDR4 +Port input data (y = + 0..15) +4 +1 ++ +IDR3 +Port input data (y = + 0..15) +3 +1 ++ +IDR2 +Port input data (y = + 0..15) +2 +1 ++ +IDR1 +Port input data (y = + 0..15) +1 +1 ++ +IDR0 +Port input data (y = + 0..15) +0 +1 ++ +ODR +ODR +GPIO port output data register +0x14 +0x20 +read-write +0x00000000 ++ ++ +ODR15 +Port output data (y = + 0..15) +15 +1 ++ +ODR14 +Port output data (y = + 0..15) +14 +1 ++ +ODR13 +Port output data (y = + 0..15) +13 +1 ++ +ODR12 +Port output data (y = + 0..15) +12 +1 ++ +ODR11 +Port output data (y = + 0..15) +11 +1 ++ +ODR10 +Port output data (y = + 0..15) +10 +1 ++ +ODR9 +Port output data (y = + 0..15) +9 +1 ++ +ODR8 +Port output data (y = + 0..15) +8 +1 ++ +ODR7 +Port output data (y = + 0..15) +7 +1 ++ +ODR6 +Port output data (y = + 0..15) +6 +1 ++ +ODR5 +Port output data (y = + 0..15) +5 +1 ++ +ODR4 +Port output data (y = + 0..15) +4 +1 ++ +ODR3 +Port output data (y = + 0..15) +3 +1 ++ +ODR2 +Port output data (y = + 0..15) +2 +1 ++ +ODR1 +Port output data (y = + 0..15) +1 +1 ++ +ODR0 +Port output data (y = + 0..15) +0 +1 ++ +BSRR +BSRR +GPIO port bit set/reset + register +0x18 +0x20 +write-only +0x00000000 ++ ++ +BR15 +Port x reset bit y (y = + 0..15) +31 +1 ++ +BR14 +Port x reset bit y (y = + 0..15) +30 +1 ++ +BR13 +Port x reset bit y (y = + 0..15) +29 +1 ++ +BR12 +Port x reset bit y (y = + 0..15) +28 +1 ++ +BR11 +Port x reset bit y (y = + 0..15) +27 +1 ++ +BR10 +Port x reset bit y (y = + 0..15) +26 +1 ++ +BR9 +Port x reset bit y (y = + 0..15) +25 +1 ++ +BR8 +Port x reset bit y (y = + 0..15) +24 +1 ++ +BR7 +Port x reset bit y (y = + 0..15) +23 +1 ++ +BR6 +Port x reset bit y (y = + 0..15) +22 +1 ++ +BR5 +Port x reset bit y (y = + 0..15) +21 +1 ++ +BR4 +Port x reset bit y (y = + 0..15) +20 +1 ++ +BR3 +Port x reset bit y (y = + 0..15) +19 +1 ++ +BR2 +Port x reset bit y (y = + 0..15) +18 +1 ++ +BR1 +Port x reset bit y (y = + 0..15) +17 +1 ++ +BR0 +Port x set bit y (y= + 0..15) +16 +1 ++ +BS15 +Port x set bit y (y= + 0..15) +15 +1 ++ +BS14 +Port x set bit y (y= + 0..15) +14 +1 ++ +BS13 +Port x set bit y (y= + 0..15) +13 +1 ++ +BS12 +Port x set bit y (y= + 0..15) +12 +1 ++ +BS11 +Port x set bit y (y= + 0..15) +11 +1 ++ +BS10 +Port x set bit y (y= + 0..15) +10 +1 ++ +BS9 +Port x set bit y (y= + 0..15) +9 +1 ++ +BS8 +Port x set bit y (y= + 0..15) +8 +1 ++ +BS7 +Port x set bit y (y= + 0..15) +7 +1 ++ +BS6 +Port x set bit y (y= + 0..15) +6 +1 ++ +BS5 +Port x set bit y (y= + 0..15) +5 +1 ++ +BS4 +Port x set bit y (y= + 0..15) +4 +1 ++ +BS3 +Port x set bit y (y= + 0..15) +3 +1 ++ +BS2 +Port x set bit y (y= + 0..15) +2 +1 ++ +BS1 +Port x set bit y (y= + 0..15) +1 +1 ++ +BS0 +Port x set bit y (y= + 0..15) +0 +1 ++ +LCKR +LCKR +GPIO port configuration lock + register +0x1C +0x20 +read-write +0x00000000 ++ ++ +LCKK +Port x lock bit y (y= + 0..15) +16 +1 ++ +LCK15 +Port x lock bit y (y= + 0..15) +15 +1 ++ +LCK14 +Port x lock bit y (y= + 0..15) +14 +1 ++ +LCK13 +Port x lock bit y (y= + 0..15) +13 +1 ++ +LCK12 +Port x lock bit y (y= + 0..15) +12 +1 ++ +LCK11 +Port x lock bit y (y= + 0..15) +11 +1 ++ +LCK10 +Port x lock bit y (y= + 0..15) +10 +1 ++ +LCK9 +Port x lock bit y (y= + 0..15) +9 +1 ++ +LCK8 +Port x lock bit y (y= + 0..15) +8 +1 ++ +LCK7 +Port x lock bit y (y= + 0..15) +7 +1 ++ +LCK6 +Port x lock bit y (y= + 0..15) +6 +1 ++ +LCK5 +Port x lock bit y (y= + 0..15) +5 +1 ++ +LCK4 +Port x lock bit y (y= + 0..15) +4 +1 ++ +LCK3 +Port x lock bit y (y= + 0..15) +3 +1 ++ +LCK2 +Port x lock bit y (y= + 0..15) +2 +1 ++ +LCK1 +Port x lock bit y (y= + 0..15) +1 +1 ++ +LCK0 +Port x lock bit y (y= + 0..15) +0 +1 ++ +AFRL +AFRL +GPIO alternate function low + register +0x20 +0x20 +read-write +0x00000000 ++ ++ +AFRL7 +Alternate function selection for port x + bit y (y = 0..7) +28 +4 ++ +AFRL6 +Alternate function selection for port x + bit y (y = 0..7) +24 +4 ++ +AFRL5 +Alternate function selection for port x + bit y (y = 0..7) +20 +4 ++ +AFRL4 +Alternate function selection for port x + bit y (y = 0..7) +16 +4 ++ +AFRL3 +Alternate function selection for port x + bit y (y = 0..7) +12 +4 ++ +AFRL2 +Alternate function selection for port x + bit y (y = 0..7) +8 +4 ++ +AFRL1 +Alternate function selection for port x + bit y (y = 0..7) +4 +4 ++ +AFRL0 +Alternate function selection for port x + bit y (y = 0..7) +0 +4 ++ +AFRH +AFRH +GPIO alternate function high + register +0x24 +0x20 +read-write +0x00000000 ++ ++ +AFRH15 +Alternate function selection for port x + bit y (y = 8..15) +28 +4 ++ +AFRH14 +Alternate function selection for port x + bit y (y = 8..15) +24 +4 ++ +AFRH13 +Alternate function selection for port x + bit y (y = 8..15) +20 +4 ++ +AFRH12 +Alternate function selection for port x + bit y (y = 8..15) +16 +4 ++ +AFRH11 +Alternate function selection for port x + bit y (y = 8..15) +12 +4 ++ +AFRH10 +Alternate function selection for port x + bit y (y = 8..15) +8 +4 ++ +AFRH9 +Alternate function selection for port x + bit y (y = 8..15) +4 +4 ++ +AFRH8 +Alternate function selection for port x + bit y (y = 8..15) +0 +4 ++ +SYSCFG +System configuration controller +SYSCFG +0x40013800 ++ +0x0 +0x400 +registers ++ ++ +MEMRM +MEMRM +memory remap register +0x0 +0x20 +read-write +0x00000000 ++ ++ +MEM_MODE +MEM_MODE +0 +2 ++ +PMC +PMC +peripheral mode configuration + register +0x4 +0x20 +read-write +0x00000000 ++ ++ +MII_RMII_SEL +Ethernet PHY interface + selection +23 +1 ++ +EXTICR1 +EXTICR1 +external interrupt configuration register + 1 +0x8 +0x20 +read-write +0x0000 ++ ++ +EXTI3 +EXTI x configuration (x = 0 to + 3) +12 +4 ++ +EXTI2 +EXTI x configuration (x = 0 to + 3) +8 +4 ++ +EXTI1 +EXTI x configuration (x = 0 to + 3) +4 +4 ++ +EXTI0 +EXTI x configuration (x = 0 to + 3) +0 +4 ++ +EXTICR2 +EXTICR2 +external interrupt configuration register + 2 +0xC +0x20 +read-write +0x0000 ++ ++ +EXTI7 +EXTI x configuration (x = 4 to + 7) +12 +4 ++ +EXTI6 +EXTI x configuration (x = 4 to + 7) +8 +4 ++ +EXTI5 +EXTI x configuration (x = 4 to + 7) +4 +4 ++ +EXTI4 +EXTI x configuration (x = 4 to + 7) +0 +4 ++ +EXTICR3 +EXTICR3 +external interrupt configuration register + 3 +0x10 +0x20 +read-write +0x0000 ++ ++ +EXTI11 +EXTI x configuration (x = 8 to + 11) +12 +4 ++ +EXTI10 +EXTI10 +8 +4 ++ +EXTI9 +EXTI x configuration (x = 8 to + 11) +4 +4 ++ +EXTI8 +EXTI x configuration (x = 8 to + 11) +0 +4 ++ +EXTICR4 +EXTICR4 +external interrupt configuration register + 4 +0x14 +0x20 +read-write +0x0000 ++ ++ +EXTI15 +EXTI x configuration (x = 12 to + 15) +12 +4 ++ +EXTI14 +EXTI x configuration (x = 12 to + 15) +8 +4 ++ +EXTI13 +EXTI x configuration (x = 12 to + 15) +4 +4 ++ +EXTI12 +EXTI x configuration (x = 12 to + 15) +0 +4 ++ +CMPCR +CMPCR +Compensation cell control + register +0x20 +0x20 +read-only +0x00000000 ++ ++ +READY +READY +8 +1 ++ +CMP_PD +Compensation cell + power-down +0 +1 ++ +SPI1 +Serial peripheral interface +SPI +0x40013000 ++ +0x0 +0x400 +registers ++ +SPI1 +SPI1 global interrupt +35 ++ ++ +CR1 +CR1 +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +BIDIMODE +Bidirectional data mode + enable +15 +1 ++ +BIDIOE +Output enable in bidirectional + mode +14 +1 ++ +CRCEN +Hardware CRC calculation + enable +13 +1 ++ +CRCNEXT +CRC transfer next +12 +1 ++ +DFF +Data frame format +11 +1 ++ +RXONLY +Receive only +10 +1 ++ +SSM +Software slave management +9 +1 ++ +SSI +Internal slave select +8 +1 ++ +LSBFIRST +Frame format +7 +1 ++ +SPE +SPI enable +6 +1 ++ +BR +Baud rate control +3 +3 ++ +MSTR +Master selection +2 +1 ++ +CPOL +Clock polarity +1 +1 ++ +CPHA +Clock phase +0 +1 ++ +CR2 +CR2 +control register 2 +0x4 +0x20 +read-write +0x0000 ++ ++ +TXEIE +Tx buffer empty interrupt + enable +7 +1 ++ +RXNEIE +RX buffer not empty interrupt + enable +6 +1 ++ +ERRIE +Error interrupt enable +5 +1 ++ +FRF +Frame format +4 +1 ++ +SSOE +SS output enable +2 +1 ++ +TXDMAEN +Tx buffer DMA enable +1 +1 ++ +RXDMAEN +Rx buffer DMA enable +0 +1 ++ +SR +SR +status register +0x8 +0x20 +0x0002 ++ ++ +TIFRFE +TI frame format error +8 +1 +read-only ++ +BSY +Busy flag +7 +1 +read-only ++ +OVR +Overrun flag +6 +1 +read-only ++ +MODF +Mode fault +5 +1 +read-only ++ +CRCERR +CRC error flag +4 +1 +read-write ++ +UDR +Underrun flag +3 +1 +read-only ++ +CHSIDE +Channel side +2 +1 +read-only ++ +TXE +Transmit buffer empty +1 +1 +read-only ++ +RXNE +Receive buffer not empty +0 +1 +read-only ++ +DR +DR +data register +0xC +0x20 +read-write +0x0000 ++ ++ +DR +Data register +0 +16 ++ +CRCPR +CRCPR +CRC polynomial register +0x10 +0x20 +read-write +0x0007 ++ ++ +CRCPOLY +CRC polynomial register +0 +16 ++ +RXCRCR +RXCRCR +RX CRC register +0x14 +0x20 +read-only +0x0000 ++ ++ +RxCRC +Rx CRC register +0 +16 ++ +TXCRCR +TXCRCR +TX CRC register +0x18 +0x20 +read-only +0x0000 ++ ++ +TxCRC +Tx CRC register +0 +16 ++ +I2SCFGR +I2SCFGR +I2S configuration register +0x1C +0x20 +read-write +0x0000 ++ ++ +I2SMOD +I2S mode selection +11 +1 ++ +I2SE +I2S Enable +10 +1 ++ +I2SCFG +I2S configuration mode +8 +2 ++ +PCMSYNC +PCM frame synchronization +7 +1 ++ +I2SSTD +I2S standard selection +4 +2 ++ +CKPOL +Steady state clock + polarity +3 +1 ++ +DATLEN +Data length to be + transferred +1 +2 ++ +CHLEN +Channel length (number of bits per audio + channel) +0 +1 ++ +I2SPR +I2SPR +I2S prescaler register +0x20 +0x20 +read-write +00000010 ++ ++ +MCKOE +Master clock output enable +9 +1 ++ +ODD +Odd factor for the + prescaler +8 +1 ++ +I2SDIV +I2S Linear prescaler +0 +8 ++ +SPI2 +0x40003800 ++ +SPI2 +SPI2 global interrupt +36 ++ +SPI3 +0x40003C00 ++ +SPI3 +SPI3 global interrupt +51 ++ +I2S2ext +0x40003400 ++ +I2S3ext +0x40004000 ++ +SPI4 +0x40013400 ++ +SPI1 +SPI1 global interrupt +35 ++ +SPI5 +0x40015000 ++ +SPI1 +SPI1 global interrupt +35 ++ +SPI6 +0x40015400 ++ +SPI3 +SPI3 global interrupt +51 ++ +SDIO +Secure digital input/output + interface +SDIO +0x40012C00 ++ +0x0 +0x400 +registers ++ +SDIO +SDIO global interrupt +49 ++ ++ +POWER +POWER +power control register +0x0 +0x20 +read-write +0x00000000 ++ ++ +PWRCTRL +PWRCTRL +0 +2 ++ +CLKCR +CLKCR +SDI clock control register +0x4 +0x20 +read-write +0x00000000 ++ ++ +HWFC_EN +HW Flow Control enable +14 +1 ++ +NEGEDGE +SDIO_CK dephasing selection + bit +13 +1 ++ +WIDBUS +Wide bus mode enable bit +11 +2 ++ +BYPASS +Clock divider bypass enable + bit +10 +1 ++ +PWRSAV +Power saving configuration + bit +9 +1 ++ +CLKEN +Clock enable bit +8 +1 ++ +CLKDIV +Clock divide factor +0 +8 ++ +ARG +ARG +argument register +0x8 +0x20 +read-write +0x00000000 ++ ++ +CMDARG +Command argument +0 +32 ++ +CMD +CMD +command register +0xC +0x20 +read-write +0x00000000 ++ ++ +CE_ATACMD +CE-ATA command +14 +1 ++ +nIEN +not Interrupt Enable +13 +1 ++ +ENCMDcompl +Enable CMD completion +12 +1 ++ +SDIOSuspend +SD I/O suspend command +11 +1 ++ +CPSMEN +Command path state machine (CPSM) Enable + bit +10 +1 ++ +WAITPEND +CPSM Waits for ends of data transfer + (CmdPend internal signal). +9 +1 ++ +WAITINT +CPSM waits for interrupt + request +8 +1 ++ +WAITRESP +Wait for response bits +6 +2 ++ +CMDINDEX +Command index +0 +6 ++ +RESPCMD +RESPCMD +command response register +0x10 +0x20 +read-only +0x00000000 ++ ++ +RESPCMD +Response command index +0 +6 ++ +RESP1 +RESP1 +response 1..4 register +0x14 +0x20 +read-only +0x00000000 ++ ++ +CARDSTATUS1 +see Table 132. +0 +32 ++ +RESP2 +RESP2 +response 1..4 register +0x18 +0x20 +read-only +0x00000000 ++ ++ +CARDSTATUS2 +see Table 132. +0 +32 ++ +RESP3 +RESP3 +response 1..4 register +0x1C +0x20 +read-only +0x00000000 ++ ++ +CARDSTATUS3 +see Table 132. +0 +32 ++ +RESP4 +RESP4 +response 1..4 register +0x20 +0x20 +read-only +0x00000000 ++ ++ +CARDSTATUS4 +see Table 132. +0 +32 ++ +DTIMER +DTIMER +data timer register +0x24 +0x20 +read-write +0x00000000 ++ ++ +DATATIME +Data timeout period +0 +32 ++ +DLEN +DLEN +data length register +0x28 +0x20 +read-write +0x00000000 ++ ++ +DATALENGTH +Data length value +0 +25 ++ +DCTRL +DCTRL +data control register +0x2C +0x20 +read-write +0x00000000 ++ ++ +SDIOEN +SD I/O enable functions +11 +1 ++ +RWMOD +Read wait mode +10 +1 ++ +RWSTOP +Read wait stop +9 +1 ++ +RWSTART +Read wait start +8 +1 ++ +DBLOCKSIZE +Data block size +4 +4 ++ +DMAEN +DMA enable bit +3 +1 ++ +DTMODE +Data transfer mode selection 1: Stream + or SDIO multibyte data transfer. +2 +1 ++ +DTDIR +Data transfer direction + selection +1 +1 ++ +DTEN +DTEN +0 +1 ++ +DCOUNT +DCOUNT +data counter register +0x30 +0x20 +read-only +0x00000000 ++ ++ +DATACOUNT +Data count value +0 +25 ++ +STA +STA +status register +0x34 +0x20 +read-only +0x00000000 ++ ++ +CEATAEND +CE-ATA command completion signal + received for CMD61 +23 +1 ++ +SDIOIT +SDIO interrupt received +22 +1 ++ +RXDAVL +Data available in receive + FIFO +21 +1 ++ +TXDAVL +Data available in transmit + FIFO +20 +1 ++ +RXFIFOE +Receive FIFO empty +19 +1 ++ +TXFIFOE +Transmit FIFO empty +18 +1 ++ +RXFIFOF +Receive FIFO full +17 +1 ++ +TXFIFOF +Transmit FIFO full +16 +1 ++ +RXFIFOHF +Receive FIFO half full: there are at + least 8 words in the FIFO +15 +1 ++ +TXFIFOHE +Transmit FIFO half empty: at least 8 + words can be written into the FIFO +14 +1 ++ +RXACT +Data receive in progress +13 +1 ++ +TXACT +Data transmit in progress +12 +1 ++ +CMDACT +Command transfer in + progress +11 +1 ++ +DBCKEND +Data block sent/received (CRC check + passed) +10 +1 ++ +STBITERR +Start bit not detected on all data + signals in wide bus mode +9 +1 ++ +DATAEND +Data end (data counter, SDIDCOUNT, is + zero) +8 +1 ++ +CMDSENT +Command sent (no response + required) +7 +1 ++ +CMDREND +Command response received (CRC check + passed) +6 +1 ++ +RXOVERR +Received FIFO overrun + error +5 +1 ++ +TXUNDERR +Transmit FIFO underrun + error +4 +1 ++ +DTIMEOUT +Data timeout +3 +1 ++ +CTIMEOUT +Command response timeout +2 +1 ++ +DCRCFAIL +Data block sent/received (CRC check + failed) +1 +1 ++ +CCRCFAIL +Command response received (CRC check + failed) +0 +1 ++ +ICR +ICR +interrupt clear register +0x38 +0x20 +read-write +0x00000000 ++ ++ +CEATAENDC +CEATAEND flag clear bit +23 +1 ++ +SDIOITC +SDIOIT flag clear bit +22 +1 ++ +DBCKENDC +DBCKEND flag clear bit +10 +1 ++ +STBITERRC +STBITERR flag clear bit +9 +1 ++ +DATAENDC +DATAEND flag clear bit +8 +1 ++ +CMDSENTC +CMDSENT flag clear bit +7 +1 ++ +CMDRENDC +CMDREND flag clear bit +6 +1 ++ +RXOVERRC +RXOVERR flag clear bit +5 +1 ++ +TXUNDERRC +TXUNDERR flag clear bit +4 +1 ++ +DTIMEOUTC +DTIMEOUT flag clear bit +3 +1 ++ +CTIMEOUTC +CTIMEOUT flag clear bit +2 +1 ++ +DCRCFAILC +DCRCFAIL flag clear bit +1 +1 ++ +CCRCFAILC +CCRCFAIL flag clear bit +0 +1 ++ +MASK +MASK +mask register +0x3C +0x20 +read-write +0x00000000 ++ ++ +CEATAENDIE +CE-ATA command completion signal + received interrupt enable +23 +1 ++ +SDIOITIE +SDIO mode interrupt received interrupt + enable +22 +1 ++ +RXDAVLIE +Data available in Rx FIFO interrupt + enable +21 +1 ++ +TXDAVLIE +Data available in Tx FIFO interrupt + enable +20 +1 ++ +RXFIFOEIE +Rx FIFO empty interrupt + enable +19 +1 ++ +TXFIFOEIE +Tx FIFO empty interrupt + enable +18 +1 ++ +RXFIFOFIE +Rx FIFO full interrupt + enable +17 +1 ++ +TXFIFOFIE +Tx FIFO full interrupt + enable +16 +1 ++ +RXFIFOHFIE +Rx FIFO half full interrupt + enable +15 +1 ++ +TXFIFOHEIE +Tx FIFO half empty interrupt + enable +14 +1 ++ +RXACTIE +Data receive acting interrupt + enable +13 +1 ++ +TXACTIE +Data transmit acting interrupt + enable +12 +1 ++ +CMDACTIE +Command acting interrupt + enable +11 +1 ++ +DBCKENDIE +Data block end interrupt + enable +10 +1 ++ +STBITERRIE +Start bit error interrupt + enable +9 +1 ++ +DATAENDIE +Data end interrupt enable +8 +1 ++ +CMDSENTIE +Command sent interrupt + enable +7 +1 ++ +CMDRENDIE +Command response received interrupt + enable +6 +1 ++ +RXOVERRIE +Rx FIFO overrun error interrupt + enable +5 +1 ++ +TXUNDERRIE +Tx FIFO underrun error interrupt + enable +4 +1 ++ +DTIMEOUTIE +Data timeout interrupt + enable +3 +1 ++ +CTIMEOUTIE +Command timeout interrupt + enable +2 +1 ++ +DCRCFAILIE +Data CRC fail interrupt + enable +1 +1 ++ +CCRCFAILIE +Command CRC fail interrupt + enable +0 +1 ++ +FIFOCNT +FIFOCNT +FIFO counter register +0x48 +0x20 +read-only +0x00000000 ++ ++ +FIFOCOUNT +Remaining number of words to be written + to or read from the FIFO. +0 +24 ++ +FIFO +FIFO +data FIFO register +0x80 +0x20 +read-write +0x00000000 ++ ++ +FIFOData +Receive and transmit FIFO + data +0 +32 ++ +ADC1 +Analog-to-digital converter +ADC +0x40012000 ++ +0x0 +0x51 +registers ++ +ADC +ADC1 global interrupt +18 ++ ++ +SR +SR +status register +0x0 +0x20 +read-write +0x00000000 ++ ++ +OVR +Overrun +5 +1 ++ +STRT +Regular channel start flag +4 +1 ++ +JSTRT +Injected channel start + flag +3 +1 ++ +JEOC +Injected channel end of + conversion +2 +1 ++ +EOC +Regular channel end of + conversion +1 +1 ++ +AWD +Analog watchdog flag +0 +1 ++ +CR1 +CR1 +control register 1 +0x4 +0x20 +read-write +0x00000000 ++ ++ +OVRIE +Overrun interrupt enable +26 +1 ++ +RES +Resolution +24 +2 ++ +AWDEN +Analog watchdog enable on regular + channels +23 +1 ++ +JAWDEN +Analog watchdog enable on injected + channels +22 +1 ++ +DISCNUM +Discontinuous mode channel + count +13 +3 ++ +JDISCEN +Discontinuous mode on injected + channels +12 +1 ++ +DISCEN +Discontinuous mode on regular + channels +11 +1 ++ +JAUTO +Automatic injected group + conversion +10 +1 ++ +AWDSGL +Enable the watchdog on a single channel + in scan mode +9 +1 ++ +SCAN +Scan mode +8 +1 ++ +JEOCIE +Interrupt enable for injected + channels +7 +1 ++ +AWDIE +Analog watchdog interrupt + enable +6 +1 ++ +EOCIE +Interrupt enable for EOC +5 +1 ++ +AWDCH +Analog watchdog channel select + bits +0 +5 ++ +CR2 +CR2 +control register 2 +0x8 +0x20 +read-write +0x00000000 ++ ++ +SWSTART +Start conversion of regular + channels +30 +1 ++ +EXTEN +External trigger enable for regular + channels +28 +2 ++ +EXTSEL +External event select for regular + group +24 +4 ++ +JSWSTART +Start conversion of injected + channels +22 +1 ++ +JEXTEN +External trigger enable for injected + channels +20 +2 ++ +JEXTSEL +External event select for injected + group +16 +4 ++ +ALIGN +Data alignment +11 +1 ++ +EOCS +End of conversion + selection +10 +1 ++ +DDS +DMA disable selection (for single ADC + mode) +9 +1 ++ +DMA +Direct memory access mode (for single + ADC mode) +8 +1 ++ +CONT +Continuous conversion +1 +1 ++ +ADON +A/D Converter ON / OFF +0 +1 ++ +SMPR1 +SMPR1 +sample time register 1 +0xC +0x20 +read-write +0x00000000 ++ ++ +SMPx_x +Sample time bits +0 +32 ++ +SMPR2 +SMPR2 +sample time register 2 +0x10 +0x20 +read-write +0x00000000 ++ ++ +SMPx_x +Sample time bits +0 +32 ++ +JOFR1 +JOFR1 +injected channel data offset register + x +0x14 +0x20 +read-write +0x00000000 ++ ++ +JOFFSET1 +Data offset for injected channel + x +0 +12 ++ +JOFR2 +JOFR2 +injected channel data offset register + x +0x18 +0x20 +read-write +0x00000000 ++ ++ +JOFFSET2 +Data offset for injected channel + x +0 +12 ++ +JOFR3 +JOFR3 +injected channel data offset register + x +0x1C +0x20 +read-write +0x00000000 ++ ++ +JOFFSET3 +Data offset for injected channel + x +0 +12 ++ +JOFR4 +JOFR4 +injected channel data offset register + x +0x20 +0x20 +read-write +0x00000000 ++ ++ +JOFFSET4 +Data offset for injected channel + x +0 +12 ++ +HTR +HTR +watchdog higher threshold + register +0x24 +0x20 +read-write +0x00000FFF ++ ++ +HT +Analog watchdog higher + threshold +0 +12 ++ +LTR +LTR +watchdog lower threshold + register +0x28 +0x20 +read-write +0x00000000 ++ ++ +LT +Analog watchdog lower + threshold +0 +12 ++ +SQR1 +SQR1 +regular sequence register 1 +0x2C +0x20 +read-write +0x00000000 ++ ++ +L +Regular channel sequence + length +20 +4 ++ +SQ16 +16th conversion in regular + sequence +15 +5 ++ +SQ15 +15th conversion in regular + sequence +10 +5 ++ +SQ14 +14th conversion in regular + sequence +5 +5 ++ +SQ13 +13th conversion in regular + sequence +0 +5 ++ +SQR2 +SQR2 +regular sequence register 2 +0x30 +0x20 +read-write +0x00000000 ++ ++ +SQ12 +12th conversion in regular + sequence +25 +5 ++ +SQ11 +11th conversion in regular + sequence +20 +5 ++ +SQ10 +10th conversion in regular + sequence +15 +5 ++ +SQ9 +9th conversion in regular + sequence +10 +5 ++ +SQ8 +8th conversion in regular + sequence +5 +5 ++ +SQ7 +7th conversion in regular + sequence +0 +5 ++ +SQR3 +SQR3 +regular sequence register 3 +0x34 +0x20 +read-write +0x00000000 ++ ++ +SQ6 +6th conversion in regular + sequence +25 +5 ++ +SQ5 +5th conversion in regular + sequence +20 +5 ++ +SQ4 +4th conversion in regular + sequence +15 +5 ++ +SQ3 +3rd conversion in regular + sequence +10 +5 ++ +SQ2 +2nd conversion in regular + sequence +5 +5 ++ +SQ1 +1st conversion in regular + sequence +0 +5 ++ +JSQR +JSQR +injected sequence register +0x38 +0x20 +read-write +0x00000000 ++ ++ +JL +Injected sequence length +20 +2 ++ +JSQ4 +4th conversion in injected + sequence +15 +5 ++ +JSQ3 +3rd conversion in injected + sequence +10 +5 ++ +JSQ2 +2nd conversion in injected + sequence +5 +5 ++ +JSQ1 +1st conversion in injected + sequence +0 +5 ++ +JDR1 +JDR1 +injected data register x +0x3C +0x20 +read-only +0x00000000 ++ ++ +JDATA +Injected data +0 +16 ++ +JDR2 +JDR2 +injected data register x +0x40 +0x20 +read-only +0x00000000 ++ ++ +JDATA +Injected data +0 +16 ++ +JDR3 +JDR3 +injected data register x +0x44 +0x20 +read-only +0x00000000 ++ ++ +JDATA +Injected data +0 +16 ++ +JDR4 +JDR4 +injected data register x +0x48 +0x20 +read-only +0x00000000 ++ ++ +JDATA +Injected data +0 +16 ++ +DR +DR +regular data register +0x4C +0x20 +read-only +0x00000000 ++ ++ +DATA +Regular data +0 +16 ++ +ADC2 +0x40012100 ++ +ADC +ADC2 global interrupts +18 ++ +ADC3 +0x40012200 ++ +ADC +ADC3 global interrupts +18 ++ +USART6 +Universal synchronous asynchronous receiver + transmitter +USART +0x40011400 ++ +0x0 +0x400 +registers ++ +USART6 +USART6 global interrupt +71 ++ ++ +SR +SR +Status register +0x0 +0x20 +0x00C00000 ++ ++ +CTS +CTS flag +9 +1 +read-write ++ +LBD +LIN break detection flag +8 +1 +read-write ++ +TXE +Transmit data register + empty +7 +1 +read-only ++ +TC +Transmission complete +6 +1 +read-write ++ +RXNE +Read data register not + empty +5 +1 +read-write ++ +IDLE +IDLE line detected +4 +1 +read-only ++ +ORE +Overrun error +3 +1 +read-only ++ +NF +Noise detected flag +2 +1 +read-only ++ +FE +Framing error +1 +1 +read-only ++ +PE +Parity error +0 +1 +read-only ++ +DR +DR +Data register +0x4 +0x20 +read-write +0x00000000 ++ ++ +DR +Data value +0 +9 ++ +BRR +BRR +Baud rate register +0x8 +0x20 +read-write +0x0000 ++ ++ +DIV_Mantissa +mantissa of USARTDIV +4 +12 ++ +DIV_Fraction +fraction of USARTDIV +0 +4 ++ +CR1 +CR1 +Control register 1 +0xC +0x20 +read-write +0x0000 ++ ++ +OVER8 +Oversampling mode +15 +1 ++ +UE +USART enable +13 +1 ++ +M +Word length +12 +1 ++ +WAKE +Wakeup method +11 +1 ++ +PCE +Parity control enable +10 +1 ++ +PS +Parity selection +9 +1 ++ +PEIE +PE interrupt enable +8 +1 ++ +TXEIE +TXE interrupt enable +7 +1 ++ +TCIE +Transmission complete interrupt + enable +6 +1 ++ +RXNEIE +RXNE interrupt enable +5 +1 ++ +IDLEIE +IDLE interrupt enable +4 +1 ++ +TE +Transmitter enable +3 +1 ++ +RE +Receiver enable +2 +1 ++ +RWU +Receiver wakeup +1 +1 ++ +SBK +Send break +0 +1 ++ +CR2 +CR2 +Control register 2 +0x10 +0x20 +read-write +0x0000 ++ ++ +LINEN +LIN mode enable +14 +1 ++ +STOP +STOP bits +12 +2 ++ +CLKEN +Clock enable +11 +1 ++ +CPOL +Clock polarity +10 +1 ++ +CPHA +Clock phase +9 +1 ++ +LBCL +Last bit clock pulse +8 +1 ++ +LBDIE +LIN break detection interrupt + enable +6 +1 ++ +LBDL +lin break detection length +5 +1 ++ +ADD +Address of the USART node +0 +4 ++ +CR3 +CR3 +Control register 3 +0x14 +0x20 +read-write +0x0000 ++ ++ +ONEBIT +One sample bit method + enable +11 +1 ++ +CTSIE +CTS interrupt enable +10 +1 ++ +CTSE +CTS enable +9 +1 ++ +RTSE +RTS enable +8 +1 ++ +DMAT +DMA enable transmitter +7 +1 ++ +DMAR +DMA enable receiver +6 +1 ++ +SCEN +Smartcard mode enable +5 +1 ++ +NACK +Smartcard NACK enable +4 +1 ++ +HDSEL +Half-duplex selection +3 +1 ++ +IRLP +IrDA low-power +2 +1 ++ +IREN +IrDA mode enable +1 +1 ++ +EIE +Error interrupt enable +0 +1 ++ +GTPR +GTPR +Guard time and prescaler + register +0x18 +0x20 +read-write +0x0000 ++ ++ +GT +Guard time value +8 +8 ++ +PSC +Prescaler value +0 +8 ++ +USART1 +0x40011000 ++ +USART1 +USART1 global interrupt +37 ++ +USART2 +0x40004400 ++ +USART2 +USART2 global interrupt +38 ++ +USART3 +0x40004800 ++ +USART3 +USART3 global interrupt +39 ++ +DAC +Digital-to-analog converter +DAC +0x40007400 ++ +0x0 +0x400 +registers ++ +TIM6_DAC +TIM6 global interrupt, DAC1 and DAC2 underrun + error interrupt +54 ++ ++ +CR +CR +control register +0x0 +0x20 +read-write +0x00000000 ++ ++ +DMAUDRIE2 +DAC channel2 DMA underrun interrupt + enable +29 +1 ++ +DMAEN2 +DAC channel2 DMA enable +28 +1 ++ +MAMP2 +DAC channel2 mask/amplitude + selector +24 +4 ++ +WAVE2 +DAC channel2 noise/triangle wave + generation enable +22 +2 ++ +TSEL2 +DAC channel2 trigger + selection +19 +3 ++ +TEN2 +DAC channel2 trigger + enable +18 +1 ++ +BOFF2 +DAC channel2 output buffer + disable +17 +1 ++ +EN2 +DAC channel2 enable +16 +1 ++ +DMAUDRIE1 +DAC channel1 DMA Underrun Interrupt + enable +13 +1 ++ +DMAEN1 +DAC channel1 DMA enable +12 +1 ++ +MAMP1 +DAC channel1 mask/amplitude + selector +8 +4 ++ +WAVE1 +DAC channel1 noise/triangle wave + generation enable +6 +2 ++ +TSEL1 +DAC channel1 trigger + selection +3 +3 ++ +TEN1 +DAC channel1 trigger + enable +2 +1 ++ +BOFF1 +DAC channel1 output buffer + disable +1 +1 ++ +EN1 +DAC channel1 enable +0 +1 ++ +SWTRIGR +SWTRIGR +software trigger register +0x4 +0x20 +write-only +0x00000000 ++ ++ +SWTRIG2 +DAC channel2 software + trigger +1 +1 ++ +SWTRIG1 +DAC channel1 software + trigger +0 +1 ++ +DHR12R1 +DHR12R1 +channel1 12-bit right-aligned data holding + register +0x8 +0x20 +read-write +0x00000000 ++ ++ +DACC1DHR +DAC channel1 12-bit right-aligned + data +0 +12 ++ +DHR12L1 +DHR12L1 +channel1 12-bit left aligned data holding + register +0xC +0x20 +read-write +0x00000000 ++ ++ +DACC1DHR +DAC channel1 12-bit left-aligned + data +4 +12 ++ +DHR8R1 +DHR8R1 +channel1 8-bit right aligned data holding + register +0x10 +0x20 +read-write +0x00000000 ++ ++ +DACC1DHR +DAC channel1 8-bit right-aligned + data +0 +8 ++ +DHR12R2 +DHR12R2 +channel2 12-bit right aligned data holding + register +0x14 +0x20 +read-write +0x00000000 ++ ++ +DACC2DHR +DAC channel2 12-bit right-aligned + data +0 +12 ++ +DHR12L2 +DHR12L2 +channel2 12-bit left aligned data holding + register +0x18 +0x20 +read-write +0x00000000 ++ ++ +DACC2DHR +DAC channel2 12-bit left-aligned + data +4 +12 ++ +DHR8R2 +DHR8R2 +channel2 8-bit right-aligned data holding + register +0x1C +0x20 +read-write +0x00000000 ++ ++ +DACC2DHR +DAC channel2 8-bit right-aligned + data +0 +8 ++ +DHR12RD +DHR12RD +Dual DAC 12-bit right-aligned data holding + register +0x20 +0x20 +read-write +0x00000000 ++ ++ +DACC2DHR +DAC channel2 12-bit right-aligned + data +16 +12 ++ +DACC1DHR +DAC channel1 12-bit right-aligned + data +0 +12 ++ +DHR12LD +DHR12LD +DUAL DAC 12-bit left aligned data holding + register +0x24 +0x20 +read-write +0x00000000 ++ ++ +DACC2DHR +DAC channel2 12-bit left-aligned + data +20 +12 ++ +DACC1DHR +DAC channel1 12-bit left-aligned + data +4 +12 ++ +DHR8RD +DHR8RD +DUAL DAC 8-bit right aligned data holding + register +0x28 +0x20 +read-write +0x00000000 ++ ++ +DACC2DHR +DAC channel2 8-bit right-aligned + data +8 +8 ++ +DACC1DHR +DAC channel1 8-bit right-aligned + data +0 +8 ++ +DOR1 +DOR1 +channel1 data output register +0x2C +0x20 +read-only +0x00000000 ++ ++ +DACC1DOR +DAC channel1 data output +0 +12 ++ +DOR2 +DOR2 +channel2 data output register +0x30 +0x20 +read-only +0x00000000 ++ ++ +DACC2DOR +DAC channel2 data output +0 +12 ++ +SR +SR +status register +0x34 +0x20 +read-write +0x00000000 ++ ++ +DMAUDR2 +DAC channel2 DMA underrun + flag +29 +1 ++ +DMAUDR1 +DAC channel1 DMA underrun + flag +13 +1 ++ +PWR +Power control +PWR +0x40007000 ++ +0x0 +0x400 +registers ++ +PVD +PVD through EXTI line detection + interrupt +1 ++ ++ +CR +CR +power control register +0x0 +0x20 +read-write +0x00000000 ++ ++ +FPDS +Flash power down in Stop + mode +9 +1 ++ +DBP +Disable backup domain write + protection +8 +1 ++ +PLS +PVD level selection +5 +3 ++ +PVDE +Power voltage detector + enable +4 +1 ++ +CSBF +Clear standby flag +3 +1 ++ +CWUF +Clear wakeup flag +2 +1 ++ +PDDS +Power down deepsleep +1 +1 ++ +LPDS +Low-power deep sleep +0 +1 ++ +CSR +CSR +power control/status register +0x4 +0x20 +0x00000000 ++ ++ +WUF +Wakeup flag +0 +1 +read-only ++ +SBF +Standby flag +1 +1 +read-only ++ +PVDO +PVD output +2 +1 +read-only ++ +BRR +Backup regulator ready +3 +1 +read-only ++ +EWUP +Enable WKUP pin +8 +1 +read-write ++ +BRE +Backup regulator enable +9 +1 +read-write ++ +VOSRDY +Regulator voltage scaling output + selection ready bit +14 +1 +read-write ++ +I2C3 +Inter-integrated circuit +I2C +0x40005C00 ++ +0x0 +0x400 +registers ++ +I2C3_EV +I2C3 event interrupt +72 ++ +I2C3_ER +I2C3 error interrupt +73 ++ ++ +CR1 +CR1 +Control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +SWRST +Software reset +15 +1 ++ +ALERT +SMBus alert +13 +1 ++ +PEC +Packet error checking +12 +1 ++ +POS +Acknowledge/PEC Position (for data + reception) +11 +1 ++ +ACK +Acknowledge enable +10 +1 ++ +STOP +Stop generation +9 +1 ++ +START +Start generation +8 +1 ++ +NOSTRETCH +Clock stretching disable (Slave + mode) +7 +1 ++ +ENGC +General call enable +6 +1 ++ +ENPEC +PEC enable +5 +1 ++ +ENARP +ARP enable +4 +1 ++ +SMBTYPE +SMBus type +3 +1 ++ +SMBUS +SMBus mode +1 +1 ++ +PE +Peripheral enable +0 +1 ++ +CR2 +CR2 +Control register 2 +0x4 +0x20 +read-write +0x0000 ++ ++ +LAST +DMA last transfer +12 +1 ++ +DMAEN +DMA requests enable +11 +1 ++ +ITBUFEN +Buffer interrupt enable +10 +1 ++ +ITEVTEN +Event interrupt enable +9 +1 ++ +ITERREN +Error interrupt enable +8 +1 ++ +FREQ +Peripheral clock frequency +0 +6 ++ +OAR1 +OAR1 +Own address register 1 +0x8 +0x20 +read-write +0x0000 ++ ++ +ADDMODE +Addressing mode (slave + mode) +15 +1 ++ +ADD10 +Interface address +8 +2 ++ +ADD7 +Interface address +1 +7 ++ +ADD0 +Interface address +0 +1 ++ +OAR2 +OAR2 +Own address register 2 +0xC +0x20 +read-write +0x0000 ++ ++ +ADD2 +Interface address +1 +7 ++ +ENDUAL +Dual addressing mode + enable +0 +1 ++ +DR +DR +Data register +0x10 +0x20 +read-write +0x0000 ++ ++ +DR +8-bit data register +0 +8 ++ +SR1 +SR1 +Status register 1 +0x14 +0x20 +0x0000 ++ ++ +SMBALERT +SMBus alert +15 +1 +read-write ++ +TIMEOUT +Timeout or Tlow error +14 +1 +read-write ++ +PECERR +PEC Error in reception +12 +1 +read-write ++ +OVR +Overrun/Underrun +11 +1 +read-write ++ +AF +Acknowledge failure +10 +1 +read-write ++ +ARLO +Arbitration lost (master + mode) +9 +1 +read-write ++ +BERR +Bus error +8 +1 +read-write ++ +TxE +Data register empty + (transmitters) +7 +1 +read-only ++ +RxNE +Data register not empty + (receivers) +6 +1 +read-only ++ +STOPF +Stop detection (slave + mode) +4 +1 +read-only ++ +ADD10 +10-bit header sent (Master + mode) +3 +1 +read-only ++ +BTF +Byte transfer finished +2 +1 +read-only ++ +ADDR +Address sent (master mode)/matched + (slave mode) +1 +1 +read-only ++ +SB +Start bit (Master mode) +0 +1 +read-only ++ +SR2 +SR2 +Status register 2 +0x18 +0x20 +read-only +0x0000 ++ ++ +PEC +acket error checking + register +8 +8 ++ +DUALF +Dual flag (Slave mode) +7 +1 ++ +SMBHOST +SMBus host header (Slave + mode) +6 +1 ++ +SMBDEFAULT +SMBus device default address (Slave + mode) +5 +1 ++ +GENCALL +General call address (Slave + mode) +4 +1 ++ +TRA +Transmitter/receiver +2 +1 ++ +BUSY +Bus busy +1 +1 ++ +MSL +Master/slave +0 +1 ++ +CCR +CCR +Clock control register +0x1C +0x20 +read-write +0x0000 ++ ++ +F_S +I2C master mode selection +15 +1 ++ +DUTY +Fast mode duty cycle +14 +1 ++ +CCR +Clock control register in Fast/Standard + mode (Master mode) +0 +12 ++ +TRISE +TRISE +TRISE register +0x20 +0x20 +read-write +0x0002 ++ ++ +TRISE +Maximum rise time in Fast/Standard mode + (Master mode) +0 +6 ++ +I2C2 +0x40005800 ++ +I2C2_EV +I2C2 event interrupt +33 ++ +I2C2_ER +I2C2 error interrupt +34 ++ +I2C1 +0x40005400 ++ +I2C1_EV +I2C1 event interrupt +31 ++ +I2C1_ER +I2C1 error interrupt +32 ++ +IWDG +Independent watchdog +IWDG +0x40003000 ++ +0x0 +0x400 +registers ++ ++ +KR +KR +Key register +0x0 +0x20 +write-only +0x00000000 ++ ++ +KEY +Key value (write only, read + 0000h) +0 +16 ++ +PR +PR +Prescaler register +0x4 +0x20 +read-write +0x00000000 ++ ++ +PR +Prescaler divider +0 +3 ++ +RLR +RLR +Reload register +0x8 +0x20 +read-write +0x00000FFF ++ ++ +RL +Watchdog counter reload + value +0 +12 ++ +SR +SR +Status register +0xC +0x20 +read-only +0x00000000 ++ ++ +RVU +Watchdog counter reload value + update +1 +1 ++ +PVU +Watchdog prescaler value + update +0 +1 ++ +WWDG +Window watchdog +WWDG +0x40002C00 ++ +0x0 +0x400 +registers ++ +WWDG +Window Watchdog interrupt +0 ++ ++ +CR +CR +Control register +0x0 +0x20 +read-write +0x7F ++ ++ +WDGA +Activation bit +7 +1 ++ +T +7-bit counter (MSB to LSB) +0 +7 ++ +CFR +CFR +Configuration register +0x4 +0x20 +read-write +0x7F ++ ++ +EWI +Early wakeup interrupt +9 +1 ++ +WDGTB1 +Timer base +8 +1 ++ +WDGTB0 +Timer base +7 +1 ++ +W +7-bit window value +0 +7 ++ +SR +SR +Status register +0x8 +0x20 +read-write +0x00 ++ ++ +EWIF +Early wakeup interrupt + flag +0 +1 ++ +RTC +Real-time clock +RTC +0x40002800 ++ +0x0 +0x400 +registers ++ +RTC_WKUP +RTC Wakeup interrupt through the EXTI + line +3 ++ +RTC_Alarm +RTC Alarms (A and B) through EXTI line + interrupt +41 ++ ++ +TR +TR +time register +0x0 +0x20 +read-write +0x00000000 ++ ++ +PM +AM/PM notation +22 +1 ++ +HT +Hour tens in BCD format +20 +2 ++ +HU +Hour units in BCD format +16 +4 ++ +MNT +Minute tens in BCD format +12 +3 ++ +MNU +Minute units in BCD format +8 +4 ++ +ST +Second tens in BCD format +4 +3 ++ +SU +Second units in BCD format +0 +4 ++ +DR +DR +date register +0x4 +0x20 +read-write +0x00002101 ++ ++ +YT +Year tens in BCD format +20 +4 ++ +YU +Year units in BCD format +16 +4 ++ +WDU +Week day units +13 +3 ++ +MT +Month tens in BCD format +12 +1 ++ +MU +Month units in BCD format +8 +4 ++ +DT +Date tens in BCD format +4 +2 ++ +DU +Date units in BCD format +0 +4 ++ +CR +CR +control register +0x8 +0x20 +read-write +0x00000000 ++ ++ +COE +Calibration output enable +23 +1 ++ +OSEL +Output selection +21 +2 ++ +POL +Output polarity +20 +1 ++ +BKP +Backup +18 +1 ++ +SUB1H +Subtract 1 hour (winter time + change) +17 +1 ++ +ADD1H +Add 1 hour (summer time + change) +16 +1 ++ +TSIE +Time-stamp interrupt + enable +15 +1 ++ +WUTIE +Wakeup timer interrupt + enable +14 +1 ++ +ALRBIE +Alarm B interrupt enable +13 +1 ++ +ALRAIE +Alarm A interrupt enable +12 +1 ++ +TSE +Time stamp enable +11 +1 ++ +WUTE +Wakeup timer enable +10 +1 ++ +ALRBE +Alarm B enable +9 +1 ++ +ALRAE +Alarm A enable +8 +1 ++ +DCE +Coarse digital calibration + enable +7 +1 ++ +FMT +Hour format +6 +1 ++ +REFCKON +Reference clock detection enable (50 or + 60 Hz) +4 +1 ++ +TSEDGE +Time-stamp event active + edge +3 +1 ++ +WCKSEL +Wakeup clock selection +0 +3 ++ +ISR +ISR +initialization and status + register +0xC +0x20 +0x00000007 ++ ++ +ALRAWF +Alarm A write flag +0 +1 +read-only ++ +ALRBWF +Alarm B write flag +1 +1 +read-only ++ +WUTWF +Wakeup timer write flag +2 +1 +read-only ++ +SHPF +Shift operation pending +3 +1 +read-write ++ +INITS +Initialization status flag +4 +1 +read-only ++ +RSF +Registers synchronization + flag +5 +1 +read-write ++ +INITF +Initialization flag +6 +1 +read-only ++ +INIT +Initialization mode +7 +1 +read-write ++ +ALRAF +Alarm A flag +8 +1 +read-write ++ +ALRBF +Alarm B flag +9 +1 +read-write ++ +WUTF +Wakeup timer flag +10 +1 +read-write ++ +TSF +Time-stamp flag +11 +1 +read-write ++ +TSOVF +Time-stamp overflow flag +12 +1 +read-write ++ +TAMP1F +Tamper detection flag +13 +1 +read-write ++ +TAMP2F +TAMPER2 detection flag +14 +1 +read-write ++ +RECALPF +Recalibration pending Flag +16 +1 +read-only ++ +PRER +PRER +prescaler register +0x10 +0x20 +read-write +0x007F00FF ++ ++ +PREDIV_A +Asynchronous prescaler + factor +16 +7 ++ +PREDIV_S +Synchronous prescaler + factor +0 +15 ++ +WUTR +WUTR +wakeup timer register +0x14 +0x20 +read-write +0x0000FFFF ++ ++ +WUT +Wakeup auto-reload value + bits +0 +16 ++ +CALIBR +CALIBR +calibration register +0x18 +0x20 +read-write +0x00000000 ++ ++ +DCS +Digital calibration sign +7 +1 ++ +DC +Digital calibration +0 +5 ++ +ALRMAR +ALRMAR +alarm A register +0x1C +0x20 +read-write +0x00000000 ++ ++ +MSK4 +Alarm A date mask +31 +1 ++ +WDSEL +Week day selection +30 +1 ++ +DT +Date tens in BCD format +28 +2 ++ +DU +Date units or day in BCD + format +24 +4 ++ +MSK3 +Alarm A hours mask +23 +1 ++ +PM +AM/PM notation +22 +1 ++ +HT +Hour tens in BCD format +20 +2 ++ +HU +Hour units in BCD format +16 +4 ++ +MSK2 +Alarm A minutes mask +15 +1 ++ +MNT +Minute tens in BCD format +12 +3 ++ +MNU +Minute units in BCD format +8 +4 ++ +MSK1 +Alarm A seconds mask +7 +1 ++ +ST +Second tens in BCD format +4 +3 ++ +SU +Second units in BCD format +0 +4 ++ +ALRMBR +ALRMBR +alarm B register +0x20 +0x20 +read-write +0x00000000 ++ ++ +MSK4 +Alarm B date mask +31 +1 ++ +WDSEL +Week day selection +30 +1 ++ +DT +Date tens in BCD format +28 +2 ++ +DU +Date units or day in BCD + format +24 +4 ++ +MSK3 +Alarm B hours mask +23 +1 ++ +PM +AM/PM notation +22 +1 ++ +HT +Hour tens in BCD format +20 +2 ++ +HU +Hour units in BCD format +16 +4 ++ +MSK2 +Alarm B minutes mask +15 +1 ++ +MNT +Minute tens in BCD format +12 +3 ++ +MNU +Minute units in BCD format +8 +4 ++ +MSK1 +Alarm B seconds mask +7 +1 ++ +ST +Second tens in BCD format +4 +3 ++ +SU +Second units in BCD format +0 +4 ++ +WPR +WPR +write protection register +0x24 +0x20 +write-only +0x00000000 ++ ++ +KEY +Write protection key +0 +8 ++ +SSR +SSR +sub second register +0x28 +0x20 +read-only +0x00000000 ++ ++ +SS +Sub second value +0 +16 ++ +SHIFTR +SHIFTR +shift control register +0x2C +0x20 +write-only +0x00000000 ++ ++ +ADD1S +Add one second +31 +1 ++ +SUBFS +Subtract a fraction of a + second +0 +15 ++ +TSTR +TSTR +time stamp time register +0x30 +0x20 +read-only +0x00000000 ++ ++ +ALARMOUTTYPE +AFO_ALARM output type +18 +1 ++ +TSINSEL +TIMESTAMP mapping +17 +1 ++ +TAMP1INSEL +TAMPER1 mapping +16 +1 ++ +TAMPIE +Tamper interrupt enable +2 +1 ++ +TAMP1TRG +Active level for tamper 1 +1 +1 ++ +TAMP1E +Tamper 1 detection enable +0 +1 ++ +TSDR +TSDR +time stamp date register +0x34 +0x20 +read-only +0x00000000 ++ ++ +WDU +Week day units +13 +3 ++ +MT +Month tens in BCD format +12 +1 ++ +MU +Month units in BCD format +8 +4 ++ +DT +Date tens in BCD format +4 +2 ++ +DU +Date units in BCD format +0 +4 ++ +TSSSR +TSSSR +timestamp sub second register +0x38 +0x20 +read-only +0x00000000 ++ ++ +SS +Sub second value +0 +16 ++ +CALR +CALR +calibration register +0x3C +0x20 +read-write +0x00000000 ++ ++ +CALP +Increase frequency of RTC by 488.5 + ppm +15 +1 ++ +CALW8 +Use an 8-second calibration cycle + period +14 +1 ++ +CALW16 +Use a 16-second calibration cycle + period +13 +1 ++ +CALM +Calibration minus +0 +9 ++ +TAFCR +TAFCR +tamper and alternate function configuration + register +0x40 +0x20 +read-write +0x00000000 ++ ++ +ALARMOUTTYPE +AFO_ALARM output type +18 +1 ++ +TSINSEL +TIMESTAMP mapping +17 +1 ++ +TAMP1INSEL +TAMPER1 mapping +16 +1 ++ +TAMPPUDIS +TAMPER pull-up disable +15 +1 ++ +TAMPPRCH +Tamper precharge duration +13 +2 ++ +TAMPFLT +Tamper filter count +11 +2 ++ +TAMPFREQ +Tamper sampling frequency +8 +3 ++ +TAMPTS +Activate timestamp on tamper detection + event +7 +1 ++ +TAMP2TRG +Active level for tamper 2 +4 +1 ++ +TAMP2E +Tamper 2 detection enable +3 +1 ++ +TAMPIE +Tamper interrupt enable +2 +1 ++ +TAMP1TRG +Active level for tamper 1 +1 +1 ++ +TAMP1E +Tamper 1 detection enable +0 +1 ++ +ALRMASSR +ALRMASSR +alarm A sub second register +0x44 +0x20 +read-write +0x00000000 ++ ++ +MASKSS +Mask the most-significant bits starting + at this bit +24 +4 ++ +SS +Sub seconds value +0 +15 ++ +ALRMBSSR +ALRMBSSR +alarm B sub second register +0x48 +0x20 +read-write +0x00000000 ++ ++ +MASKSS +Mask the most-significant bits starting + at this bit +24 +4 ++ +SS +Sub seconds value +0 +15 ++ +BKP0R +BKP0R +backup register +0x50 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP1R +BKP1R +backup register +0x54 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP2R +BKP2R +backup register +0x58 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP3R +BKP3R +backup register +0x5C +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP4R +BKP4R +backup register +0x60 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP5R +BKP5R +backup register +0x64 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP6R +BKP6R +backup register +0x68 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP7R +BKP7R +backup register +0x6C +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP8R +BKP8R +backup register +0x70 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP9R +BKP9R +backup register +0x74 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP10R +BKP10R +backup register +0x78 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP11R +BKP11R +backup register +0x7C +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP12R +BKP12R +backup register +0x80 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP13R +BKP13R +backup register +0x84 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP14R +BKP14R +backup register +0x88 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP15R +BKP15R +backup register +0x8C +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP16R +BKP16R +backup register +0x90 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP17R +BKP17R +backup register +0x94 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP18R +BKP18R +backup register +0x98 +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +BKP19R +BKP19R +backup register +0x9C +0x20 +read-write +0x00000000 ++ ++ +BKP +BKP +0 +32 ++ +UART4 +Universal synchronous asynchronous receiver + transmitter +USART +0x40004C00 ++ +0x0 +0x400 +registers ++ +UART4 +UART4 global interrupt +52 ++ ++ +SR +SR +Status register +0x0 +0x20 +0x00C00000 ++ ++ +LBD +LIN break detection flag +8 +1 +read-write ++ +TXE +Transmit data register + empty +7 +1 +read-only ++ +TC +Transmission complete +6 +1 +read-write ++ +RXNE +Read data register not + empty +5 +1 +read-write ++ +IDLE +IDLE line detected +4 +1 +read-only ++ +ORE +Overrun error +3 +1 +read-only ++ +NF +Noise detected flag +2 +1 +read-only ++ +FE +Framing error +1 +1 +read-only ++ +PE +Parity error +0 +1 +read-only ++ +DR +DR +Data register +0x4 +0x20 +read-write +0x00000000 ++ ++ +DR +Data value +0 +9 ++ +BRR +BRR +Baud rate register +0x8 +0x20 +read-write +0x0000 ++ ++ +DIV_Mantissa +mantissa of USARTDIV +4 +12 ++ +DIV_Fraction +fraction of USARTDIV +0 +4 ++ +CR1 +CR1 +Control register 1 +0xC +0x20 +read-write +0x0000 ++ ++ +OVER8 +Oversampling mode +15 +1 ++ +UE +USART enable +13 +1 ++ +M +Word length +12 +1 ++ +WAKE +Wakeup method +11 +1 ++ +PCE +Parity control enable +10 +1 ++ +PS +Parity selection +9 +1 ++ +PEIE +PE interrupt enable +8 +1 ++ +TXEIE +TXE interrupt enable +7 +1 ++ +TCIE +Transmission complete interrupt + enable +6 +1 ++ +RXNEIE +RXNE interrupt enable +5 +1 ++ +IDLEIE +IDLE interrupt enable +4 +1 ++ +TE +Transmitter enable +3 +1 ++ +RE +Receiver enable +2 +1 ++ +RWU +Receiver wakeup +1 +1 ++ +SBK +Send break +0 +1 ++ +CR2 +CR2 +Control register 2 +0x10 +0x20 +read-write +0x0000 ++ ++ +LINEN +LIN mode enable +14 +1 ++ +STOP +STOP bits +12 +2 ++ +LBDIE +LIN break detection interrupt + enable +6 +1 ++ +LBDL +lin break detection length +5 +1 ++ +ADD +Address of the USART node +0 +4 ++ +CR3 +CR3 +Control register 3 +0x14 +0x20 +read-write +0x0000 ++ ++ +ONEBIT +One sample bit method + enable +11 +1 ++ +DMAT +DMA enable transmitter +7 +1 ++ +DMAR +DMA enable receiver +6 +1 ++ +HDSEL +Half-duplex selection +3 +1 ++ +IRLP +IrDA low-power +2 +1 ++ +IREN +IrDA mode enable +1 +1 ++ +EIE +Error interrupt enable +0 +1 ++ +UART5 +0x40005000 ++ +UART5 +UART5 global interrupt +53 ++ +UART7 +0x40007800 ++ +UART4 +UART4 global interrupt +52 ++ +UART8 +0x40007C00 ++ +UART5 +UART5 global interrupt +53 ++ +C_ADC +Common ADC registers +ADC +0x40012300 ++ +0x0 +0x400 +registers ++ ++ +CSR +CSR +ADC Common status register +0x0 +0x20 +read-only +0x00000000 ++ ++ +OVR3 +Overrun flag of ADC3 +21 +1 ++ +STRT3 +Regular channel Start flag of ADC + 3 +20 +1 ++ +JSTRT3 +Injected channel Start flag of ADC + 3 +19 +1 ++ +JEOC3 +Injected channel end of conversion of + ADC 3 +18 +1 ++ +EOC3 +End of conversion of ADC 3 +17 +1 ++ +AWD3 +Analog watchdog flag of ADC + 3 +16 +1 ++ +OVR2 +Overrun flag of ADC 2 +13 +1 ++ +STRT2 +Regular channel Start flag of ADC + 2 +12 +1 ++ +JSTRT2 +Injected channel Start flag of ADC + 2 +11 +1 ++ +JEOC2 +Injected channel end of conversion of + ADC 2 +10 +1 ++ +EOC2 +End of conversion of ADC 2 +9 +1 ++ +AWD2 +Analog watchdog flag of ADC + 2 +8 +1 ++ +OVR1 +Overrun flag of ADC 1 +5 +1 ++ +STRT1 +Regular channel Start flag of ADC + 1 +4 +1 ++ +JSTRT1 +Injected channel Start flag of ADC + 1 +3 +1 ++ +JEOC1 +Injected channel end of conversion of + ADC 1 +2 +1 ++ +EOC1 +End of conversion of ADC 1 +1 +1 ++ +AWD1 +Analog watchdog flag of ADC + 1 +0 +1 ++ +CCR +CCR +ADC common control register +0x4 +0x20 +read-write +0x00000000 ++ ++ +TSVREFE +Temperature sensor and VREFINT + enable +23 +1 ++ +VBATE +VBAT enable +22 +1 ++ +ADCPRE +ADC prescaler +16 +2 ++ +DMA +Direct memory access mode for multi ADC + mode +14 +2 ++ +DDS +DMA disable selection for multi-ADC + mode +13 +1 ++ +DELAY +Delay between 2 sampling + phases +8 +4 ++ +MULT +Multi ADC mode selection +0 +5 ++ +CDR +CDR +ADC common regular data register for dual + and triple modes +0x8 +0x20 +read-only +0x00000000 ++ ++ +DATA2 +2nd data item of a pair of regular + conversions +16 +16 ++ +DATA1 +1st data item of a pair of regular + conversions +0 +16 ++ +TIM1 +Advanced-timers +TIM +0x40010000 ++ +0x0 +0x400 +registers ++ +TIM1_BRK_TIM9 +TIM1 Break interrupt and TIM9 global + interrupt +24 ++ +TIM1_UP_TIM10 +TIM1 Update interrupt and TIM10 global + interrupt +25 ++ +TIM1_TRG_COM_TIM11 +TIM1 Trigger and Commutation interrupts and + TIM11 global interrupt +26 ++ +TIM1_CC +TIM1 Capture Compare interrupt +27 ++ ++ +CR1 +CR1 +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +CKD +Clock division +8 +2 ++ +ARPE +Auto-reload preload enable +7 +1 ++ +CMS +Center-aligned mode + selection +5 +2 ++ +DIR +Direction +4 +1 ++ +OPM +One-pulse mode +3 +1 ++ +URS +Update request source +2 +1 ++ +UDIS +Update disable +1 +1 ++ +CEN +Counter enable +0 +1 ++ +CR2 +CR2 +control register 2 +0x4 +0x20 +read-write +0x0000 ++ ++ +OIS4 +Output Idle state 4 +14 +1 ++ +OIS3N +Output Idle state 3 +13 +1 ++ +OIS3 +Output Idle state 3 +12 +1 ++ +OIS2N +Output Idle state 2 +11 +1 ++ +OIS2 +Output Idle state 2 +10 +1 ++ +OIS1N +Output Idle state 1 +9 +1 ++ +OIS1 +Output Idle state 1 +8 +1 ++ +TI1S +TI1 selection +7 +1 ++ +MMS +Master mode selection +4 +3 ++ +CCDS +Capture/compare DMA + selection +3 +1 ++ +CCUS +Capture/compare control update + selection +2 +1 ++ +CCPC +Capture/compare preloaded + control +0 +1 ++ +SMCR +SMCR +slave mode control register +0x8 +0x20 +read-write +0x0000 ++ ++ +ETP +External trigger polarity +15 +1 ++ +ECE +External clock enable +14 +1 ++ +ETPS +External trigger prescaler +12 +2 ++ +ETF +External trigger filter +8 +4 ++ +MSM +Master/Slave mode +7 +1 ++ +TS +Trigger selection +4 +3 ++ +SMS +Slave mode selection +0 +3 ++ +DIER +DIER +DMA/Interrupt enable register +0xC +0x20 +read-write +0x0000 ++ ++ +TDE +Trigger DMA request enable +14 +1 ++ +COMDE +COM DMA request enable +13 +1 ++ +CC4DE +Capture/Compare 4 DMA request + enable +12 +1 ++ +CC3DE +Capture/Compare 3 DMA request + enable +11 +1 ++ +CC2DE +Capture/Compare 2 DMA request + enable +10 +1 ++ +CC1DE +Capture/Compare 1 DMA request + enable +9 +1 ++ +UDE +Update DMA request enable +8 +1 ++ +TIE +Trigger interrupt enable +6 +1 ++ +CC4IE +Capture/Compare 4 interrupt + enable +4 +1 ++ +CC3IE +Capture/Compare 3 interrupt + enable +3 +1 ++ +CC2IE +Capture/Compare 2 interrupt + enable +2 +1 ++ +CC1IE +Capture/Compare 1 interrupt + enable +1 +1 ++ +UIE +Update interrupt enable +0 +1 ++ +BIE +Break interrupt enable +7 +1 ++ +COMIE +COM interrupt enable +5 +1 ++ +SR +SR +status register +0x10 +0x20 +read-write +0x0000 ++ ++ +CC4OF +Capture/Compare 4 overcapture + flag +12 +1 ++ +CC3OF +Capture/Compare 3 overcapture + flag +11 +1 ++ +CC2OF +Capture/compare 2 overcapture + flag +10 +1 ++ +CC1OF +Capture/Compare 1 overcapture + flag +9 +1 ++ +BIF +Break interrupt flag +7 +1 ++ +TIF +Trigger interrupt flag +6 +1 ++ +COMIF +COM interrupt flag +5 +1 ++ +CC4IF +Capture/Compare 4 interrupt + flag +4 +1 ++ +CC3IF +Capture/Compare 3 interrupt + flag +3 +1 ++ +CC2IF +Capture/Compare 2 interrupt + flag +2 +1 ++ +CC1IF +Capture/compare 1 interrupt + flag +1 +1 ++ +UIF +Update interrupt flag +0 +1 ++ +EGR +EGR +event generation register +0x14 +0x20 +write-only +0x0000 ++ ++ +BG +Break generation +7 +1 ++ +TG +Trigger generation +6 +1 ++ +COMG +Capture/Compare control update + generation +5 +1 ++ +CC4G +Capture/compare 4 + generation +4 +1 ++ +CC3G +Capture/compare 3 + generation +3 +1 ++ +CC2G +Capture/compare 2 + generation +2 +1 ++ +CC1G +Capture/compare 1 + generation +1 +1 ++ +UG +Update generation +0 +1 ++ +CCMR1_Output +CCMR1_Output +capture/compare mode register 1 (output + mode) +0x18 +0x20 +read-write +0x00000000 ++ ++ +OC2CE +Output Compare 2 clear + enable +15 +1 ++ +OC2M +Output Compare 2 mode +12 +3 ++ +OC2PE +Output Compare 2 preload + enable +11 +1 ++ +OC2FE +Output Compare 2 fast + enable +10 +1 ++ +CC2S +Capture/Compare 2 + selection +8 +2 ++ +OC1CE +Output Compare 1 clear + enable +7 +1 ++ +OC1M +Output Compare 1 mode +4 +3 ++ +OC1PE +Output Compare 1 preload + enable +3 +1 ++ +OC1FE +Output Compare 1 fast + enable +2 +1 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCMR1_Input +CCMR1_Input +capture/compare mode register 1 (input + mode) +CCMR1_Output +0x18 +0x20 +read-write +0x00000000 ++ ++ +IC2F +Input capture 2 filter +12 +4 ++ +IC2PCS +Input capture 2 prescaler +10 +2 ++ +CC2S +Capture/Compare 2 + selection +8 +2 ++ +IC1F +Input capture 1 filter +4 +4 ++ +ICPCS +Input capture 1 prescaler +2 +2 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCMR2_Output +CCMR2_Output +capture/compare mode register 2 (output + mode) +0x1C +0x20 +read-write +0x00000000 ++ ++ +OC4CE +Output compare 4 clear + enable +15 +1 ++ +OC4M +Output compare 4 mode +12 +3 ++ +OC4PE +Output compare 4 preload + enable +11 +1 ++ +OC4FE +Output compare 4 fast + enable +10 +1 ++ +CC4S +Capture/Compare 4 + selection +8 +2 ++ +OC3CE +Output compare 3 clear + enable +7 +1 ++ +OC3M +Output compare 3 mode +4 +3 ++ +OC3PE +Output compare 3 preload + enable +3 +1 ++ +OC3FE +Output compare 3 fast + enable +2 +1 ++ +CC3S +Capture/Compare 3 + selection +0 +2 ++ +CCMR2_Input +CCMR2_Input +capture/compare mode register 2 (input + mode) +CCMR2_Output +0x1C +0x20 +read-write +0x00000000 ++ ++ +IC4F +Input capture 4 filter +12 +4 ++ +IC4PSC +Input capture 4 prescaler +10 +2 ++ +CC4S +Capture/Compare 4 + selection +8 +2 ++ +IC3F +Input capture 3 filter +4 +4 ++ +IC3PSC +Input capture 3 prescaler +2 +2 ++ +CC3S +Capture/compare 3 + selection +0 +2 ++ +CCER +CCER +capture/compare enable + register +0x20 +0x20 +read-write +0x0000 ++ ++ +CC4P +Capture/Compare 3 output + Polarity +13 +1 ++ +CC4E +Capture/Compare 4 output + enable +12 +1 ++ +CC3NP +Capture/Compare 3 output + Polarity +11 +1 ++ +CC3NE +Capture/Compare 3 complementary output + enable +10 +1 ++ +CC3P +Capture/Compare 3 output + Polarity +9 +1 ++ +CC3E +Capture/Compare 3 output + enable +8 +1 ++ +CC2NP +Capture/Compare 2 output + Polarity +7 +1 ++ +CC2NE +Capture/Compare 2 complementary output + enable +6 +1 ++ +CC2P +Capture/Compare 2 output + Polarity +5 +1 ++ +CC2E +Capture/Compare 2 output + enable +4 +1 ++ +CC1NP +Capture/Compare 1 output + Polarity +3 +1 ++ +CC1NE +Capture/Compare 1 complementary output + enable +2 +1 ++ +CC1P +Capture/Compare 1 output + Polarity +1 +1 ++ +CC1E +Capture/Compare 1 output + enable +0 +1 ++ +CNT +CNT +counter +0x24 +0x20 +read-write +0x00000000 ++ ++ +CNT +counter value +0 +16 ++ +PSC +PSC +prescaler +0x28 +0x20 +read-write +0x0000 ++ ++ +PSC +Prescaler value +0 +16 ++ +ARR +ARR +auto-reload register +0x2C +0x20 +read-write +0x00000000 ++ ++ +ARR +Auto-reload value +0 +16 ++ +CCR1 +CCR1 +capture/compare register 1 +0x34 +0x20 +read-write +0x00000000 ++ ++ +CCR1 +Capture/Compare 1 value +0 +16 ++ +CCR2 +CCR2 +capture/compare register 2 +0x38 +0x20 +read-write +0x00000000 ++ ++ +CCR2 +Capture/Compare 2 value +0 +16 ++ +CCR3 +CCR3 +capture/compare register 3 +0x3C +0x20 +read-write +0x00000000 ++ ++ +CCR3 +Capture/Compare value +0 +16 ++ +CCR4 +CCR4 +capture/compare register 4 +0x40 +0x20 +read-write +0x00000000 ++ ++ +CCR4 +Capture/Compare value +0 +16 ++ +DCR +DCR +DMA control register +0x48 +0x20 +read-write +0x0000 ++ ++ +DBL +DMA burst length +8 +5 ++ +DBA +DMA base address +0 +5 ++ +DMAR +DMAR +DMA address for full transfer +0x4C +0x20 +read-write +0x0000 ++ ++ +DMAB +DMA register for burst + accesses +0 +16 ++ +RCR +RCR +repetition counter register +0x30 +0x20 +read-write +0x0000 ++ ++ +REP +Repetition counter value +0 +8 ++ +BDTR +BDTR +break and dead-time register +0x44 +0x20 +read-write +0x0000 ++ ++ +MOE +Main output enable +15 +1 ++ +AOE +Automatic output enable +14 +1 ++ +BKP +Break polarity +13 +1 ++ +BKE +Break enable +12 +1 ++ +OSSR +Off-state selection for Run + mode +11 +1 ++ +OSSI +Off-state selection for Idle + mode +10 +1 ++ +LOCK +Lock configuration +8 +2 ++ +DTG +Dead-time generator setup +0 +8 ++ +TIM8 +0x40010400 ++ +TIM8_BRK_TIM12 +TIM8 Break interrupt and TIM12 global + interrupt +43 ++ +TIM8_UP_TIM13 +TIM8 Update interrupt and TIM13 global + interrupt +44 ++ +TIM8_TRG_COM_TIM14 +TIM8 Trigger and Commutation interrupts and + TIM14 global interrupt +45 ++ +TIM8_CC +TIM8 Capture Compare interrupt +46 ++ +TIM2 +General purpose timers +TIM +0x40000000 ++ +0x0 +0x400 +registers ++ +TIM2 +TIM2 global interrupt +28 ++ ++ +CR1 +CR1 +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +CKD +Clock division +8 +2 ++ +ARPE +Auto-reload preload enable +7 +1 ++ +CMS +Center-aligned mode + selection +5 +2 ++ +DIR +Direction +4 +1 ++ +OPM +One-pulse mode +3 +1 ++ +URS +Update request source +2 +1 ++ +UDIS +Update disable +1 +1 ++ +CEN +Counter enable +0 +1 ++ +CR2 +CR2 +control register 2 +0x4 +0x20 +read-write +0x0000 ++ ++ +TI1S +TI1 selection +7 +1 ++ +MMS +Master mode selection +4 +3 ++ +CCDS +Capture/compare DMA + selection +3 +1 ++ +SMCR +SMCR +slave mode control register +0x8 +0x20 +read-write +0x0000 ++ ++ +ETP +External trigger polarity +15 +1 ++ +ECE +External clock enable +14 +1 ++ +ETPS +External trigger prescaler +12 +2 ++ +ETF +External trigger filter +8 +4 ++ +MSM +Master/Slave mode +7 +1 ++ +TS +Trigger selection +4 +3 ++ +SMS +Slave mode selection +0 +3 ++ +DIER +DIER +DMA/Interrupt enable register +0xC +0x20 +read-write +0x0000 ++ ++ +TDE +Trigger DMA request enable +14 +1 ++ +CC4DE +Capture/Compare 4 DMA request + enable +12 +1 ++ +CC3DE +Capture/Compare 3 DMA request + enable +11 +1 ++ +CC2DE +Capture/Compare 2 DMA request + enable +10 +1 ++ +CC1DE +Capture/Compare 1 DMA request + enable +9 +1 ++ +UDE +Update DMA request enable +8 +1 ++ +TIE +Trigger interrupt enable +6 +1 ++ +CC4IE +Capture/Compare 4 interrupt + enable +4 +1 ++ +CC3IE +Capture/Compare 3 interrupt + enable +3 +1 ++ +CC2IE +Capture/Compare 2 interrupt + enable +2 +1 ++ +CC1IE +Capture/Compare 1 interrupt + enable +1 +1 ++ +UIE +Update interrupt enable +0 +1 ++ +SR +SR +status register +0x10 +0x20 +read-write +0x0000 ++ ++ +CC4OF +Capture/Compare 4 overcapture + flag +12 +1 ++ +CC3OF +Capture/Compare 3 overcapture + flag +11 +1 ++ +CC2OF +Capture/compare 2 overcapture + flag +10 +1 ++ +CC1OF +Capture/Compare 1 overcapture + flag +9 +1 ++ +TIF +Trigger interrupt flag +6 +1 ++ +CC4IF +Capture/Compare 4 interrupt + flag +4 +1 ++ +CC3IF +Capture/Compare 3 interrupt + flag +3 +1 ++ +CC2IF +Capture/Compare 2 interrupt + flag +2 +1 ++ +CC1IF +Capture/compare 1 interrupt + flag +1 +1 ++ +UIF +Update interrupt flag +0 +1 ++ +EGR +EGR +event generation register +0x14 +0x20 +write-only +0x0000 ++ ++ +TG +Trigger generation +6 +1 ++ +CC4G +Capture/compare 4 + generation +4 +1 ++ +CC3G +Capture/compare 3 + generation +3 +1 ++ +CC2G +Capture/compare 2 + generation +2 +1 ++ +CC1G +Capture/compare 1 + generation +1 +1 ++ +UG +Update generation +0 +1 ++ +CCMR1_Output +CCMR1_Output +capture/compare mode register 1 (output + mode) +0x18 +0x20 +read-write +0x00000000 ++ ++ +OC2CE +OC2CE +15 +1 ++ +OC2M +OC2M +12 +3 ++ +OC2PE +OC2PE +11 +1 ++ +OC2FE +OC2FE +10 +1 ++ +CC2S +CC2S +8 +2 ++ +OC1CE +OC1CE +7 +1 ++ +OC1M +OC1M +4 +3 ++ +OC1PE +OC1PE +3 +1 ++ +OC1FE +OC1FE +2 +1 ++ +CC1S +CC1S +0 +2 ++ +CCMR1_Input +CCMR1_Input +capture/compare mode register 1 (input + mode) +CCMR1_Output +0x18 +0x20 +read-write +0x00000000 ++ ++ +IC2F +Input capture 2 filter +12 +4 ++ +IC2PCS +Input capture 2 prescaler +10 +2 ++ +CC2S +Capture/Compare 2 + selection +8 +2 ++ +IC1F +Input capture 1 filter +4 +4 ++ +ICPCS +Input capture 1 prescaler +2 +2 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCMR2_Output +CCMR2_Output +capture/compare mode register 2 (output + mode) +0x1C +0x20 +read-write +0x00000000 ++ ++ +O24CE +O24CE +15 +1 ++ +OC4M +OC4M +12 +3 ++ +OC4PE +OC4PE +11 +1 ++ +OC4FE +OC4FE +10 +1 ++ +CC4S +CC4S +8 +2 ++ +OC3CE +OC3CE +7 +1 ++ +OC3M +OC3M +4 +3 ++ +OC3PE +OC3PE +3 +1 ++ +OC3FE +OC3FE +2 +1 ++ +CC3S +CC3S +0 +2 ++ +CCMR2_Input +CCMR2_Input +capture/compare mode register 2 (input + mode) +CCMR2_Output +0x1C +0x20 +read-write +0x00000000 ++ ++ +IC4F +Input capture 4 filter +12 +4 ++ +IC4PSC +Input capture 4 prescaler +10 +2 ++ +CC4S +Capture/Compare 4 + selection +8 +2 ++ +IC3F +Input capture 3 filter +4 +4 ++ +IC3PSC +Input capture 3 prescaler +2 +2 ++ +CC3S +Capture/compare 3 + selection +0 +2 ++ +CCER +CCER +capture/compare enable + register +0x20 +0x20 +read-write +0x0000 ++ ++ +CC4NP +Capture/Compare 4 output + Polarity +15 +1 ++ +CC4P +Capture/Compare 3 output + Polarity +13 +1 ++ +CC4E +Capture/Compare 4 output + enable +12 +1 ++ +CC3NP +Capture/Compare 3 output + Polarity +11 +1 ++ +CC3P +Capture/Compare 3 output + Polarity +9 +1 ++ +CC3E +Capture/Compare 3 output + enable +8 +1 ++ +CC2NP +Capture/Compare 2 output + Polarity +7 +1 ++ +CC2P +Capture/Compare 2 output + Polarity +5 +1 ++ +CC2E +Capture/Compare 2 output + enable +4 +1 ++ +CC1NP +Capture/Compare 1 output + Polarity +3 +1 ++ +CC1P +Capture/Compare 1 output + Polarity +1 +1 ++ +CC1E +Capture/Compare 1 output + enable +0 +1 ++ +CNT +CNT +counter +0x24 +0x20 +read-write +0x00000000 ++ ++ +CNT_H +High counter value +16 +16 ++ +CNT_L +Low counter value +0 +16 ++ +PSC +PSC +prescaler +0x28 +0x20 +read-write +0x0000 ++ ++ +PSC +Prescaler value +0 +16 ++ +ARR +ARR +auto-reload register +0x2C +0x20 +read-write +0x00000000 ++ ++ +ARR_H +High Auto-reload value +16 +16 ++ +ARR_L +Low Auto-reload value +0 +16 ++ +CCR1 +CCR1 +capture/compare register 1 +0x34 +0x20 +read-write +0x00000000 ++ ++ +CCR1_H +High Capture/Compare 1 + value +16 +16 ++ +CCR1_L +Low Capture/Compare 1 + value +0 +16 ++ +CCR2 +CCR2 +capture/compare register 2 +0x38 +0x20 +read-write +0x00000000 ++ ++ +CCR2_H +High Capture/Compare 2 + value +16 +16 ++ +CCR2_L +Low Capture/Compare 2 + value +0 +16 ++ +CCR3 +CCR3 +capture/compare register 3 +0x3C +0x20 +read-write +0x00000000 ++ ++ +CCR3_H +High Capture/Compare value +16 +16 ++ +CCR3_L +Low Capture/Compare value +0 +16 ++ +CCR4 +CCR4 +capture/compare register 4 +0x40 +0x20 +read-write +0x00000000 ++ ++ +CCR4_H +High Capture/Compare value +16 +16 ++ +CCR4_L +Low Capture/Compare value +0 +16 ++ +DCR +DCR +DMA control register +0x48 +0x20 +read-write +0x0000 ++ ++ +DBL +DMA burst length +8 +5 ++ +DBA +DMA base address +0 +5 ++ +DMAR +DMAR +DMA address for full transfer +0x4C +0x20 +read-write +0x0000 ++ ++ +DMAB +DMA register for burst + accesses +0 +16 ++ +OR +OR +TIM5 option register +0x50 +0x20 +read-write +0x0000 ++ ++ +ITR1_RMP +Timer Input 4 remap +10 +2 ++ +TIM3 +General purpose timers +TIM +0x40000400 ++ +0x0 +0x400 +registers ++ +TIM3 +TIM3 global interrupt +29 ++ ++ +CR1 +CR1 +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +CKD +Clock division +8 +2 ++ +ARPE +Auto-reload preload enable +7 +1 ++ +CMS +Center-aligned mode + selection +5 +2 ++ +DIR +Direction +4 +1 ++ +OPM +One-pulse mode +3 +1 ++ +URS +Update request source +2 +1 ++ +UDIS +Update disable +1 +1 ++ +CEN +Counter enable +0 +1 ++ +CR2 +CR2 +control register 2 +0x4 +0x20 +read-write +0x0000 ++ ++ +TI1S +TI1 selection +7 +1 ++ +MMS +Master mode selection +4 +3 ++ +CCDS +Capture/compare DMA + selection +3 +1 ++ +SMCR +SMCR +slave mode control register +0x8 +0x20 +read-write +0x0000 ++ ++ +ETP +External trigger polarity +15 +1 ++ +ECE +External clock enable +14 +1 ++ +ETPS +External trigger prescaler +12 +2 ++ +ETF +External trigger filter +8 +4 ++ +MSM +Master/Slave mode +7 +1 ++ +TS +Trigger selection +4 +3 ++ +SMS +Slave mode selection +0 +3 ++ +DIER +DIER +DMA/Interrupt enable register +0xC +0x20 +read-write +0x0000 ++ ++ +TDE +Trigger DMA request enable +14 +1 ++ +CC4DE +Capture/Compare 4 DMA request + enable +12 +1 ++ +CC3DE +Capture/Compare 3 DMA request + enable +11 +1 ++ +CC2DE +Capture/Compare 2 DMA request + enable +10 +1 ++ +CC1DE +Capture/Compare 1 DMA request + enable +9 +1 ++ +UDE +Update DMA request enable +8 +1 ++ +TIE +Trigger interrupt enable +6 +1 ++ +CC4IE +Capture/Compare 4 interrupt + enable +4 +1 ++ +CC3IE +Capture/Compare 3 interrupt + enable +3 +1 ++ +CC2IE +Capture/Compare 2 interrupt + enable +2 +1 ++ +CC1IE +Capture/Compare 1 interrupt + enable +1 +1 ++ +UIE +Update interrupt enable +0 +1 ++ +SR +SR +status register +0x10 +0x20 +read-write +0x0000 ++ ++ +CC4OF +Capture/Compare 4 overcapture + flag +12 +1 ++ +CC3OF +Capture/Compare 3 overcapture + flag +11 +1 ++ +CC2OF +Capture/compare 2 overcapture + flag +10 +1 ++ +CC1OF +Capture/Compare 1 overcapture + flag +9 +1 ++ +TIF +Trigger interrupt flag +6 +1 ++ +CC4IF +Capture/Compare 4 interrupt + flag +4 +1 ++ +CC3IF +Capture/Compare 3 interrupt + flag +3 +1 ++ +CC2IF +Capture/Compare 2 interrupt + flag +2 +1 ++ +CC1IF +Capture/compare 1 interrupt + flag +1 +1 ++ +UIF +Update interrupt flag +0 +1 ++ +EGR +EGR +event generation register +0x14 +0x20 +write-only +0x0000 ++ ++ +TG +Trigger generation +6 +1 ++ +CC4G +Capture/compare 4 + generation +4 +1 ++ +CC3G +Capture/compare 3 + generation +3 +1 ++ +CC2G +Capture/compare 2 + generation +2 +1 ++ +CC1G +Capture/compare 1 + generation +1 +1 ++ +UG +Update generation +0 +1 ++ +CCMR1_Output +CCMR1_Output +capture/compare mode register 1 (output + mode) +0x18 +0x20 +read-write +0x00000000 ++ ++ +OC2CE +OC2CE +15 +1 ++ +OC2M +OC2M +12 +3 ++ +OC2PE +OC2PE +11 +1 ++ +OC2FE +OC2FE +10 +1 ++ +CC2S +CC2S +8 +2 ++ +OC1CE +OC1CE +7 +1 ++ +OC1M +OC1M +4 +3 ++ +OC1PE +OC1PE +3 +1 ++ +OC1FE +OC1FE +2 +1 ++ +CC1S +CC1S +0 +2 ++ +CCMR1_Input +CCMR1_Input +capture/compare mode register 1 (input + mode) +CCMR1_Output +0x18 +0x20 +read-write +0x00000000 ++ ++ +IC2F +Input capture 2 filter +12 +4 ++ +IC2PCS +Input capture 2 prescaler +10 +2 ++ +CC2S +Capture/Compare 2 + selection +8 +2 ++ +IC1F +Input capture 1 filter +4 +4 ++ +ICPCS +Input capture 1 prescaler +2 +2 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCMR2_Output +CCMR2_Output +capture/compare mode register 2 (output + mode) +0x1C +0x20 +read-write +0x00000000 ++ ++ +O24CE +O24CE +15 +1 ++ +OC4M +OC4M +12 +3 ++ +OC4PE +OC4PE +11 +1 ++ +OC4FE +OC4FE +10 +1 ++ +CC4S +CC4S +8 +2 ++ +OC3CE +OC3CE +7 +1 ++ +OC3M +OC3M +4 +3 ++ +OC3PE +OC3PE +3 +1 ++ +OC3FE +OC3FE +2 +1 ++ +CC3S +CC3S +0 +2 ++ +CCMR2_Input +CCMR2_Input +capture/compare mode register 2 (input + mode) +CCMR2_Output +0x1C +0x20 +read-write +0x00000000 ++ ++ +IC4F +Input capture 4 filter +12 +4 ++ +IC4PSC +Input capture 4 prescaler +10 +2 ++ +CC4S +Capture/Compare 4 + selection +8 +2 ++ +IC3F +Input capture 3 filter +4 +4 ++ +IC3PSC +Input capture 3 prescaler +2 +2 ++ +CC3S +Capture/compare 3 + selection +0 +2 ++ +CCER +CCER +capture/compare enable + register +0x20 +0x20 +read-write +0x0000 ++ ++ +CC4NP +Capture/Compare 4 output + Polarity +15 +1 ++ +CC4P +Capture/Compare 3 output + Polarity +13 +1 ++ +CC4E +Capture/Compare 4 output + enable +12 +1 ++ +CC3NP +Capture/Compare 3 output + Polarity +11 +1 ++ +CC3P +Capture/Compare 3 output + Polarity +9 +1 ++ +CC3E +Capture/Compare 3 output + enable +8 +1 ++ +CC2NP +Capture/Compare 2 output + Polarity +7 +1 ++ +CC2P +Capture/Compare 2 output + Polarity +5 +1 ++ +CC2E +Capture/Compare 2 output + enable +4 +1 ++ +CC1NP +Capture/Compare 1 output + Polarity +3 +1 ++ +CC1P +Capture/Compare 1 output + Polarity +1 +1 ++ +CC1E +Capture/Compare 1 output + enable +0 +1 ++ +CNT +CNT +counter +0x24 +0x20 +read-write +0x00000000 ++ ++ +CNT_H +High counter value +16 +16 ++ +CNT_L +Low counter value +0 +16 ++ +PSC +PSC +prescaler +0x28 +0x20 +read-write +0x0000 ++ ++ +PSC +Prescaler value +0 +16 ++ +ARR +ARR +auto-reload register +0x2C +0x20 +read-write +0x00000000 ++ ++ +ARR_H +High Auto-reload value +16 +16 ++ +ARR_L +Low Auto-reload value +0 +16 ++ +CCR1 +CCR1 +capture/compare register 1 +0x34 +0x20 +read-write +0x00000000 ++ ++ +CCR1_H +High Capture/Compare 1 + value +16 +16 ++ +CCR1_L +Low Capture/Compare 1 + value +0 +16 ++ +CCR2 +CCR2 +capture/compare register 2 +0x38 +0x20 +read-write +0x00000000 ++ ++ +CCR2_H +High Capture/Compare 2 + value +16 +16 ++ +CCR2_L +Low Capture/Compare 2 + value +0 +16 ++ +CCR3 +CCR3 +capture/compare register 3 +0x3C +0x20 +read-write +0x00000000 ++ ++ +CCR3_H +High Capture/Compare value +16 +16 ++ +CCR3_L +Low Capture/Compare value +0 +16 ++ +CCR4 +CCR4 +capture/compare register 4 +0x40 +0x20 +read-write +0x00000000 ++ ++ +CCR4_H +High Capture/Compare value +16 +16 ++ +CCR4_L +Low Capture/Compare value +0 +16 ++ +DCR +DCR +DMA control register +0x48 +0x20 +read-write +0x0000 ++ ++ +DBL +DMA burst length +8 +5 ++ +DBA +DMA base address +0 +5 ++ +DMAR +DMAR +DMA address for full transfer +0x4C +0x20 +read-write +0x0000 ++ ++ +DMAB +DMA register for burst + accesses +0 +16 ++ +TIM4 +0x40000800 ++ +TIM4 +TIM4 global interrupt +30 ++ +TIM5 +General-purpose-timers +TIM +0x40000C00 ++ +0x0 +0x400 +registers ++ +TIM5 +TIM5 global interrupt +50 ++ ++ +CR1 +CR1 +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +CKD +Clock division +8 +2 ++ +ARPE +Auto-reload preload enable +7 +1 ++ +CMS +Center-aligned mode + selection +5 +2 ++ +DIR +Direction +4 +1 ++ +OPM +One-pulse mode +3 +1 ++ +URS +Update request source +2 +1 ++ +UDIS +Update disable +1 +1 ++ +CEN +Counter enable +0 +1 ++ +CR2 +CR2 +control register 2 +0x4 +0x20 +read-write +0x0000 ++ ++ +TI1S +TI1 selection +7 +1 ++ +MMS +Master mode selection +4 +3 ++ +CCDS +Capture/compare DMA + selection +3 +1 ++ +SMCR +SMCR +slave mode control register +0x8 +0x20 +read-write +0x0000 ++ ++ +ETP +External trigger polarity +15 +1 ++ +ECE +External clock enable +14 +1 ++ +ETPS +External trigger prescaler +12 +2 ++ +ETF +External trigger filter +8 +4 ++ +MSM +Master/Slave mode +7 +1 ++ +TS +Trigger selection +4 +3 ++ +SMS +Slave mode selection +0 +3 ++ +DIER +DIER +DMA/Interrupt enable register +0xC +0x20 +read-write +0x0000 ++ ++ +TDE +Trigger DMA request enable +14 +1 ++ +CC4DE +Capture/Compare 4 DMA request + enable +12 +1 ++ +CC3DE +Capture/Compare 3 DMA request + enable +11 +1 ++ +CC2DE +Capture/Compare 2 DMA request + enable +10 +1 ++ +CC1DE +Capture/Compare 1 DMA request + enable +9 +1 ++ +UDE +Update DMA request enable +8 +1 ++ +TIE +Trigger interrupt enable +6 +1 ++ +CC4IE +Capture/Compare 4 interrupt + enable +4 +1 ++ +CC3IE +Capture/Compare 3 interrupt + enable +3 +1 ++ +CC2IE +Capture/Compare 2 interrupt + enable +2 +1 ++ +CC1IE +Capture/Compare 1 interrupt + enable +1 +1 ++ +UIE +Update interrupt enable +0 +1 ++ +SR +SR +status register +0x10 +0x20 +read-write +0x0000 ++ ++ +CC4OF +Capture/Compare 4 overcapture + flag +12 +1 ++ +CC3OF +Capture/Compare 3 overcapture + flag +11 +1 ++ +CC2OF +Capture/compare 2 overcapture + flag +10 +1 ++ +CC1OF +Capture/Compare 1 overcapture + flag +9 +1 ++ +TIF +Trigger interrupt flag +6 +1 ++ +CC4IF +Capture/Compare 4 interrupt + flag +4 +1 ++ +CC3IF +Capture/Compare 3 interrupt + flag +3 +1 ++ +CC2IF +Capture/Compare 2 interrupt + flag +2 +1 ++ +CC1IF +Capture/compare 1 interrupt + flag +1 +1 ++ +UIF +Update interrupt flag +0 +1 ++ +EGR +EGR +event generation register +0x14 +0x20 +write-only +0x0000 ++ ++ +TG +Trigger generation +6 +1 ++ +CC4G +Capture/compare 4 + generation +4 +1 ++ +CC3G +Capture/compare 3 + generation +3 +1 ++ +CC2G +Capture/compare 2 + generation +2 +1 ++ +CC1G +Capture/compare 1 + generation +1 +1 ++ +UG +Update generation +0 +1 ++ +CCMR1_Output +CCMR1_Output +capture/compare mode register 1 (output + mode) +0x18 +0x20 +read-write +0x00000000 ++ ++ +OC2CE +OC2CE +15 +1 ++ +OC2M +OC2M +12 +3 ++ +OC2PE +OC2PE +11 +1 ++ +OC2FE +OC2FE +10 +1 ++ +CC2S +CC2S +8 +2 ++ +OC1CE +OC1CE +7 +1 ++ +OC1M +OC1M +4 +3 ++ +OC1PE +OC1PE +3 +1 ++ +OC1FE +OC1FE +2 +1 ++ +CC1S +CC1S +0 +2 ++ +CCMR1_Input +CCMR1_Input +capture/compare mode register 1 (input + mode) +CCMR1_Output +0x18 +0x20 +read-write +0x00000000 ++ ++ +IC2F +Input capture 2 filter +12 +4 ++ +IC2PCS +Input capture 2 prescaler +10 +2 ++ +CC2S +Capture/Compare 2 + selection +8 +2 ++ +IC1F +Input capture 1 filter +4 +4 ++ +ICPCS +Input capture 1 prescaler +2 +2 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCMR2_Output +CCMR2_Output +capture/compare mode register 2 (output + mode) +0x1C +0x20 +read-write +0x00000000 ++ ++ +O24CE +O24CE +15 +1 ++ +OC4M +OC4M +12 +3 ++ +OC4PE +OC4PE +11 +1 ++ +OC4FE +OC4FE +10 +1 ++ +CC4S +CC4S +8 +2 ++ +OC3CE +OC3CE +7 +1 ++ +OC3M +OC3M +4 +3 ++ +OC3PE +OC3PE +3 +1 ++ +OC3FE +OC3FE +2 +1 ++ +CC3S +CC3S +0 +2 ++ +CCMR2_Input +CCMR2_Input +capture/compare mode register 2 (input + mode) +CCMR2_Output +0x1C +0x20 +read-write +0x00000000 ++ ++ +IC4F +Input capture 4 filter +12 +4 ++ +IC4PSC +Input capture 4 prescaler +10 +2 ++ +CC4S +Capture/Compare 4 + selection +8 +2 ++ +IC3F +Input capture 3 filter +4 +4 ++ +IC3PSC +Input capture 3 prescaler +2 +2 ++ +CC3S +Capture/compare 3 + selection +0 +2 ++ +CCER +CCER +capture/compare enable + register +0x20 +0x20 +read-write +0x0000 ++ ++ +CC4NP +Capture/Compare 4 output + Polarity +15 +1 ++ +CC4P +Capture/Compare 3 output + Polarity +13 +1 ++ +CC4E +Capture/Compare 4 output + enable +12 +1 ++ +CC3NP +Capture/Compare 3 output + Polarity +11 +1 ++ +CC3P +Capture/Compare 3 output + Polarity +9 +1 ++ +CC3E +Capture/Compare 3 output + enable +8 +1 ++ +CC2NP +Capture/Compare 2 output + Polarity +7 +1 ++ +CC2P +Capture/Compare 2 output + Polarity +5 +1 ++ +CC2E +Capture/Compare 2 output + enable +4 +1 ++ +CC1NP +Capture/Compare 1 output + Polarity +3 +1 ++ +CC1P +Capture/Compare 1 output + Polarity +1 +1 ++ +CC1E +Capture/Compare 1 output + enable +0 +1 ++ +CNT +CNT +counter +0x24 +0x20 +read-write +0x00000000 ++ ++ +CNT_H +High counter value +16 +16 ++ +CNT_L +Low counter value +0 +16 ++ +PSC +PSC +prescaler +0x28 +0x20 +read-write +0x0000 ++ ++ +PSC +Prescaler value +0 +16 ++ +ARR +ARR +auto-reload register +0x2C +0x20 +read-write +0x00000000 ++ ++ +ARR_H +High Auto-reload value +16 +16 ++ +ARR_L +Low Auto-reload value +0 +16 ++ +CCR1 +CCR1 +capture/compare register 1 +0x34 +0x20 +read-write +0x00000000 ++ ++ +CCR1_H +High Capture/Compare 1 + value +16 +16 ++ +CCR1_L +Low Capture/Compare 1 + value +0 +16 ++ +CCR2 +CCR2 +capture/compare register 2 +0x38 +0x20 +read-write +0x00000000 ++ ++ +CCR2_H +High Capture/Compare 2 + value +16 +16 ++ +CCR2_L +Low Capture/Compare 2 + value +0 +16 ++ +CCR3 +CCR3 +capture/compare register 3 +0x3C +0x20 +read-write +0x00000000 ++ ++ +CCR3_H +High Capture/Compare value +16 +16 ++ +CCR3_L +Low Capture/Compare value +0 +16 ++ +CCR4 +CCR4 +capture/compare register 4 +0x40 +0x20 +read-write +0x00000000 ++ ++ +CCR4_H +High Capture/Compare value +16 +16 ++ +CCR4_L +Low Capture/Compare value +0 +16 ++ +DCR +DCR +DMA control register +0x48 +0x20 +read-write +0x0000 ++ ++ +DBL +DMA burst length +8 +5 ++ +DBA +DMA base address +0 +5 ++ +DMAR +DMAR +DMA address for full transfer +0x4C +0x20 +read-write +0x0000 ++ ++ +DMAB +DMA register for burst + accesses +0 +16 ++ +OR +OR +TIM5 option register +0x50 +0x20 +read-write +0x0000 ++ ++ +IT4_RMP +Timer Input 4 remap +6 +2 ++ +TIM9 +General purpose timers +TIM +0x40014000 ++ +0x0 +0x400 +registers ++ +TIM1_BRK_TIM9 +TIM1 Break interrupt and TIM9 global + interrupt +24 ++ ++ +CR1 +CR1 +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +CKD +Clock division +8 +2 ++ +ARPE +Auto-reload preload enable +7 +1 ++ +OPM +One-pulse mode +3 +1 ++ +URS +Update request source +2 +1 ++ +UDIS +Update disable +1 +1 ++ +CEN +Counter enable +0 +1 ++ +CR2 +CR2 +control register 2 +0x4 +0x20 +read-write +0x0000 ++ ++ +MMS +Master mode selection +4 +3 ++ +SMCR +SMCR +slave mode control register +0x8 +0x20 +read-write +0x0000 ++ ++ +MSM +Master/Slave mode +7 +1 ++ +TS +Trigger selection +4 +3 ++ +SMS +Slave mode selection +0 +3 ++ +DIER +DIER +DMA/Interrupt enable register +0xC +0x20 +read-write +0x0000 ++ ++ +TIE +Trigger interrupt enable +6 +1 ++ +CC2IE +Capture/Compare 2 interrupt + enable +2 +1 ++ +CC1IE +Capture/Compare 1 interrupt + enable +1 +1 ++ +UIE +Update interrupt enable +0 +1 ++ +SR +SR +status register +0x10 +0x20 +read-write +0x0000 ++ ++ +CC2OF +Capture/compare 2 overcapture + flag +10 +1 ++ +CC1OF +Capture/Compare 1 overcapture + flag +9 +1 ++ +TIF +Trigger interrupt flag +6 +1 ++ +CC2IF +Capture/Compare 2 interrupt + flag +2 +1 ++ +CC1IF +Capture/compare 1 interrupt + flag +1 +1 ++ +UIF +Update interrupt flag +0 +1 ++ +EGR +EGR +event generation register +0x14 +0x20 +write-only +0x0000 ++ ++ +TG +Trigger generation +6 +1 ++ +CC2G +Capture/compare 2 + generation +2 +1 ++ +CC1G +Capture/compare 1 + generation +1 +1 ++ +UG +Update generation +0 +1 ++ +CCMR1_Output +CCMR1_Output +capture/compare mode register 1 (output + mode) +0x18 +0x20 +read-write +0x00000000 ++ ++ +OC2M +Output Compare 2 mode +12 +3 ++ +OC2PE +Output Compare 2 preload + enable +11 +1 ++ +OC2FE +Output Compare 2 fast + enable +10 +1 ++ +CC2S +Capture/Compare 2 + selection +8 +2 ++ +OC1M +Output Compare 1 mode +4 +3 ++ +OC1PE +Output Compare 1 preload + enable +3 +1 ++ +OC1FE +Output Compare 1 fast + enable +2 +1 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCMR1_Input +CCMR1_Input +capture/compare mode register 1 (input + mode) +CCMR1_Output +0x18 +0x20 +read-write +0x00000000 ++ ++ +IC2F +Input capture 2 filter +12 +3 ++ +IC2PCS +Input capture 2 prescaler +10 +2 ++ +CC2S +Capture/Compare 2 + selection +8 +2 ++ +IC1F +Input capture 1 filter +4 +3 ++ +ICPCS +Input capture 1 prescaler +2 +2 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCER +CCER +capture/compare enable + register +0x20 +0x20 +read-write +0x0000 ++ ++ +CC2NP +Capture/Compare 2 output + Polarity +7 +1 ++ +CC2P +Capture/Compare 2 output + Polarity +5 +1 ++ +CC2E +Capture/Compare 2 output + enable +4 +1 ++ +CC1NP +Capture/Compare 1 output + Polarity +3 +1 ++ +CC1P +Capture/Compare 1 output + Polarity +1 +1 ++ +CC1E +Capture/Compare 1 output + enable +0 +1 ++ +CNT +CNT +counter +0x24 +0x20 +read-write +0x00000000 ++ ++ +CNT +counter value +0 +16 ++ +PSC +PSC +prescaler +0x28 +0x20 +read-write +0x0000 ++ ++ +PSC +Prescaler value +0 +16 ++ +ARR +ARR +auto-reload register +0x2C +0x20 +read-write +0x00000000 ++ ++ +ARR +Auto-reload value +0 +16 ++ +CCR1 +CCR1 +capture/compare register 1 +0x34 +0x20 +read-write +0x00000000 ++ ++ +CCR1 +Capture/Compare 1 value +0 +16 ++ +CCR2 +CCR2 +capture/compare register 2 +0x38 +0x20 +read-write +0x00000000 ++ ++ +CCR2 +Capture/Compare 2 value +0 +16 ++ +TIM12 +0x40001800 ++ +TIM8_BRK_TIM12 +TIM8 Break interrupt and TIM12 global + interrupt +43 ++ +TIM10 +General-purpose-timers +TIM +0x40014400 ++ +0x0 +0x400 +registers ++ +TIM1_UP_TIM10 +TIM1 Update interrupt and TIM10 global + interrupt +25 ++ ++ +CR1 +CR1 +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +CKD +Clock division +8 +2 ++ +ARPE +Auto-reload preload enable +7 +1 ++ +URS +Update request source +2 +1 ++ +UDIS +Update disable +1 +1 ++ +CEN +Counter enable +0 +1 ++ +DIER +DIER +DMA/Interrupt enable register +0xC +0x20 +read-write +0x0000 ++ ++ +CC1IE +Capture/Compare 1 interrupt + enable +1 +1 ++ +UIE +Update interrupt enable +0 +1 ++ +SR +SR +status register +0x10 +0x20 +read-write +0x0000 ++ ++ +CC1OF +Capture/Compare 1 overcapture + flag +9 +1 ++ +CC1IF +Capture/compare 1 interrupt + flag +1 +1 ++ +UIF +Update interrupt flag +0 +1 ++ +EGR +EGR +event generation register +0x14 +0x20 +write-only +0x0000 ++ ++ +CC1G +Capture/compare 1 + generation +1 +1 ++ +UG +Update generation +0 +1 ++ +CCMR1_Output +CCMR1_Output +capture/compare mode register 1 (output + mode) +0x18 +0x20 +read-write +0x00000000 ++ ++ +OC1M +Output Compare 1 mode +4 +3 ++ +OC1PE +Output Compare 1 preload + enable +3 +1 ++ +OC1FE +Output Compare 1 fast + enable +2 +1 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCMR1_Input +CCMR1_Input +capture/compare mode register 1 (input + mode) +CCMR1_Output +0x18 +0x20 +read-write +0x00000000 ++ ++ +IC1F +Input capture 1 filter +4 +4 ++ +ICPCS +Input capture 1 prescaler +2 +2 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCER +CCER +capture/compare enable + register +0x20 +0x20 +read-write +0x0000 ++ ++ +CC1NP +Capture/Compare 1 output + Polarity +3 +1 ++ +CC1P +Capture/Compare 1 output + Polarity +1 +1 ++ +CC1E +Capture/Compare 1 output + enable +0 +1 ++ +CNT +CNT +counter +0x24 +0x20 +read-write +0x00000000 ++ ++ +CNT +counter value +0 +16 ++ +PSC +PSC +prescaler +0x28 +0x20 +read-write +0x0000 ++ ++ +PSC +Prescaler value +0 +16 ++ +ARR +ARR +auto-reload register +0x2C +0x20 +read-write +0x00000000 ++ ++ +ARR +Auto-reload value +0 +16 ++ +CCR1 +CCR1 +capture/compare register 1 +0x34 +0x20 +read-write +0x00000000 ++ ++ +CCR1 +Capture/Compare 1 value +0 +16 ++ +TIM13 +0x40001C00 ++ +TIM8_UP_TIM13 +TIM8 Update interrupt and TIM13 global + interrupt +44 ++ +TIM14 +0x40002000 ++ +TIM8_TRG_COM_TIM14 +TIM8 Trigger and Commutation interrupts and + TIM14 global interrupt +45 ++ +TIM11 +General-purpose-timers +TIM +0x40014800 ++ +0x0 +0x400 +registers ++ +TIM1_TRG_COM_TIM11 +TIM1 Trigger and Commutation interrupts and + TIM11 global interrupt +26 ++ ++ +CR1 +CR1 +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +CKD +Clock division +8 +2 ++ +ARPE +Auto-reload preload enable +7 +1 ++ +URS +Update request source +2 +1 ++ +UDIS +Update disable +1 +1 ++ +CEN +Counter enable +0 +1 ++ +DIER +DIER +DMA/Interrupt enable register +0xC +0x20 +read-write +0x0000 ++ ++ +CC1IE +Capture/Compare 1 interrupt + enable +1 +1 ++ +UIE +Update interrupt enable +0 +1 ++ +SR +SR +status register +0x10 +0x20 +read-write +0x0000 ++ ++ +CC1OF +Capture/Compare 1 overcapture + flag +9 +1 ++ +CC1IF +Capture/compare 1 interrupt + flag +1 +1 ++ +UIF +Update interrupt flag +0 +1 ++ +EGR +EGR +event generation register +0x14 +0x20 +write-only +0x0000 ++ ++ +CC1G +Capture/compare 1 + generation +1 +1 ++ +UG +Update generation +0 +1 ++ +CCMR1_Output +CCMR1_Output +capture/compare mode register 1 (output + mode) +0x18 +0x20 +read-write +0x00000000 ++ ++ +OC1M +Output Compare 1 mode +4 +3 ++ +OC1PE +Output Compare 1 preload + enable +3 +1 ++ +OC1FE +Output Compare 1 fast + enable +2 +1 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCMR1_Input +CCMR1_Input +capture/compare mode register 1 (input + mode) +CCMR1_Output +0x18 +0x20 +read-write +0x00000000 ++ ++ +IC1F +Input capture 1 filter +4 +4 ++ +ICPCS +Input capture 1 prescaler +2 +2 ++ +CC1S +Capture/Compare 1 + selection +0 +2 ++ +CCER +CCER +capture/compare enable + register +0x20 +0x20 +read-write +0x0000 ++ ++ +CC1NP +Capture/Compare 1 output + Polarity +3 +1 ++ +CC1P +Capture/Compare 1 output + Polarity +1 +1 ++ +CC1E +Capture/Compare 1 output + enable +0 +1 ++ +CNT +CNT +counter +0x24 +0x20 +read-write +0x00000000 ++ ++ +CNT +counter value +0 +16 ++ +PSC +PSC +prescaler +0x28 +0x20 +read-write +0x0000 ++ ++ +PSC +Prescaler value +0 +16 ++ +ARR +ARR +auto-reload register +0x2C +0x20 +read-write +0x00000000 ++ ++ +ARR +Auto-reload value +0 +16 ++ +CCR1 +CCR1 +capture/compare register 1 +0x34 +0x20 +read-write +0x00000000 ++ ++ +CCR1 +Capture/Compare 1 value +0 +16 ++ +OR +OR +option register +0x50 +0x20 +read-write +0x00000000 ++ ++ +RMP +Input 1 remapping + capability +0 +2 ++ +TIM6 +Basic timers +TIM +0x40001000 ++ +0x0 +0x400 +registers ++ +TIM6_DAC +TIM6 global interrupt, DAC1 and DAC2 underrun + error interrupt +54 ++ ++ +CR1 +CR1 +control register 1 +0x0 +0x20 +read-write +0x0000 ++ ++ +ARPE +Auto-reload preload enable +7 +1 ++ +OPM +One-pulse mode +3 +1 ++ +URS +Update request source +2 +1 ++ +UDIS +Update disable +1 +1 ++ +CEN +Counter enable +0 +1 ++ +CR2 +CR2 +control register 2 +0x4 +0x20 +read-write +0x0000 ++ ++ +MMS +Master mode selection +4 +3 ++ +DIER +DIER +DMA/Interrupt enable register +0xC +0x20 +read-write +0x0000 ++ ++ +UDE +Update DMA request enable +8 +1 ++ +UIE +Update interrupt enable +0 +1 ++ +SR +SR +status register +0x10 +0x20 +read-write +0x0000 ++ ++ +UIF +Update interrupt flag +0 +1 ++ +EGR +EGR +event generation register +0x14 +0x20 +write-only +0x0000 ++ ++ +UG +Update generation +0 +1 ++ +CNT +CNT +counter +0x24 +0x20 +read-write +0x00000000 ++ ++ +CNT +Low counter value +0 +16 ++ +PSC +PSC +prescaler +0x28 +0x20 +read-write +0x0000 ++ ++ +PSC +Prescaler value +0 +16 ++ +ARR +ARR +auto-reload register +0x2C +0x20 +read-write +0x00000000 ++ ++ +ARR +Low Auto-reload value +0 +16 ++ +TIM7 +0x40001400 ++ +TIM7 +TIM7 global interrupt +55 ++ +Ethernet_MAC +Ethernet: media access control + (MAC) +Ethernet +0x40028000 ++ +0x0 +0x61 +registers ++ +ETH +Ethernet global interrupt +61 ++ +ETH_WKUP +Ethernet Wakeup through EXTI line + interrupt +62 ++ ++ +MACCR +MACCR +Ethernet MAC configuration + register +0x0 +0x20 +read-write +0x0008000 ++ ++ +RE +RE +2 +1 ++ +TE +TE +3 +1 ++ +DC +DC +4 +1 ++ +BL +BL +5 +2 ++ +APCS +APCS +7 +1 ++ +RD +RD +9 +1 ++ +IPCO +IPCO +10 +1 ++ +DM +DM +11 +1 ++ +LM +LM +12 +1 ++ +ROD +ROD +13 +1 ++ +FES +FES +14 +1 ++ +CSD +CSD +16 +1 ++ +IFG +IFG +17 +3 ++ +JD +JD +22 +1 ++ +WD +WD +23 +1 ++ +CSTF +CSTF +25 +1 ++ +MACFFR +MACFFR +Ethernet MAC frame filter + register +0x4 +0x20 +read-write +0x00000000 ++ ++ +PM +PM +0 +1 ++ +HU +HU +1 +1 ++ +HM +HM +2 +1 ++ +DAIF +DAIF +3 +1 ++ +RAM +RAM +4 +1 ++ +BFD +BFD +5 +1 ++ +PCF +PCF +6 +1 ++ +SAIF +SAIF +7 +1 ++ +SAF +SAF +8 +1 ++ +HPF +HPF +9 +1 ++ +RA +RA +31 +1 ++ +MACHTHR +MACHTHR +Ethernet MAC hash table high + register +0x8 +0x20 +read-write +0x00000000 ++ ++ +HTH +HTH +0 +32 ++ +MACHTLR +MACHTLR +Ethernet MAC hash table low + register +0xC +0x20 +read-write +0x00000000 ++ ++ +HTL +HTL +0 +32 ++ +MACMIIAR +MACMIIAR +Ethernet MAC MII address + register +0x10 +0x20 +read-write +0x00000000 ++ ++ +MB +MB +0 +1 ++ +MW +MW +1 +1 ++ +CR +CR +2 +3 ++ +MR +MR +6 +5 ++ +PA +PA +11 +5 ++ +MACMIIDR +MACMIIDR +Ethernet MAC MII data register +0x14 +0x20 +read-write +0x00000000 ++ ++ +TD +TD +0 +16 ++ +MACFCR +MACFCR +Ethernet MAC flow control + register +0x18 +0x20 +read-write +0x00000000 ++ ++ +FCB +FCB +0 +1 ++ +TFCE +TFCE +1 +1 ++ +RFCE +RFCE +2 +1 ++ +UPFD +UPFD +3 +1 ++ +PLT +PLT +4 +2 ++ +ZQPD +ZQPD +7 +1 ++ +PT +PT +16 +16 ++ +MACVLANTR +MACVLANTR +Ethernet MAC VLAN tag register +0x1C +0x20 +read-write +0x00000000 ++ ++ +VLANTI +VLANTI +0 +16 ++ +VLANTC +VLANTC +16 +1 ++ +MACPMTCSR +MACPMTCSR +Ethernet MAC PMT control and status + register +0x2C +0x20 +read-write +0x00000000 ++ ++ +PD +PD +0 +1 ++ +MPE +MPE +1 +1 ++ +WFE +WFE +2 +1 ++ +MPR +MPR +5 +1 ++ +WFR +WFR +6 +1 ++ +GU +GU +9 +1 ++ +WFFRPR +WFFRPR +31 +1 ++ +MACDBGR +MACDBGR +Ethernet MAC debug register +0x34 +0x20 +read-only +0x00000000 ++ ++ +CR +CR +0 +1 ++ +CSR +CSR +1 +1 ++ +ROR +ROR +2 +1 ++ +MCF +MCF +3 +1 ++ +MCP +MCP +4 +1 ++ +MCFHP +MCFHP +5 +1 ++ +MACSR +MACSR +Ethernet MAC interrupt status + register +0x38 +0x20 +0x00000000 ++ ++ +PMTS +PMTS +3 +1 +read-only ++ +MMCS +MMCS +4 +1 +read-only ++ +MMCRS +MMCRS +5 +1 +read-only ++ +MMCTS +MMCTS +6 +1 +read-only ++ +TSTS +TSTS +9 +1 +read-write ++ +MACIMR +MACIMR +Ethernet MAC interrupt mask + register +0x3C +0x20 +read-write +0x00000000 ++ ++ +PMTIM +PMTIM +3 +1 ++ +TSTIM +TSTIM +9 +1 ++ +MACA0HR +MACA0HR +Ethernet MAC address 0 high + register +0x40 +0x20 +0x0010FFFF ++ ++ +MACA0H +MAC address0 high +0 +16 +read-write ++ +MO +Always 1 +31 +1 +read-only ++ +MACA0LR +MACA0LR +Ethernet MAC address 0 low + register +0x44 +0x20 +read-write +0xFFFFFFFF ++ ++ +MACA0L +0 +0 +32 ++ +MACA1HR +MACA1HR +Ethernet MAC address 1 high + register +0x48 +0x20 +read-write +0x0000FFFF ++ ++ +MACA1H +MACA1H +0 +16 ++ +MBC +MBC +24 +6 ++ +SA +SA +30 +1 ++ +AE +AE +31 +1 ++ +MACA1LR +MACA1LR +Ethernet MAC address1 low + register +0x4C +0x20 +read-write +0xFFFFFFFF ++ ++ +MACA1LR +MACA1LR +0 +32 ++ +MACA2HR +MACA2HR +Ethernet MAC address 2 high + register +0x50 +0x20 +read-write +0x0000FFFF ++ ++ +MAC2AH +MAC2AH +0 +16 ++ +MBC +MBC +24 +6 ++ +SA +SA +30 +1 ++ +AE +AE +31 +1 ++ +MACA2LR +MACA2LR +Ethernet MAC address 2 low + register +0x54 +0x20 +read-write +0xFFFFFFFF ++ ++ +MACA2L +MACA2L +0 +31 ++ +MACA3HR +MACA3HR +Ethernet MAC address 3 high + register +0x58 +0x20 +read-write +0x0000FFFF ++ ++ +MACA3H +MACA3H +0 +16 ++ +MBC +MBC +24 +6 ++ +SA +SA +30 +1 ++ +AE +AE +31 +1 ++ +MACA3LR +MACA3LR +Ethernet MAC address 3 low + register +0x5C +0x20 +read-write +0xFFFFFFFF ++ ++ +MBCA3L +MBCA3L +0 +32 ++ +Ethernet_MMC +Ethernet: MAC management counters +Ethernet +0x40028100 ++ +0x0 +0x400 +registers ++ ++ +MMCCR +MMCCR +Ethernet MMC control register +0x0 +0x20 +read-write +0x00000000 ++ ++ +CR +CR +0 +1 ++ +CSR +CSR +1 +1 ++ +ROR +ROR +2 +1 ++ +MCF +MCF +3 +1 ++ +MCP +MCP +4 +1 ++ +MCFHP +MCFHP +5 +1 ++ +MMCRIR +MMCRIR +Ethernet MMC receive interrupt + register +0x4 +0x20 +read-write +0x00000000 ++ ++ +RFCES +RFCES +5 +1 ++ +RFAES +RFAES +6 +1 ++ +RGUFS +RGUFS +17 +1 ++ +MMCTIR +MMCTIR +Ethernet MMC transmit interrupt + register +0x8 +0x20 +read-only +0x00000000 ++ ++ +TGFSCS +TGFSCS +14 +1 ++ +TGFMSCS +TGFMSCS +15 +1 ++ +TGFS +TGFS +21 +1 ++ +MMCRIMR +MMCRIMR +Ethernet MMC receive interrupt mask + register +0xC +0x20 +read-write +0x00000000 ++ ++ +RFCEM +RFCEM +5 +1 ++ +RFAEM +RFAEM +6 +1 ++ +RGUFM +RGUFM +17 +1 ++ +MMCTIMR +MMCTIMR +Ethernet MMC transmit interrupt mask + register +0x10 +0x20 +read-write +0x00000000 ++ ++ +TGFSCM +TGFSCM +14 +1 ++ +TGFMSCM +TGFMSCM +15 +1 ++ +TGFM +TGFM +16 +1 ++ +MMCTGFSCCR +MMCTGFSCCR +Ethernet MMC transmitted good frames after a + single collision counter +0x4C +0x20 +read-only +0x00000000 ++ ++ +TGFSCC +TGFSCC +0 +32 ++ +MMCTGFMSCCR +MMCTGFMSCCR +Ethernet MMC transmitted good frames after + more than a single collision +0x50 +0x20 +read-only +0x00000000 ++ ++ +TGFMSCC +TGFMSCC +0 +32 ++ +MMCTGFCR +MMCTGFCR +Ethernet MMC transmitted good frames counter + register +0x68 +0x20 +read-only +0x00000000 ++ ++ +TGFC +HTL +0 +32 ++ +MMCRFCECR +MMCRFCECR +Ethernet MMC received frames with CRC error + counter register +0x94 +0x20 +read-only +0x00000000 ++ ++ +RFCFC +RFCFC +0 +32 ++ +MMCRFAECR +MMCRFAECR +Ethernet MMC received frames with alignment + error counter register +0x98 +0x20 +read-only +0x00000000 ++ ++ +RFAEC +RFAEC +0 +32 ++ +MMCRGUFCR +MMCRGUFCR +MMC received good unicast frames counter + register +0xC4 +0x20 +read-only +0x00000000 ++ ++ +RGUFC +RGUFC +0 +32 ++ +Ethernet_PTP +Ethernet: Precision time protocol +Ethernet +0x40028700 ++ +0x0 +0x400 +registers ++ ++ +PTPTSCR +PTPTSCR +Ethernet PTP time stamp control + register +0x0 +0x20 +read-write +0x00002000 ++ ++ +TSE +TSE +0 +1 ++ +TSFCU +TSFCU +1 +1 ++ +TSPTPPSV2E +TSPTPPSV2E +10 +1 ++ +TSSPTPOEFE +TSSPTPOEFE +11 +1 ++ +TSSIPV6FE +TSSIPV6FE +12 +1 ++ +TSSIPV4FE +TSSIPV4FE +13 +1 ++ +TSSEME +TSSEME +14 +1 ++ +TSSMRME +TSSMRME +15 +1 ++ +TSCNT +TSCNT +16 +2 ++ +TSPFFMAE +TSPFFMAE +18 +1 ++ +TSSTI +TSSTI +2 +1 ++ +TSSTU +TSSTU +3 +1 ++ +TSITE +TSITE +4 +1 ++ +TTSARU +TTSARU +5 +1 ++ +TSSARFE +TSSARFE +8 +1 ++ +TSSSR +TSSSR +9 +1 ++ +PTPSSIR +PTPSSIR +Ethernet PTP subsecond increment + register +0x4 +0x20 +read-write +0x00000000 ++ ++ +STSSI +STSSI +0 +8 ++ +PTPTSHR +PTPTSHR +Ethernet PTP time stamp high + register +0x8 +0x20 +read-only +0x00000000 ++ ++ +STS +STS +0 +32 ++ +PTPTSLR +PTPTSLR +Ethernet PTP time stamp low + register +0xC +0x20 +read-only +0x00000000 ++ ++ +STSS +STSS +0 +31 ++ +STPNS +STPNS +31 +1 ++ +PTPTSHUR +PTPTSHUR +Ethernet PTP time stamp high update + register +0x10 +0x20 +read-write +0x00000000 ++ ++ +TSUS +TSUS +0 +32 ++ +PTPTSLUR +PTPTSLUR +Ethernet PTP time stamp low update + register +0x14 +0x20 +read-write +0x00000000 ++ ++ +TSUSS +TSUSS +0 +31 ++ +TSUPNS +TSUPNS +31 +1 ++ +PTPTSAR +PTPTSAR +Ethernet PTP time stamp addend + register +0x18 +0x20 +read-write +0x00000000 ++ ++ +TSA +TSA +0 +32 ++ +PTPTTHR +PTPTTHR +Ethernet PTP target time high + register +0x1C +0x20 +read-write +0x00000000 ++ ++ +TTSH +0 +0 +32 ++ +PTPTTLR +PTPTTLR +Ethernet PTP target time low + register +0x20 +0x20 +read-write +0x00000000 ++ ++ +TTSL +TTSL +0 +32 ++ +PTPTSSR +PTPTSSR +Ethernet PTP time stamp status + register +0x28 +0x20 +read-only +0x00000000 ++ ++ +TSSO +TSSO +0 +1 ++ +TSTTR +TSTTR +1 +1 ++ +PTPPPSCR +PTPPPSCR +Ethernet PTP PPS control + register +0x2C +0x20 +read-only +0x00000000 ++ ++ +TSSO +TSSO +0 +1 ++ +TSTTR +TSTTR +1 +1 ++ +Ethernet_DMA +Ethernet: DMA controller operation +Ethernet +0x40029000 ++ +0x0 +0x400 +registers ++ ++ +DMABMR +DMABMR +Ethernet DMA bus mode register +0x0 +0x20 +read-write +0x00002101 ++ ++ +SR +SR +0 +1 ++ +DA +DA +1 +1 ++ +DSL +DSL +2 +5 ++ +EDFE +EDFE +7 +1 ++ +PBL +PBL +8 +6 ++ +RTPR +RTPR +14 +2 ++ +FB +FB +16 +1 ++ +RDP +RDP +17 +6 ++ +USP +USP +23 +1 ++ +FPM +FPM +24 +1 ++ +AAB +AAB +25 +1 ++ +MB +MB +26 +1 ++ +DMATPDR +DMATPDR +Ethernet DMA transmit poll demand + register +0x4 +0x20 +read-write +0x00000000 ++ ++ +TPD +TPD +0 +32 ++ +DMARPDR +DMARPDR +EHERNET DMA receive poll demand + register +0x8 +0x20 +read-write +0x00000000 ++ ++ +RPD +RPD +0 +32 ++ +DMARDLAR +DMARDLAR +Ethernet DMA receive descriptor list address + register +0xC +0x20 +read-write +0x00000000 ++ ++ +SRL +SRL +0 +32 ++ +DMATDLAR +DMATDLAR +Ethernet DMA transmit descriptor list + address register +0x10 +0x20 +read-write +0x00000000 ++ ++ +STL +STL +0 +32 ++ +DMASR +DMASR +Ethernet DMA status register +0x14 +0x20 +0x00000000 ++ ++ +TS +TS +0 +1 +read-write ++ +TPSS +TPSS +1 +1 +read-write ++ +TBUS +TBUS +2 +1 +read-write ++ +TJTS +TJTS +3 +1 +read-write ++ +ROS +ROS +4 +1 +read-write ++ +TUS +TUS +5 +1 +read-write ++ +RS +RS +6 +1 +read-write ++ +RBUS +RBUS +7 +1 +read-write ++ +RPSS +RPSS +8 +1 +read-write ++ +PWTS +PWTS +9 +1 +read-write ++ +ETS +ETS +10 +1 +read-write ++ +FBES +FBES +13 +1 +read-write ++ +ERS +ERS +14 +1 +read-write ++ +AIS +AIS +15 +1 +read-write ++ +NIS +NIS +16 +1 +read-write ++ +RPS +RPS +17 +3 +read-only ++ +TPS +TPS +20 +3 +read-only ++ +EBS +EBS +23 +3 +read-only ++ +MMCS +MMCS +27 +1 +read-only ++ +PMTS +PMTS +28 +1 +read-only ++ +TSTS +TSTS +29 +1 +read-only ++ +DMAOMR +DMAOMR +Ethernet DMA operation mode + register +0x18 +0x20 +read-write +0x00000000 ++ ++ +SR +SR +1 +1 ++ +OSF +OSF +2 +1 ++ +RTC +RTC +3 +2 ++ +FUGF +FUGF +6 +1 ++ +FEF +FEF +7 +1 ++ +ST +ST +13 +1 ++ +TTC +TTC +14 +3 ++ +FTF +FTF +20 +1 ++ +TSF +TSF +21 +1 ++ +DFRF +DFRF +24 +1 ++ +RSF +RSF +25 +1 ++ +DTCEFD +DTCEFD +26 +1 ++ +DMAIER +DMAIER +Ethernet DMA interrupt enable + register +0x1C +0x20 +read-write +0x00000000 ++ ++ +TIE +TIE +0 +1 ++ +TPSIE +TPSIE +1 +1 ++ +TBUIE +TBUIE +2 +1 ++ +TJTIE +TJTIE +3 +1 ++ +ROIE +ROIE +4 +1 ++ +TUIE +TUIE +5 +1 ++ +RIE +RIE +6 +1 ++ +RBUIE +RBUIE +7 +1 ++ +RPSIE +RPSIE +8 +1 ++ +RWTIE +RWTIE +9 +1 ++ +ETIE +ETIE +10 +1 ++ +FBEIE +FBEIE +13 +1 ++ +ERIE +ERIE +14 +1 ++ +AISE +AISE +15 +1 ++ +NISE +NISE +16 +1 ++ +DMAMFBOCR +DMAMFBOCR +Ethernet DMA missed frame and buffer + overflow counter register +0x20 +0x20 +read-write +0x00000000 ++ ++ +MFC +MFC +0 +16 ++ +OMFC +OMFC +16 +1 ++ +MFA +MFA +17 +11 ++ +OFOC +OFOC +28 +1 ++ +DMARSWTR +DMARSWTR +Ethernet DMA receive status watchdog timer + register +0x24 +0x20 +read-write +0x00000000 ++ ++ +RSWTC +RSWTC +0 +8 ++ +DMACHTDR +DMACHTDR +Ethernet DMA current host transmit + descriptor register +0x48 +0x20 +read-only +0x00000000 ++ ++ +HTDAP +HTDAP +0 +32 ++ +DMACHRDR +DMACHRDR +Ethernet DMA current host receive descriptor + register +0x4C +0x20 +read-only +0x00000000 ++ ++ +HRDAP +HRDAP +0 +32 ++ +DMACHTBAR +DMACHTBAR +Ethernet DMA current host transmit buffer + address register +0x50 +0x20 +read-only +0x00000000 ++ ++ +HTBAP +HTBAP +0 +32 ++ +DMACHRBAR +DMACHRBAR +Ethernet DMA current host receive buffer + address register +0x54 +0x20 +read-only +0x00000000 ++ ++ +HRBAP +HRBAP +0 +32 ++ +CRC +Cryptographic processor +CRC +0x40023000 ++ +0x0 +0x400 +registers ++ ++ +DR +DR +Data register +0x0 +0x20 +read-write +0xFFFFFFFF ++ ++ +DR +Data Register +0 +32 ++ +IDR +IDR +Independent Data register +0x4 +0x20 +read-write +0x00000000 ++ ++ +IDR +Independent Data register +0 +8 ++ +CR +CR +Control register +0x8 +0x20 +write-only +0x00000000 ++ ++ +CR +Control regidter +0 +1 ++ +OTG_FS_GLOBAL +USB on the go full speed +USB_OTG_FS +0x50000000 ++ +0x0 +0x400 +registers ++ +OTG_FS_WKUP +USB On-The-Go FS Wakeup through EXTI line + interrupt +42 ++ +OTG_FS +USB On The Go FS global + interrupt +67 ++ ++ +FS_GOTGCTL +FS_GOTGCTL +OTG_FS control and status register + (OTG_FS_GOTGCTL) +0x0 +0x20 +0x00000800 ++ ++ +SRQSCS +Session request success +0 +1 +read-only ++ +SRQ +Session request +1 +1 +read-write ++ +HNGSCS +Host negotiation success +8 +1 +read-only ++ +HNPRQ +HNP request +9 +1 +read-write ++ +HSHNPEN +Host set HNP enable +10 +1 +read-write ++ +DHNPEN +Device HNP enabled +11 +1 +read-write ++ +CIDSTS +Connector ID status +16 +1 +read-only ++ +DBCT +Long/short debounce time +17 +1 +read-only ++ +ASVLD +A-session valid +18 +1 +read-only ++ +BSVLD +B-session valid +19 +1 +read-only ++ +FS_GOTGINT +FS_GOTGINT +OTG_FS interrupt register + (OTG_FS_GOTGINT) +0x4 +0x20 +read-write +0x00000000 ++ ++ +SEDET +Session end detected +2 +1 ++ +SRSSCHG +Session request success status + change +8 +1 ++ +HNSSCHG +Host negotiation success status + change +9 +1 ++ +HNGDET +Host negotiation detected +17 +1 ++ +ADTOCHG +A-device timeout change +18 +1 ++ +DBCDNE +Debounce done +19 +1 ++ +FS_GAHBCFG +FS_GAHBCFG +OTG_FS AHB configuration register + (OTG_FS_GAHBCFG) +0x8 +0x20 +read-write +0x00000000 ++ ++ +GINT +Global interrupt mask +0 +1 ++ +TXFELVL +TxFIFO empty level +7 +1 ++ +PTXFELVL +Periodic TxFIFO empty + level +8 +1 ++ +FS_GUSBCFG +FS_GUSBCFG +OTG_FS USB configuration register + (OTG_FS_GUSBCFG) +0xC +0x20 +0x00000A00 ++ ++ +TOCAL +FS timeout calibration +0 +3 +read-write ++ +PHYSEL +Full Speed serial transceiver + select +6 +1 +write-only ++ +SRPCAP +SRP-capable +8 +1 +read-write ++ +HNPCAP +HNP-capable +9 +1 +read-write ++ +TRDT +USB turnaround time +10 +4 +read-write ++ +FHMOD +Force host mode +29 +1 +read-write ++ +FDMOD +Force device mode +30 +1 +read-write ++ +CTXPKT +Corrupt Tx packet +31 +1 +read-write ++ +FS_GRSTCTL +FS_GRSTCTL +OTG_FS reset register + (OTG_FS_GRSTCTL) +0x10 +0x20 +0x20000000 ++ ++ +CSRST +Core soft reset +0 +1 +read-write ++ +HSRST +HCLK soft reset +1 +1 +read-write ++ +FCRST +Host frame counter reset +2 +1 +read-write ++ +RXFFLSH +RxFIFO flush +4 +1 +read-write ++ +TXFFLSH +TxFIFO flush +5 +1 +read-write ++ +TXFNUM +TxFIFO number +6 +5 +read-write ++ +AHBIDL +AHB master idle +31 +1 +read-only ++ +FS_GINTSTS +FS_GINTSTS +OTG_FS core interrupt register + (OTG_FS_GINTSTS) +0x14 +0x20 +0x04000020 ++ ++ +CMOD +Current mode of operation +0 +1 +read-only ++ +MMIS +Mode mismatch interrupt +1 +1 +read-write ++ +OTGINT +OTG interrupt +2 +1 +read-only ++ +SOF +Start of frame +3 +1 +read-write ++ +RXFLVL +RxFIFO non-empty +4 +1 +read-only ++ +NPTXFE +Non-periodic TxFIFO empty +5 +1 +read-only ++ +GINAKEFF +Global IN non-periodic NAK + effective +6 +1 +read-only ++ +GOUTNAKEFF +Global OUT NAK effective +7 +1 +read-only ++ +ESUSP +Early suspend +10 +1 +read-write ++ +USBSUSP +USB suspend +11 +1 +read-write ++ +USBRST +USB reset +12 +1 +read-write ++ +ENUMDNE +Enumeration done +13 +1 +read-write ++ +ISOODRP +Isochronous OUT packet dropped + interrupt +14 +1 +read-write ++ +EOPF +End of periodic frame + interrupt +15 +1 +read-write ++ +IEPINT +IN endpoint interrupt +18 +1 +read-only ++ +OEPINT +OUT endpoint interrupt +19 +1 +read-only ++ +IISOIXFR +Incomplete isochronous IN + transfer +20 +1 +read-write ++ +IPXFR_INCOMPISOOUT +Incomplete periodic transfer(Host + mode)/Incomplete isochronous OUT transfer(Device + mode) +21 +1 +read-write ++ +HPRTINT +Host port interrupt +24 +1 +read-only ++ +HCINT +Host channels interrupt +25 +1 +read-only ++ +PTXFE +Periodic TxFIFO empty +26 +1 +read-only ++ +CIDSCHG +Connector ID status change +28 +1 +read-write ++ +DISCINT +Disconnect detected + interrupt +29 +1 +read-write ++ +SRQINT +Session request/new session detected + interrupt +30 +1 +read-write ++ +WKUPINT +Resume/remote wakeup detected + interrupt +31 +1 +read-write ++ +FS_GINTMSK +FS_GINTMSK +OTG_FS interrupt mask register + (OTG_FS_GINTMSK) +0x18 +0x20 +0x00000000 ++ ++ +MMISM +Mode mismatch interrupt + mask +1 +1 +read-write ++ +OTGINT +OTG interrupt mask +2 +1 +read-write ++ +SOFM +Start of frame mask +3 +1 +read-write ++ +RXFLVLM +Receive FIFO non-empty + mask +4 +1 +read-write ++ +NPTXFEM +Non-periodic TxFIFO empty + mask +5 +1 +read-write ++ +GINAKEFFM +Global non-periodic IN NAK effective + mask +6 +1 +read-write ++ +GONAKEFFM +Global OUT NAK effective + mask +7 +1 +read-write ++ +ESUSPM +Early suspend mask +10 +1 +read-write ++ +USBSUSPM +USB suspend mask +11 +1 +read-write ++ +USBRST +USB reset mask +12 +1 +read-write ++ +ENUMDNEM +Enumeration done mask +13 +1 +read-write ++ +ISOODRPM +Isochronous OUT packet dropped interrupt + mask +14 +1 +read-write ++ +EOPFM +End of periodic frame interrupt + mask +15 +1 +read-write ++ +EPMISM +Endpoint mismatch interrupt + mask +17 +1 +read-write ++ +IEPINT +IN endpoints interrupt + mask +18 +1 +read-write ++ +OEPINT +OUT endpoints interrupt + mask +19 +1 +read-write ++ +IISOIXFRM +Incomplete isochronous IN transfer + mask +20 +1 +read-write ++ +IPXFRM_IISOOXFRM +Incomplete periodic transfer mask(Host + mode)/Incomplete isochronous OUT transfer mask(Device + mode) +21 +1 +read-write ++ +PRTIM +Host port interrupt mask +24 +1 +read-only ++ +HCIM +Host channels interrupt + mask +25 +1 +read-write ++ +PTXFEM +Periodic TxFIFO empty mask +26 +1 +read-write ++ +CIDSCHGM +Connector ID status change + mask +28 +1 +read-write ++ +DISCINT +Disconnect detected interrupt + mask +29 +1 +read-write ++ +SRQIM +Session request/new session detected + interrupt mask +30 +1 +read-write ++ +WUIM +Resume/remote wakeup detected interrupt + mask +31 +1 +read-write ++ +FS_GRXSTSR_Device +FS_GRXSTSR_Device +OTG_FS Receive status debug read(Device + mode) +0x1C +0x20 +read-only +0x00000000 ++ ++ +EPNUM +Endpoint number +0 +4 ++ +BCNT +Byte count +4 +11 ++ +DPID +Data PID +15 +2 ++ +PKTSTS +Packet status +17 +4 ++ +FRMNUM +Frame number +21 +4 ++ +FS_GRXSTSR_Host +FS_GRXSTSR_Host +OTG_FS Receive status debug read(Host + mode) +FS_GRXSTSR_Device +0x1C +0x20 +read-only +0x00000000 ++ ++ +EPNUM +Endpoint number +0 +4 ++ +BCNT +Byte count +4 +11 ++ +DPID +Data PID +15 +2 ++ +PKTSTS +Packet status +17 +4 ++ +FRMNUM +Frame number +21 +4 ++ +FS_GRXFSIZ +FS_GRXFSIZ +OTG_FS Receive FIFO size register + (OTG_FS_GRXFSIZ) +0x24 +0x20 +read-write +0x00000200 ++ ++ +RXFD +RxFIFO depth +0 +16 ++ +FS_GNPTXFSIZ_Device +FS_GNPTXFSIZ_Device +OTG_FS non-periodic transmit FIFO size + register (Device mode) +0x28 +0x20 +read-write +0x00000200 ++ ++ +TX0FSA +Endpoint 0 transmit RAM start + address +0 +16 ++ +TX0FD +Endpoint 0 TxFIFO depth +16 +16 ++ +FS_GNPTXFSIZ_Host +FS_GNPTXFSIZ_Host +OTG_FS non-periodic transmit FIFO size + register (Host mode) +FS_GNPTXFSIZ_Device +0x28 +0x20 +read-write +0x00000200 ++ ++ +NPTXFSA +Non-periodic transmit RAM start + address +0 +16 ++ +NPTXFD +Non-periodic TxFIFO depth +16 +16 ++ +FS_GNPTXSTS +FS_GNPTXSTS +OTG_FS non-periodic transmit FIFO/queue + status register (OTG_FS_GNPTXSTS) +0x2C +0x20 +read-only +0x00080200 ++ ++ +NPTXFSAV +Non-periodic TxFIFO space + available +0 +16 ++ +NPTQXSAV +Non-periodic transmit request queue + space available +16 +8 ++ +NPTXQTOP +Top of the non-periodic transmit request + queue +24 +7 ++ +FS_GCCFG +FS_GCCFG +OTG_FS general core configuration register + (OTG_FS_GCCFG) +0x38 +0x20 +read-write +0x00000000 ++ ++ +PWRDWN +Power down +16 +1 ++ +VBUSASEN +Enable the VBUS sensing + device +18 +1 ++ +VBUSBSEN +Enable the VBUS sensing + device +19 +1 ++ +SOFOUTEN +SOF output enable +20 +1 ++ +FS_CID +FS_CID +core ID register +0x3C +0x20 +read-write +0x00001000 ++ ++ +PRODUCT_ID +Product ID field +0 +32 ++ +FS_HPTXFSIZ +FS_HPTXFSIZ +OTG_FS Host periodic transmit FIFO size + register (OTG_FS_HPTXFSIZ) +0x100 +0x20 +read-write +0x02000600 ++ ++ +PTXSA +Host periodic TxFIFO start + address +0 +16 ++ +PTXFSIZ +Host periodic TxFIFO depth +16 +16 ++ +FS_DIEPTXF1 +FS_DIEPTXF1 +OTG_FS device IN endpoint transmit FIFO size + register (OTG_FS_DIEPTXF2) +0x104 +0x20 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFO2 transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +FS_DIEPTXF2 +FS_DIEPTXF2 +OTG_FS device IN endpoint transmit FIFO size + register (OTG_FS_DIEPTXF3) +0x108 +0x20 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFO3 transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +FS_DIEPTXF3 +FS_DIEPTXF3 +OTG_FS device IN endpoint transmit FIFO size + register (OTG_FS_DIEPTXF4) +0x10C +0x20 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFO4 transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +OTG_FS_HOST +USB on the go full speed +USB_OTG_FS +0x50000400 ++ +0x0 +0x400 +registers ++ ++ +FS_HCFG +FS_HCFG +OTG_FS host configuration register + (OTG_FS_HCFG) +0x0 +0x20 +0x00000000 ++ ++ +FSLSPCS +FS/LS PHY clock select +0 +2 +read-write ++ +FSLSS +FS- and LS-only support +2 +1 +read-only ++ +HFIR +HFIR +OTG_FS Host frame interval + register +0x4 +0x20 +read-write +0x0000EA60 ++ ++ +FRIVL +Frame interval +0 +16 ++ +FS_HFNUM +FS_HFNUM +OTG_FS host frame number/frame time + remaining register (OTG_FS_HFNUM) +0x8 +0x20 +read-only +0x00003FFF ++ ++ +FRNUM +Frame number +0 +16 ++ +FTREM +Frame time remaining +16 +16 ++ +FS_HPTXSTS +FS_HPTXSTS +OTG_FS_Host periodic transmit FIFO/queue + status register (OTG_FS_HPTXSTS) +0x10 +0x20 +0x00080100 ++ ++ +PTXFSAVL +Periodic transmit data FIFO space + available +0 +16 +read-write ++ +PTXQSAV +Periodic transmit request queue space + available +16 +8 +read-only ++ +PTXQTOP +Top of the periodic transmit request + queue +24 +8 +read-only ++ +HAINT +HAINT +OTG_FS Host all channels interrupt + register +0x14 +0x20 +read-only +0x00000000 ++ ++ +HAINT +Channel interrupts +0 +16 ++ +HAINTMSK +HAINTMSK +OTG_FS host all channels interrupt mask + register +0x18 +0x20 +read-write +0x00000000 ++ ++ +HAINTM +Channel interrupt mask +0 +16 ++ +FS_HPRT +FS_HPRT +OTG_FS host port control and status register + (OTG_FS_HPRT) +0x40 +0x20 +0x00000000 ++ ++ +PCSTS +Port connect status +0 +1 +read-only ++ +PCDET +Port connect detected +1 +1 +read-write ++ +PENA +Port enable +2 +1 +read-write ++ +PENCHNG +Port enable/disable change +3 +1 +read-write ++ +POCA +Port overcurrent active +4 +1 +read-only ++ +POCCHNG +Port overcurrent change +5 +1 +read-write ++ +PRES +Port resume +6 +1 +read-write ++ +PSUSP +Port suspend +7 +1 +read-write ++ +PRST +Port reset +8 +1 +read-write ++ +PLSTS +Port line status +10 +2 +read-only ++ +PPWR +Port power +12 +1 +read-write ++ +PTCTL +Port test control +13 +4 +read-write ++ +PSPD +Port speed +17 +2 +read-only ++ +FS_HCCHAR0 +FS_HCCHAR0 +OTG_FS host channel-0 characteristics + register (OTG_FS_HCCHAR0) +0x100 +0x20 +read-write +0x00000000 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MCNT +Multicount +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +FS_HCCHAR1 +FS_HCCHAR1 +OTG_FS host channel-1 characteristics + register (OTG_FS_HCCHAR1) +0x120 +0x20 +read-write +0x00000000 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MCNT +Multicount +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +FS_HCCHAR2 +FS_HCCHAR2 +OTG_FS host channel-2 characteristics + register (OTG_FS_HCCHAR2) +0x140 +0x20 +read-write +0x00000000 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MCNT +Multicount +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +FS_HCCHAR3 +FS_HCCHAR3 +OTG_FS host channel-3 characteristics + register (OTG_FS_HCCHAR3) +0x160 +0x20 +read-write +0x00000000 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MCNT +Multicount +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +FS_HCCHAR4 +FS_HCCHAR4 +OTG_FS host channel-4 characteristics + register (OTG_FS_HCCHAR4) +0x180 +0x20 +read-write +0x00000000 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MCNT +Multicount +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +FS_HCCHAR5 +FS_HCCHAR5 +OTG_FS host channel-5 characteristics + register (OTG_FS_HCCHAR5) +0x1A0 +0x20 +read-write +0x00000000 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MCNT +Multicount +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +FS_HCCHAR6 +FS_HCCHAR6 +OTG_FS host channel-6 characteristics + register (OTG_FS_HCCHAR6) +0x1C0 +0x20 +read-write +0x00000000 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MCNT +Multicount +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +FS_HCCHAR7 +FS_HCCHAR7 +OTG_FS host channel-7 characteristics + register (OTG_FS_HCCHAR7) +0x1E0 +0x20 +read-write +0x00000000 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MCNT +Multicount +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +FS_HCINT0 +FS_HCINT0 +OTG_FS host channel-0 interrupt register + (OTG_FS_HCINT0) +0x108 +0x20 +read-write +0x00000000 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +FS_HCINT1 +FS_HCINT1 +OTG_FS host channel-1 interrupt register + (OTG_FS_HCINT1) +0x128 +0x20 +read-write +0x00000000 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +FS_HCINT2 +FS_HCINT2 +OTG_FS host channel-2 interrupt register + (OTG_FS_HCINT2) +0x148 +0x20 +read-write +0x00000000 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +FS_HCINT3 +FS_HCINT3 +OTG_FS host channel-3 interrupt register + (OTG_FS_HCINT3) +0x168 +0x20 +read-write +0x00000000 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +FS_HCINT4 +FS_HCINT4 +OTG_FS host channel-4 interrupt register + (OTG_FS_HCINT4) +0x188 +0x20 +read-write +0x00000000 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +FS_HCINT5 +FS_HCINT5 +OTG_FS host channel-5 interrupt register + (OTG_FS_HCINT5) +0x1A8 +0x20 +read-write +0x00000000 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +FS_HCINT6 +FS_HCINT6 +OTG_FS host channel-6 interrupt register + (OTG_FS_HCINT6) +0x1C8 +0x20 +read-write +0x00000000 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +FS_HCINT7 +FS_HCINT7 +OTG_FS host channel-7 interrupt register + (OTG_FS_HCINT7) +0x1E8 +0x20 +read-write +0x00000000 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +FS_HCINTMSK0 +FS_HCINTMSK0 +OTG_FS host channel-0 mask register + (OTG_FS_HCINTMSK0) +0x10C +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +FS_HCINTMSK1 +FS_HCINTMSK1 +OTG_FS host channel-1 mask register + (OTG_FS_HCINTMSK1) +0x12C +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +FS_HCINTMSK2 +FS_HCINTMSK2 +OTG_FS host channel-2 mask register + (OTG_FS_HCINTMSK2) +0x14C +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +FS_HCINTMSK3 +FS_HCINTMSK3 +OTG_FS host channel-3 mask register + (OTG_FS_HCINTMSK3) +0x16C +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +FS_HCINTMSK4 +FS_HCINTMSK4 +OTG_FS host channel-4 mask register + (OTG_FS_HCINTMSK4) +0x18C +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +FS_HCINTMSK5 +FS_HCINTMSK5 +OTG_FS host channel-5 mask register + (OTG_FS_HCINTMSK5) +0x1AC +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +FS_HCINTMSK6 +FS_HCINTMSK6 +OTG_FS host channel-6 mask register + (OTG_FS_HCINTMSK6) +0x1CC +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +FS_HCINTMSK7 +FS_HCINTMSK7 +OTG_FS host channel-7 mask register + (OTG_FS_HCINTMSK7) +0x1EC +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +FS_HCTSIZ0 +FS_HCTSIZ0 +OTG_FS host channel-0 transfer size + register +0x110 +0x20 +read-write +0x00000000 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +FS_HCTSIZ1 +FS_HCTSIZ1 +OTG_FS host channel-1 transfer size + register +0x130 +0x20 +read-write +0x00000000 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +FS_HCTSIZ2 +FS_HCTSIZ2 +OTG_FS host channel-2 transfer size + register +0x150 +0x20 +read-write +0x00000000 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +FS_HCTSIZ3 +FS_HCTSIZ3 +OTG_FS host channel-3 transfer size + register +0x170 +0x20 +read-write +0x00000000 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +FS_HCTSIZ4 +FS_HCTSIZ4 +OTG_FS host channel-x transfer size + register +0x190 +0x20 +read-write +0x00000000 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +FS_HCTSIZ5 +FS_HCTSIZ5 +OTG_FS host channel-5 transfer size + register +0x1B0 +0x20 +read-write +0x00000000 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +FS_HCTSIZ6 +FS_HCTSIZ6 +OTG_FS host channel-6 transfer size + register +0x1D0 +0x20 +read-write +0x00000000 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +FS_HCTSIZ7 +FS_HCTSIZ7 +OTG_FS host channel-7 transfer size + register +0x1F0 +0x20 +read-write +0x00000000 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_FS_DEVICE +USB on the go full speed +USB_OTG_FS +0x50000800 ++ +0x0 +0x400 +registers ++ ++ +FS_DCFG +FS_DCFG +OTG_FS device configuration register + (OTG_FS_DCFG) +0x0 +0x20 +read-write +0x02200000 ++ ++ +DSPD +Device speed +0 +2 ++ +NZLSOHSK +Non-zero-length status OUT + handshake +2 +1 ++ +DAD +Device address +4 +7 ++ +PFIVL +Periodic frame interval +11 +2 ++ +FS_DCTL +FS_DCTL +OTG_FS device control register + (OTG_FS_DCTL) +0x4 +0x20 +0x00000000 ++ ++ +RWUSIG +Remote wakeup signaling +0 +1 +read-write ++ +SDIS +Soft disconnect +1 +1 +read-write ++ +GINSTS +Global IN NAK status +2 +1 +read-only ++ +GONSTS +Global OUT NAK status +3 +1 +read-only ++ +TCTL +Test control +4 +3 +read-write ++ +SGINAK +Set global IN NAK +7 +1 +read-write ++ +CGINAK +Clear global IN NAK +8 +1 +read-write ++ +SGONAK +Set global OUT NAK +9 +1 +read-write ++ +CGONAK +Clear global OUT NAK +10 +1 +read-write ++ +POPRGDNE +Power-on programming done +11 +1 +read-write ++ +FS_DSTS +FS_DSTS +OTG_FS device status register + (OTG_FS_DSTS) +0x8 +0x20 +read-only +0x00000010 ++ ++ +SUSPSTS +Suspend status +0 +1 ++ +ENUMSPD +Enumerated speed +1 +2 ++ +EERR +Erratic error +3 +1 ++ +FNSOF +Frame number of the received + SOF +8 +14 ++ +FS_DIEPMSK +FS_DIEPMSK +OTG_FS device IN endpoint common interrupt + mask register (OTG_FS_DIEPMSK) +0x10 +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed interrupt + mask +0 +1 ++ +EPDM +Endpoint disabled interrupt + mask +1 +1 ++ +TOM +Timeout condition mask (Non-isochronous + endpoints) +3 +1 ++ +ITTXFEMSK +IN token received when TxFIFO empty + mask +4 +1 ++ +INEPNMM +IN token received with EP mismatch + mask +5 +1 ++ +INEPNEM +IN endpoint NAK effective + mask +6 +1 ++ +FS_DOEPMSK +FS_DOEPMSK +OTG_FS device OUT endpoint common interrupt + mask register (OTG_FS_DOEPMSK) +0x14 +0x20 +read-write +0x00000000 ++ ++ +XFRCM +Transfer completed interrupt + mask +0 +1 ++ +EPDM +Endpoint disabled interrupt + mask +1 +1 ++ +STUPM +SETUP phase done mask +3 +1 ++ +OTEPDM +OUT token received when endpoint + disabled mask +4 +1 ++ +FS_DAINT +FS_DAINT +OTG_FS device all endpoints interrupt + register (OTG_FS_DAINT) +0x18 +0x20 +read-only +0x00000000 ++ ++ +IEPINT +IN endpoint interrupt bits +0 +16 ++ +OEPINT +OUT endpoint interrupt + bits +16 +16 ++ +FS_DAINTMSK +FS_DAINTMSK +OTG_FS all endpoints interrupt mask register + (OTG_FS_DAINTMSK) +0x1C +0x20 +read-write +0x00000000 ++ ++ +IEPM +IN EP interrupt mask bits +0 +16 ++ +OEPINT +OUT endpoint interrupt + bits +16 +16 ++ +DVBUSDIS +DVBUSDIS +OTG_FS device VBUS discharge time + register +0x28 +0x20 +read-write +0x000017D7 ++ ++ +VBUSDT +Device VBUS discharge time +0 +16 ++ +DVBUSPULSE +DVBUSPULSE +OTG_FS device VBUS pulsing time + register +0x2C +0x20 +read-write +0x000005B8 ++ ++ +DVBUSP +Device VBUS pulsing time +0 +12 ++ +DIEPEMPMSK +DIEPEMPMSK +OTG_FS device IN endpoint FIFO empty + interrupt mask register +0x34 +0x20 +read-write +0x00000000 ++ ++ +INEPTXFEM +IN EP Tx FIFO empty interrupt mask + bits +0 +16 ++ +FS_DIEPCTL0 +FS_DIEPCTL0 +OTG_FS device control IN endpoint 0 control + register (OTG_FS_DIEPCTL0) +0x100 +0x20 +0x00000000 ++ ++ +MPSIZ +Maximum packet size +0 +2 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-only ++ +STALL +STALL handshake +21 +1 +read-write ++ +TXFNUM +TxFIFO number +22 +4 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-only ++ +EPENA +Endpoint enable +31 +1 +read-only ++ +DIEPCTL1 +DIEPCTL1 +OTG device endpoint-1 control + register +0x120 +0x20 +0x00000000 ++ ++ +EPENA +EPENA +31 +1 +read-write ++ +EPDIS +EPDIS +30 +1 +read-write ++ +SODDFRM_SD1PID +SODDFRM/SD1PID +29 +1 +write-only ++ +SD0PID_SEVNFRM +SD0PID/SEVNFRM +28 +1 +write-only ++ +SNAK +SNAK +27 +1 +write-only ++ +CNAK +CNAK +26 +1 +write-only ++ +TXFNUM +TXFNUM +22 +4 +read-write ++ +Stall +Stall +21 +1 +read-write ++ +EPTYP +EPTYP +18 +2 +read-write ++ +NAKSTS +NAKSTS +17 +1 +read-only ++ +EONUM_DPID +EONUM/DPID +16 +1 +read-only ++ +USBAEP +USBAEP +15 +1 +read-write ++ +MPSIZ +MPSIZ +0 +11 +read-write ++ +DIEPCTL2 +DIEPCTL2 +OTG device endpoint-2 control + register +0x140 +0x20 +0x00000000 ++ ++ +EPENA +EPENA +31 +1 +read-write ++ +EPDIS +EPDIS +30 +1 +read-write ++ +SODDFRM +SODDFRM +29 +1 +write-only ++ +SD0PID_SEVNFRM +SD0PID/SEVNFRM +28 +1 +write-only ++ +SNAK +SNAK +27 +1 +write-only ++ +CNAK +CNAK +26 +1 +write-only ++ +TXFNUM +TXFNUM +22 +4 +read-write ++ +Stall +Stall +21 +1 +read-write ++ +EPTYP +EPTYP +18 +2 +read-write ++ +NAKSTS +NAKSTS +17 +1 +read-only ++ +EONUM_DPID +EONUM/DPID +16 +1 +read-only ++ +USBAEP +USBAEP +15 +1 +read-write ++ +MPSIZ +MPSIZ +0 +11 +read-write ++ +DIEPCTL3 +DIEPCTL3 +OTG device endpoint-3 control + register +0x160 +0x20 +0x00000000 ++ ++ +EPENA +EPENA +31 +1 +read-write ++ +EPDIS +EPDIS +30 +1 +read-write ++ +SODDFRM +SODDFRM +29 +1 +write-only ++ +SD0PID_SEVNFRM +SD0PID/SEVNFRM +28 +1 +write-only ++ +SNAK +SNAK +27 +1 +write-only ++ +CNAK +CNAK +26 +1 +write-only ++ +TXFNUM +TXFNUM +22 +4 +read-write ++ +Stall +Stall +21 +1 +read-write ++ +EPTYP +EPTYP +18 +2 +read-write ++ +NAKSTS +NAKSTS +17 +1 +read-only ++ +EONUM_DPID +EONUM/DPID +16 +1 +read-only ++ +USBAEP +USBAEP +15 +1 +read-write ++ +MPSIZ +MPSIZ +0 +11 +read-write ++ +DOEPCTL0 +DOEPCTL0 +device endpoint-0 control + register +0x300 +0x20 +0x00008000 ++ ++ +EPENA +EPENA +31 +1 +write-only ++ +EPDIS +EPDIS +30 +1 +read-only ++ +SNAK +SNAK +27 +1 +write-only ++ +CNAK +CNAK +26 +1 +write-only ++ +Stall +Stall +21 +1 +read-write ++ +SNPM +SNPM +20 +1 +read-write ++ +EPTYP +EPTYP +18 +2 +read-only ++ +NAKSTS +NAKSTS +17 +1 +read-only ++ +USBAEP +USBAEP +15 +1 +read-only ++ +MPSIZ +MPSIZ +0 +2 +read-only ++ +DOEPCTL1 +DOEPCTL1 +device endpoint-1 control + register +0x320 +0x20 +0x00000000 ++ ++ +EPENA +EPENA +31 +1 +read-write ++ +EPDIS +EPDIS +30 +1 +read-write ++ +SODDFRM +SODDFRM +29 +1 +write-only ++ +SD0PID_SEVNFRM +SD0PID/SEVNFRM +28 +1 +write-only ++ +SNAK +SNAK +27 +1 +write-only ++ +CNAK +CNAK +26 +1 +write-only ++ +Stall +Stall +21 +1 +read-write ++ +SNPM +SNPM +20 +1 +read-write ++ +EPTYP +EPTYP +18 +2 +read-write ++ +NAKSTS +NAKSTS +17 +1 +read-only ++ +EONUM_DPID +EONUM/DPID +16 +1 +read-only ++ +USBAEP +USBAEP +15 +1 +read-write ++ +MPSIZ +MPSIZ +0 +11 +read-write ++ +DOEPCTL2 +DOEPCTL2 +device endpoint-2 control + register +0x340 +0x20 +0x00000000 ++ ++ +EPENA +EPENA +31 +1 +read-write ++ +EPDIS +EPDIS +30 +1 +read-write ++ +SODDFRM +SODDFRM +29 +1 +write-only ++ +SD0PID_SEVNFRM +SD0PID/SEVNFRM +28 +1 +write-only ++ +SNAK +SNAK +27 +1 +write-only ++ +CNAK +CNAK +26 +1 +write-only ++ +Stall +Stall +21 +1 +read-write ++ +SNPM +SNPM +20 +1 +read-write ++ +EPTYP +EPTYP +18 +2 +read-write ++ +NAKSTS +NAKSTS +17 +1 +read-only ++ +EONUM_DPID +EONUM/DPID +16 +1 +read-only ++ +USBAEP +USBAEP +15 +1 +read-write ++ +MPSIZ +MPSIZ +0 +11 +read-write ++ +DOEPCTL3 +DOEPCTL3 +device endpoint-3 control + register +0x360 +0x20 +0x00000000 ++ ++ +EPENA +EPENA +31 +1 +read-write ++ +EPDIS +EPDIS +30 +1 +read-write ++ +SODDFRM +SODDFRM +29 +1 +write-only ++ +SD0PID_SEVNFRM +SD0PID/SEVNFRM +28 +1 +write-only ++ +SNAK +SNAK +27 +1 +write-only ++ +CNAK +CNAK +26 +1 +write-only ++ +Stall +Stall +21 +1 +read-write ++ +SNPM +SNPM +20 +1 +read-write ++ +EPTYP +EPTYP +18 +2 +read-write ++ +NAKSTS +NAKSTS +17 +1 +read-only ++ +EONUM_DPID +EONUM/DPID +16 +1 +read-only ++ +USBAEP +USBAEP +15 +1 +read-write ++ +MPSIZ +MPSIZ +0 +11 +read-write ++ +DIEPINT0 +DIEPINT0 +device endpoint-x interrupt + register +0x108 +0x20 +0x00000080 ++ ++ +TXFE +TXFE +7 +1 +read-only ++ +INEPNE +INEPNE +6 +1 +read-write ++ +ITTXFE +ITTXFE +4 +1 +read-write ++ +TOC +TOC +3 +1 +read-write ++ +EPDISD +EPDISD +1 +1 +read-write ++ +XFRC +XFRC +0 +1 +read-write ++ +DIEPINT1 +DIEPINT1 +device endpoint-1 interrupt + register +0x128 +0x20 +0x00000080 ++ ++ +TXFE +TXFE +7 +1 +read-only ++ +INEPNE +INEPNE +6 +1 +read-write ++ +ITTXFE +ITTXFE +4 +1 +read-write ++ +TOC +TOC +3 +1 +read-write ++ +EPDISD +EPDISD +1 +1 +read-write ++ +XFRC +XFRC +0 +1 +read-write ++ +DIEPINT2 +DIEPINT2 +device endpoint-2 interrupt + register +0x148 +0x20 +0x00000080 ++ ++ +TXFE +TXFE +7 +1 +read-only ++ +INEPNE +INEPNE +6 +1 +read-write ++ +ITTXFE +ITTXFE +4 +1 +read-write ++ +TOC +TOC +3 +1 +read-write ++ +EPDISD +EPDISD +1 +1 +read-write ++ +XFRC +XFRC +0 +1 +read-write ++ +DIEPINT3 +DIEPINT3 +device endpoint-3 interrupt + register +0x168 +0x20 +0x00000080 ++ ++ +TXFE +TXFE +7 +1 +read-only ++ +INEPNE +INEPNE +6 +1 +read-write ++ +ITTXFE +ITTXFE +4 +1 +read-write ++ +TOC +TOC +3 +1 +read-write ++ +EPDISD +EPDISD +1 +1 +read-write ++ +XFRC +XFRC +0 +1 +read-write ++ +DOEPINT0 +DOEPINT0 +device endpoint-0 interrupt + register +0x308 +0x20 +read-write +0x00000080 ++ ++ +B2BSTUP +B2BSTUP +6 +1 ++ +OTEPDIS +OTEPDIS +4 +1 ++ +STUP +STUP +3 +1 ++ +EPDISD +EPDISD +1 +1 ++ +XFRC +XFRC +0 +1 ++ +DOEPINT1 +DOEPINT1 +device endpoint-1 interrupt + register +0x328 +0x20 +read-write +0x00000080 ++ ++ +B2BSTUP +B2BSTUP +6 +1 ++ +OTEPDIS +OTEPDIS +4 +1 ++ +STUP +STUP +3 +1 ++ +EPDISD +EPDISD +1 +1 ++ +XFRC +XFRC +0 +1 ++ +DOEPINT2 +DOEPINT2 +device endpoint-2 interrupt + register +0x348 +0x20 +read-write +0x00000080 ++ ++ +B2BSTUP +B2BSTUP +6 +1 ++ +OTEPDIS +OTEPDIS +4 +1 ++ +STUP +STUP +3 +1 ++ +EPDISD +EPDISD +1 +1 ++ +XFRC +XFRC +0 +1 ++ +DOEPINT3 +DOEPINT3 +device endpoint-3 interrupt + register +0x368 +0x20 +read-write +0x00000080 ++ ++ +B2BSTUP +B2BSTUP +6 +1 ++ +OTEPDIS +OTEPDIS +4 +1 ++ +STUP +STUP +3 +1 ++ +EPDISD +EPDISD +1 +1 ++ +XFRC +XFRC +0 +1 ++ +DIEPTSIZ0 +DIEPTSIZ0 +device endpoint-0 transfer size + register +0x110 +0x20 +read-write +0x00000000 ++ ++ +PKTCNT +Packet count +19 +2 ++ +XFRSIZ +Transfer size +0 +7 ++ +DOEPTSIZ0 +DOEPTSIZ0 +device OUT endpoint-0 transfer size + register +0x310 +0x20 +read-write +0x00000000 ++ ++ +STUPCNT +SETUP packet count +29 +2 ++ +PKTCNT +Packet count +19 +1 ++ +XFRSIZ +Transfer size +0 +7 ++ +DIEPTSIZ1 +DIEPTSIZ1 +device endpoint-1 transfer size + register +0x130 +0x20 +read-write +0x00000000 ++ ++ +MCNT +Multi count +29 +2 ++ +PKTCNT +Packet count +19 +10 ++ +XFRSIZ +Transfer size +0 +19 ++ +DIEPTSIZ2 +DIEPTSIZ2 +device endpoint-2 transfer size + register +0x150 +0x20 +read-write +0x00000000 ++ ++ +MCNT +Multi count +29 +2 ++ +PKTCNT +Packet count +19 +10 ++ +XFRSIZ +Transfer size +0 +19 ++ +DIEPTSIZ3 +DIEPTSIZ3 +device endpoint-3 transfer size + register +0x170 +0x20 +read-write +0x00000000 ++ ++ +MCNT +Multi count +29 +2 ++ +PKTCNT +Packet count +19 +10 ++ +XFRSIZ +Transfer size +0 +19 ++ +DTXFSTS0 +DTXFSTS0 +OTG_FS device IN endpoint transmit FIFO + status register +0x118 +0x20 +read-only +0x00000000 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + available +0 +16 ++ +DTXFSTS1 +DTXFSTS1 +OTG_FS device IN endpoint transmit FIFO + status register +0x138 +0x20 +read-only +0x00000000 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + available +0 +16 ++ +DTXFSTS2 +DTXFSTS2 +OTG_FS device IN endpoint transmit FIFO + status register +0x158 +0x20 +read-only +0x00000000 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + available +0 +16 ++ +DTXFSTS3 +DTXFSTS3 +OTG_FS device IN endpoint transmit FIFO + status register +0x178 +0x20 +read-only +0x00000000 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + available +0 +16 ++ +DOEPTSIZ1 +DOEPTSIZ1 +device OUT endpoint-1 transfer size + register +0x330 +0x20 +read-write +0x00000000 ++ ++ +RXDPID_STUPCNT +Received data PID/SETUP packet + count +29 +2 ++ +PKTCNT +Packet count +19 +10 ++ +XFRSIZ +Transfer size +0 +19 ++ +DOEPTSIZ2 +DOEPTSIZ2 +device OUT endpoint-2 transfer size + register +0x350 +0x20 +read-write +0x00000000 ++ ++ +RXDPID_STUPCNT +Received data PID/SETUP packet + count +29 +2 ++ +PKTCNT +Packet count +19 +10 ++ +XFRSIZ +Transfer size +0 +19 ++ +DOEPTSIZ3 +DOEPTSIZ3 +device OUT endpoint-3 transfer size + register +0x370 +0x20 +read-write +0x00000000 ++ ++ +RXDPID_STUPCNT +Received data PID/SETUP packet + count +29 +2 ++ +PKTCNT +Packet count +19 +10 ++ +XFRSIZ +Transfer size +0 +19 ++ +OTG_FS_PWRCLK +USB on the go full speed +USB_OTG_FS +0x50000E00 ++ +0x0 +0x400 +registers ++ ++ +FS_PCGCCTL +FS_PCGCCTL +OTG_FS power and clock gating control + register +0x0 +0x20 +read-write +0x00000000 ++ ++ +STPPCLK +Stop PHY clock +0 +1 ++ +GATEHCLK +Gate HCLK +1 +1 ++ +PHYSUSP +PHY Suspended +4 +1 ++ +CAN1 +Controller area network +CAN +0x40006400 ++ +0x0 +0x400 +registers ++ +CAN1_TX +CAN1 TX interrupts +19 ++ +CAN1_RX0 +CAN1 RX0 interrupts +20 ++ +CAN1_RX1 +CAN1 RX1 interrupts +21 ++ +CAN1_SCE +CAN1 SCE interrupt +22 ++ ++ +MCR +MCR +master control register +0x0 +0x20 +read-write +0x00010002 ++ ++ +DBF +DBF +16 +1 ++ +RESET +RESET +15 +1 ++ +TTCM +TTCM +7 +1 ++ +ABOM +ABOM +6 +1 ++ +AWUM +AWUM +5 +1 ++ +NART +NART +4 +1 ++ +RFLM +RFLM +3 +1 ++ +TXFP +TXFP +2 +1 ++ +SLEEP +SLEEP +1 +1 ++ +INRQ +INRQ +0 +1 ++ +MSR +MSR +master status register +0x4 +0x20 +0x00000C02 ++ ++ +RX +RX +11 +1 +read-only ++ +SAMP +SAMP +10 +1 +read-only ++ +RXM +RXM +9 +1 +read-only ++ +TXM +TXM +8 +1 +read-only ++ +SLAKI +SLAKI +4 +1 +read-write ++ +WKUI +WKUI +3 +1 +read-write ++ +ERRI +ERRI +2 +1 +read-write ++ +SLAK +SLAK +1 +1 +read-only ++ +INAK +INAK +0 +1 +read-only ++ +TSR +TSR +transmit status register +0x8 +0x20 +0x1C000000 ++ ++ +LOW2 +Lowest priority flag for mailbox + 2 +31 +1 +read-only ++ +LOW1 +Lowest priority flag for mailbox + 1 +30 +1 +read-only ++ +LOW0 +Lowest priority flag for mailbox + 0 +29 +1 +read-only ++ +TME2 +Lowest priority flag for mailbox + 2 +28 +1 +read-only ++ +TME1 +Lowest priority flag for mailbox + 1 +27 +1 +read-only ++ +TME0 +Lowest priority flag for mailbox + 0 +26 +1 +read-only ++ +CODE +CODE +24 +2 +read-only ++ +ABRQ2 +ABRQ2 +23 +1 +read-write ++ +TERR2 +TERR2 +19 +1 +read-write ++ +ALST2 +ALST2 +18 +1 +read-write ++ +TXOK2 +TXOK2 +17 +1 +read-write ++ +RQCP2 +RQCP2 +16 +1 +read-write ++ +ABRQ1 +ABRQ1 +15 +1 +read-write ++ +TERR1 +TERR1 +11 +1 +read-write ++ +ALST1 +ALST1 +10 +1 +read-write ++ +TXOK1 +TXOK1 +9 +1 +read-write ++ +RQCP1 +RQCP1 +8 +1 +read-write ++ +ABRQ0 +ABRQ0 +7 +1 +read-write ++ +TERR0 +TERR0 +3 +1 +read-write ++ +ALST0 +ALST0 +2 +1 +read-write ++ +TXOK0 +TXOK0 +1 +1 +read-write ++ +RQCP0 +RQCP0 +0 +1 +read-write ++ +RF0R +RF0R +receive FIFO 0 register +0xC +0x20 +0x00000000 ++ ++ +RFOM0 +RFOM0 +5 +1 +read-write ++ +FOVR0 +FOVR0 +4 +1 +read-write ++ +FULL0 +FULL0 +3 +1 +read-write ++ +FMP0 +FMP0 +0 +2 +read-only ++ +RF1R +RF1R +receive FIFO 1 register +0x10 +0x20 +0x00000000 ++ ++ +RFOM1 +RFOM1 +5 +1 +read-write ++ +FOVR1 +FOVR1 +4 +1 +read-write ++ +FULL1 +FULL1 +3 +1 +read-write ++ +FMP1 +FMP1 +0 +2 +read-only ++ +IER +IER +interrupt enable register +0x14 +0x20 +read-write +0x00000000 ++ ++ +SLKIE +SLKIE +17 +1 ++ +WKUIE +WKUIE +16 +1 ++ +ERRIE +ERRIE +15 +1 ++ +LECIE +LECIE +11 +1 ++ +BOFIE +BOFIE +10 +1 ++ +EPVIE +EPVIE +9 +1 ++ +EWGIE +EWGIE +8 +1 ++ +FOVIE1 +FOVIE1 +6 +1 ++ +FFIE1 +FFIE1 +5 +1 ++ +FMPIE1 +FMPIE1 +4 +1 ++ +FOVIE0 +FOVIE0 +3 +1 ++ +FFIE0 +FFIE0 +2 +1 ++ +FMPIE0 +FMPIE0 +1 +1 ++ +TMEIE +TMEIE +0 +1 ++ +ESR +ESR +interrupt enable register +0x18 +0x20 +0x00000000 ++ ++ +REC +REC +24 +8 +read-only ++ +TEC +TEC +16 +8 +read-only ++ +LEC +LEC +4 +3 +read-write ++ +BOFF +BOFF +2 +1 +read-only ++ +EPVF +EPVF +1 +1 +read-only ++ +EWGF +EWGF +0 +1 +read-only ++ +BTR +BTR +bit timing register +0x1C +0x20 +read-write +0x00000000 ++ ++ +SILM +SILM +31 +1 ++ +LBKM +LBKM +30 +1 ++ +SJW +SJW +24 +2 ++ +TS2 +TS2 +20 +3 ++ +TS1 +TS1 +16 +4 ++ +BRP +BRP +0 +10 ++ +TI0R +TI0R +TX mailbox identifier register +0x180 +0x20 +read-write +0x00000000 ++ ++ +STID +STID +21 +11 ++ +EXID +EXID +3 +18 ++ +IDE +IDE +2 +1 ++ +RTR +RTR +1 +1 ++ +TXRQ +TXRQ +0 +1 ++ +TDT0R +TDT0R +mailbox data length control and time stamp + register +0x184 +0x20 +read-write +0x00000000 ++ ++ +TIME +TIME +16 +16 ++ +TGT +TGT +8 +1 ++ +DLC +DLC +0 +4 ++ +TDL0R +TDL0R +mailbox data low register +0x188 +0x20 +read-write +0x00000000 ++ ++ +DATA3 +DATA3 +24 +8 ++ +DATA2 +DATA2 +16 +8 ++ +DATA1 +DATA1 +8 +8 ++ +DATA0 +DATA0 +0 +8 ++ +TDH0R +TDH0R +mailbox data high register +0x18C +0x20 +read-write +0x00000000 ++ ++ +DATA7 +DATA7 +24 +8 ++ +DATA6 +DATA6 +16 +8 ++ +DATA5 +DATA5 +8 +8 ++ +DATA4 +DATA4 +0 +8 ++ +TI1R +TI1R +mailbox identifier register +0x190 +0x20 +read-write +0x00000000 ++ ++ +STID +STID +21 +11 ++ +EXID +EXID +3 +18 ++ +IDE +IDE +2 +1 ++ +RTR +RTR +1 +1 ++ +TXRQ +TXRQ +0 +1 ++ +TDT1R +TDT1R +mailbox data length control and time stamp + register +0x194 +0x20 +read-write +0x00000000 ++ ++ +TIME +TIME +16 +16 ++ +TGT +TGT +8 +1 ++ +DLC +DLC +0 +4 ++ +TDL1R +TDL1R +mailbox data low register +0x198 +0x20 +read-write +0x00000000 ++ ++ +DATA3 +DATA3 +24 +8 ++ +DATA2 +DATA2 +16 +8 ++ +DATA1 +DATA1 +8 +8 ++ +DATA0 +DATA0 +0 +8 ++ +TDH1R +TDH1R +mailbox data high register +0x19C +0x20 +read-write +0x00000000 ++ ++ +DATA7 +DATA7 +24 +8 ++ +DATA6 +DATA6 +16 +8 ++ +DATA5 +DATA5 +8 +8 ++ +DATA4 +DATA4 +0 +8 ++ +TI2R +TI2R +mailbox identifier register +0x1A0 +0x20 +read-write +0x00000000 ++ ++ +STID +STID +21 +11 ++ +EXID +EXID +3 +18 ++ +IDE +IDE +2 +1 ++ +RTR +RTR +1 +1 ++ +TXRQ +TXRQ +0 +1 ++ +TDT2R +TDT2R +mailbox data length control and time stamp + register +0x1A4 +0x20 +read-write +0x00000000 ++ ++ +TIME +TIME +16 +16 ++ +TGT +TGT +8 +1 ++ +DLC +DLC +0 +4 ++ +TDL2R +TDL2R +mailbox data low register +0x1A8 +0x20 +read-write +0x00000000 ++ ++ +DATA3 +DATA3 +24 +8 ++ +DATA2 +DATA2 +16 +8 ++ +DATA1 +DATA1 +8 +8 ++ +DATA0 +DATA0 +0 +8 ++ +TDH2R +TDH2R +mailbox data high register +0x1AC +0x20 +read-write +0x00000000 ++ ++ +DATA7 +DATA7 +24 +8 ++ +DATA6 +DATA6 +16 +8 ++ +DATA5 +DATA5 +8 +8 ++ +DATA4 +DATA4 +0 +8 ++ +RI0R +RI0R +receive FIFO mailbox identifier + register +0x1B0 +0x20 +read-only +0x00000000 ++ ++ +STID +STID +21 +11 ++ +EXID +EXID +3 +18 ++ +IDE +IDE +2 +1 ++ +RTR +RTR +1 +1 ++ +RDT0R +RDT0R +mailbox data high register +0x1B4 +0x20 +read-only +0x00000000 ++ ++ +TIME +TIME +16 +16 ++ +FMI +FMI +8 +8 ++ +DLC +DLC +0 +4 ++ +RDL0R +RDL0R +mailbox data high register +0x1B8 +0x20 +read-only +0x00000000 ++ ++ +DATA3 +DATA3 +24 +8 ++ +DATA2 +DATA2 +16 +8 ++ +DATA1 +DATA1 +8 +8 ++ +DATA0 +DATA0 +0 +8 ++ +RDH0R +RDH0R +receive FIFO mailbox data high + register +0x1BC +0x20 +read-only +0x00000000 ++ ++ +DATA7 +DATA7 +24 +8 ++ +DATA6 +DATA6 +16 +8 ++ +DATA5 +DATA5 +8 +8 ++ +DATA4 +DATA4 +0 +8 ++ +RI1R +RI1R +mailbox data high register +0x1C0 +0x20 +read-only +0x00000000 ++ ++ +STID +STID +21 +11 ++ +EXID +EXID +3 +18 ++ +IDE +IDE +2 +1 ++ +RTR +RTR +1 +1 ++ +RDT1R +RDT1R +mailbox data high register +0x1C4 +0x20 +read-only +0x00000000 ++ ++ +TIME +TIME +16 +16 ++ +FMI +FMI +8 +8 ++ +DLC +DLC +0 +4 ++ +RDL1R +RDL1R +mailbox data high register +0x1C8 +0x20 +read-only +0x00000000 ++ ++ +DATA3 +DATA3 +24 +8 ++ +DATA2 +DATA2 +16 +8 ++ +DATA1 +DATA1 +8 +8 ++ +DATA0 +DATA0 +0 +8 ++ +RDH1R +RDH1R +mailbox data high register +0x1CC +0x20 +read-only +0x00000000 ++ ++ +DATA7 +DATA7 +24 +8 ++ +DATA6 +DATA6 +16 +8 ++ +DATA5 +DATA5 +8 +8 ++ +DATA4 +DATA4 +0 +8 ++ +FMR +FMR +filter master register +0x200 +0x20 +read-write +0x2A1C0E01 ++ ++ +CAN2SB +CAN2SB +8 +6 ++ +FINIT +FINIT +0 +1 ++ +FM1R +FM1R +filter mode register +0x204 +0x20 +read-write +0x00000000 ++ ++ +FBM0 +Filter mode +0 +1 ++ +FBM1 +Filter mode +1 +1 ++ +FBM2 +Filter mode +2 +1 ++ +FBM3 +Filter mode +3 +1 ++ +FBM4 +Filter mode +4 +1 ++ +FBM5 +Filter mode +5 +1 ++ +FBM6 +Filter mode +6 +1 ++ +FBM7 +Filter mode +7 +1 ++ +FBM8 +Filter mode +8 +1 ++ +FBM9 +Filter mode +9 +1 ++ +FBM10 +Filter mode +10 +1 ++ +FBM11 +Filter mode +11 +1 ++ +FBM12 +Filter mode +12 +1 ++ +FBM13 +Filter mode +13 +1 ++ +FBM14 +Filter mode +14 +1 ++ +FBM15 +Filter mode +15 +1 ++ +FBM16 +Filter mode +16 +1 ++ +FBM17 +Filter mode +17 +1 ++ +FBM18 +Filter mode +18 +1 ++ +FBM19 +Filter mode +19 +1 ++ +FBM20 +Filter mode +20 +1 ++ +FBM21 +Filter mode +21 +1 ++ +FBM22 +Filter mode +22 +1 ++ +FBM23 +Filter mode +23 +1 ++ +FBM24 +Filter mode +24 +1 ++ +FBM25 +Filter mode +25 +1 ++ +FBM26 +Filter mode +26 +1 ++ +FBM27 +Filter mode +27 +1 ++ +FS1R +FS1R +filter scale register +0x20C +0x20 +read-write +0x00000000 ++ ++ +FSC0 +Filter scale configuration +0 +1 ++ +FSC1 +Filter scale configuration +1 +1 ++ +FSC2 +Filter scale configuration +2 +1 ++ +FSC3 +Filter scale configuration +3 +1 ++ +FSC4 +Filter scale configuration +4 +1 ++ +FSC5 +Filter scale configuration +5 +1 ++ +FSC6 +Filter scale configuration +6 +1 ++ +FSC7 +Filter scale configuration +7 +1 ++ +FSC8 +Filter scale configuration +8 +1 ++ +FSC9 +Filter scale configuration +9 +1 ++ +FSC10 +Filter scale configuration +10 +1 ++ +FSC11 +Filter scale configuration +11 +1 ++ +FSC12 +Filter scale configuration +12 +1 ++ +FSC13 +Filter scale configuration +13 +1 ++ +FSC14 +Filter scale configuration +14 +1 ++ +FSC15 +Filter scale configuration +15 +1 ++ +FSC16 +Filter scale configuration +16 +1 ++ +FSC17 +Filter scale configuration +17 +1 ++ +FSC18 +Filter scale configuration +18 +1 ++ +FSC19 +Filter scale configuration +19 +1 ++ +FSC20 +Filter scale configuration +20 +1 ++ +FSC21 +Filter scale configuration +21 +1 ++ +FSC22 +Filter scale configuration +22 +1 ++ +FSC23 +Filter scale configuration +23 +1 ++ +FSC24 +Filter scale configuration +24 +1 ++ +FSC25 +Filter scale configuration +25 +1 ++ +FSC26 +Filter scale configuration +26 +1 ++ +FSC27 +Filter scale configuration +27 +1 ++ +FFA1R +FFA1R +filter FIFO assignment + register +0x214 +0x20 +read-write +0x00000000 ++ ++ +FFA0 +Filter FIFO assignment for filter + 0 +0 +1 ++ +FFA1 +Filter FIFO assignment for filter + 1 +1 +1 ++ +FFA2 +Filter FIFO assignment for filter + 2 +2 +1 ++ +FFA3 +Filter FIFO assignment for filter + 3 +3 +1 ++ +FFA4 +Filter FIFO assignment for filter + 4 +4 +1 ++ +FFA5 +Filter FIFO assignment for filter + 5 +5 +1 ++ +FFA6 +Filter FIFO assignment for filter + 6 +6 +1 ++ +FFA7 +Filter FIFO assignment for filter + 7 +7 +1 ++ +FFA8 +Filter FIFO assignment for filter + 8 +8 +1 ++ +FFA9 +Filter FIFO assignment for filter + 9 +9 +1 ++ +FFA10 +Filter FIFO assignment for filter + 10 +10 +1 ++ +FFA11 +Filter FIFO assignment for filter + 11 +11 +1 ++ +FFA12 +Filter FIFO assignment for filter + 12 +12 +1 ++ +FFA13 +Filter FIFO assignment for filter + 13 +13 +1 ++ +FFA14 +Filter FIFO assignment for filter + 14 +14 +1 ++ +FFA15 +Filter FIFO assignment for filter + 15 +15 +1 ++ +FFA16 +Filter FIFO assignment for filter + 16 +16 +1 ++ +FFA17 +Filter FIFO assignment for filter + 17 +17 +1 ++ +FFA18 +Filter FIFO assignment for filter + 18 +18 +1 ++ +FFA19 +Filter FIFO assignment for filter + 19 +19 +1 ++ +FFA20 +Filter FIFO assignment for filter + 20 +20 +1 ++ +FFA21 +Filter FIFO assignment for filter + 21 +21 +1 ++ +FFA22 +Filter FIFO assignment for filter + 22 +22 +1 ++ +FFA23 +Filter FIFO assignment for filter + 23 +23 +1 ++ +FFA24 +Filter FIFO assignment for filter + 24 +24 +1 ++ +FFA25 +Filter FIFO assignment for filter + 25 +25 +1 ++ +FFA26 +Filter FIFO assignment for filter + 26 +26 +1 ++ +FFA27 +Filter FIFO assignment for filter + 27 +27 +1 ++ +FA1R +FA1R +filter activation register +0x21C +0x20 +read-write +0x00000000 ++ ++ +FACT0 +Filter active +0 +1 ++ +FACT1 +Filter active +1 +1 ++ +FACT2 +Filter active +2 +1 ++ +FACT3 +Filter active +3 +1 ++ +FACT4 +Filter active +4 +1 ++ +FACT5 +Filter active +5 +1 ++ +FACT6 +Filter active +6 +1 ++ +FACT7 +Filter active +7 +1 ++ +FACT8 +Filter active +8 +1 ++ +FACT9 +Filter active +9 +1 ++ +FACT10 +Filter active +10 +1 ++ +FACT11 +Filter active +11 +1 ++ +FACT12 +Filter active +12 +1 ++ +FACT13 +Filter active +13 +1 ++ +FACT14 +Filter active +14 +1 ++ +FACT15 +Filter active +15 +1 ++ +FACT16 +Filter active +16 +1 ++ +FACT17 +Filter active +17 +1 ++ +FACT18 +Filter active +18 +1 ++ +FACT19 +Filter active +19 +1 ++ +FACT20 +Filter active +20 +1 ++ +FACT21 +Filter active +21 +1 ++ +FACT22 +Filter active +22 +1 ++ +FACT23 +Filter active +23 +1 ++ +FACT24 +Filter active +24 +1 ++ +FACT25 +Filter active +25 +1 ++ +FACT26 +Filter active +26 +1 ++ +FACT27 +Filter active +27 +1 ++ +F0R1 +F0R1 +Filter bank 0 register 1 +0x240 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F0R2 +F0R2 +Filter bank 0 register 2 +0x244 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F1R1 +F1R1 +Filter bank 1 register 1 +0x248 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F1R2 +F1R2 +Filter bank 1 register 2 +0x24C +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F2R1 +F2R1 +Filter bank 2 register 1 +0x250 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F2R2 +F2R2 +Filter bank 2 register 2 +0x254 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F3R1 +F3R1 +Filter bank 3 register 1 +0x258 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F3R2 +F3R2 +Filter bank 3 register 2 +0x25C +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F4R1 +F4R1 +Filter bank 4 register 1 +0x260 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F4R2 +F4R2 +Filter bank 4 register 2 +0x264 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F5R1 +F5R1 +Filter bank 5 register 1 +0x268 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F5R2 +F5R2 +Filter bank 5 register 2 +0x26C +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F6R1 +F6R1 +Filter bank 6 register 1 +0x270 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F6R2 +F6R2 +Filter bank 6 register 2 +0x274 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F7R1 +F7R1 +Filter bank 7 register 1 +0x278 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F7R2 +F7R2 +Filter bank 7 register 2 +0x27C +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F8R1 +F8R1 +Filter bank 8 register 1 +0x280 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F8R2 +F8R2 +Filter bank 8 register 2 +0x284 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F9R1 +F9R1 +Filter bank 9 register 1 +0x288 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F9R2 +F9R2 +Filter bank 9 register 2 +0x28C +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F10R1 +F10R1 +Filter bank 10 register 1 +0x290 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F10R2 +F10R2 +Filter bank 10 register 2 +0x294 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F11R1 +F11R1 +Filter bank 11 register 1 +0x298 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F11R2 +F11R2 +Filter bank 11 register 2 +0x29C +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F12R1 +F12R1 +Filter bank 4 register 1 +0x2A0 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F12R2 +F12R2 +Filter bank 12 register 2 +0x2A4 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F13R1 +F13R1 +Filter bank 13 register 1 +0x2A8 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F13R2 +F13R2 +Filter bank 13 register 2 +0x2AC +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F14R1 +F14R1 +Filter bank 14 register 1 +0x2B0 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F14R2 +F14R2 +Filter bank 14 register 2 +0x2B4 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F15R1 +F15R1 +Filter bank 15 register 1 +0x2B8 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F15R2 +F15R2 +Filter bank 15 register 2 +0x2BC +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F16R1 +F16R1 +Filter bank 16 register 1 +0x2C0 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F16R2 +F16R2 +Filter bank 16 register 2 +0x2C4 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F17R1 +F17R1 +Filter bank 17 register 1 +0x2C8 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F17R2 +F17R2 +Filter bank 17 register 2 +0x2CC +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F18R1 +F18R1 +Filter bank 18 register 1 +0x2D0 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F18R2 +F18R2 +Filter bank 18 register 2 +0x2D4 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F19R1 +F19R1 +Filter bank 19 register 1 +0x2D8 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F19R2 +F19R2 +Filter bank 19 register 2 +0x2DC +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F20R1 +F20R1 +Filter bank 20 register 1 +0x2E0 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F20R2 +F20R2 +Filter bank 20 register 2 +0x2E4 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F21R1 +F21R1 +Filter bank 21 register 1 +0x2E8 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F21R2 +F21R2 +Filter bank 21 register 2 +0x2EC +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F22R1 +F22R1 +Filter bank 22 register 1 +0x2F0 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F22R2 +F22R2 +Filter bank 22 register 2 +0x2F4 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F23R1 +F23R1 +Filter bank 23 register 1 +0x2F8 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F23R2 +F23R2 +Filter bank 23 register 2 +0x2FC +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F24R1 +F24R1 +Filter bank 24 register 1 +0x300 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F24R2 +F24R2 +Filter bank 24 register 2 +0x304 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F25R1 +F25R1 +Filter bank 25 register 1 +0x308 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F25R2 +F25R2 +Filter bank 25 register 2 +0x30C +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F26R1 +F26R1 +Filter bank 26 register 1 +0x310 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F26R2 +F26R2 +Filter bank 26 register 2 +0x314 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F27R1 +F27R1 +Filter bank 27 register 1 +0x318 +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +F27R2 +F27R2 +Filter bank 27 register 2 +0x31C +0x20 +read-write +0x00000000 ++ ++ +FB0 +Filter bits +0 +1 ++ +FB1 +Filter bits +1 +1 ++ +FB2 +Filter bits +2 +1 ++ +FB3 +Filter bits +3 +1 ++ +FB4 +Filter bits +4 +1 ++ +FB5 +Filter bits +5 +1 ++ +FB6 +Filter bits +6 +1 ++ +FB7 +Filter bits +7 +1 ++ +FB8 +Filter bits +8 +1 ++ +FB9 +Filter bits +9 +1 ++ +FB10 +Filter bits +10 +1 ++ +FB11 +Filter bits +11 +1 ++ +FB12 +Filter bits +12 +1 ++ +FB13 +Filter bits +13 +1 ++ +FB14 +Filter bits +14 +1 ++ +FB15 +Filter bits +15 +1 ++ +FB16 +Filter bits +16 +1 ++ +FB17 +Filter bits +17 +1 ++ +FB18 +Filter bits +18 +1 ++ +FB19 +Filter bits +19 +1 ++ +FB20 +Filter bits +20 +1 ++ +FB21 +Filter bits +21 +1 ++ +FB22 +Filter bits +22 +1 ++ +FB23 +Filter bits +23 +1 ++ +FB24 +Filter bits +24 +1 ++ +FB25 +Filter bits +25 +1 ++ +FB26 +Filter bits +26 +1 ++ +FB27 +Filter bits +27 +1 ++ +FB28 +Filter bits +28 +1 ++ +FB29 +Filter bits +29 +1 ++ +FB30 +Filter bits +30 +1 ++ +FB31 +Filter bits +31 +1 ++ +CAN2 +0x40006800 ++ +CAN2_TX +CAN2 TX interrupts +63 ++ +CAN2_RX0 +CAN2 RX0 interrupts +64 ++ +CAN2_RX1 +CAN2 RX1 interrupts +65 ++ +CAN2_SCE +CAN2 SCE interrupt +66 ++ +FLASH +FLASH +FLASH +0x40023C00 ++ +0x0 +0x400 +registers ++ ++ +ACR +ACR +Flash access control register +0x0 +0x20 +0x00000000 ++ ++ +LATENCY +Latency +0 +3 +read-write ++ +PRFTEN +Prefetch enable +8 +1 +read-write ++ +ICEN +Instruction cache enable +9 +1 +read-write ++ +DCEN +Data cache enable +10 +1 +read-write ++ +ICRST +Instruction cache reset +11 +1 +write-only ++ +DCRST +Data cache reset +12 +1 +read-write ++ +KEYR +KEYR +Flash key register +0x4 +0x20 +write-only +0x00000000 ++ ++ +KEY +FPEC key +0 +32 ++ +OPTKEYR +OPTKEYR +Flash option key register +0x8 +0x20 +write-only +0x00000000 ++ ++ +OPTKEY +Option byte key +0 +32 ++ +SR +SR +Status register +0xC +0x20 +0x00000000 ++ ++ +EOP +End of operation +0 +1 +read-write ++ +OPERR +Operation error +1 +1 +read-write ++ +WRPERR +Write protection error +4 +1 +read-write ++ +PGAERR +Programming alignment + error +5 +1 +read-write ++ +PGPERR +Programming parallelism + error +6 +1 +read-write ++ +PGSERR +Programming sequence error +7 +1 +read-write ++ +BSY +Busy +16 +1 +read-only ++ +CR +CR +Control register +0x10 +0x20 +read-write +0x80000000 ++ ++ +PG +Programming +0 +1 ++ +SER +Sector Erase +1 +1 ++ +MER +Mass Erase +2 +1 ++ +SNB +Sector number +3 +4 ++ +PSIZE +Program size +8 +2 ++ +STRT +Start +16 +1 ++ +EOPIE +End of operation interrupt + enable +24 +1 ++ +ERRIE +Error interrupt enable +25 +1 ++ +LOCK +Lock +31 +1 ++ +OPTCR +OPTCR +Flash option control register +0x14 +0x20 +read-write +0x00000014 ++ ++ +OPTLOCK +Option lock +0 +1 ++ +OPTSTRT +Option start +1 +1 ++ +BOR_LEV +BOR reset Level +2 +2 ++ +WDG_SW +WDG_SW User option bytes +5 +1 ++ +nRST_STOP +nRST_STOP User option + bytes +6 +1 ++ +nRST_STDBY +nRST_STDBY User option + bytes +7 +1 ++ +RDP +Read protect +8 +8 ++ +nWRP +Not write protect +16 +12 ++ +EXTI +External interrupt/event + controller +EXTI +0x40013C00 ++ +0x0 +0x400 +registers ++ +TAMP_STAMP +Tamper and TimeStamp interrupts through the + EXTI line +2 ++ +EXTI0 +EXTI Line0 interrupt +6 ++ +EXTI1 +EXTI Line1 interrupt +7 ++ +EXTI2 +EXTI Line2 interrupt +8 ++ +EXTI3 +EXTI Line3 interrupt +9 ++ +EXTI4 +EXTI Line4 interrupt +10 ++ +EXTI9_5 +EXTI Line[9:5] interrupts +23 ++ +EXTI9_5 +EXTI Line[9:5] interrupts +23 ++ +EXTI15_10 +EXTI Line[15:10] interrupts +40 ++ ++ +IMR +IMR +Interrupt mask register + (EXTI_IMR) +0x0 +0x20 +read-write +0x00000000 ++ ++ +MR0 +Interrupt Mask on line 0 +0 +1 ++ +MR1 +Interrupt Mask on line 1 +1 +1 ++ +MR2 +Interrupt Mask on line 2 +2 +1 ++ +MR3 +Interrupt Mask on line 3 +3 +1 ++ +MR4 +Interrupt Mask on line 4 +4 +1 ++ +MR5 +Interrupt Mask on line 5 +5 +1 ++ +MR6 +Interrupt Mask on line 6 +6 +1 ++ +MR7 +Interrupt Mask on line 7 +7 +1 ++ +MR8 +Interrupt Mask on line 8 +8 +1 ++ +MR9 +Interrupt Mask on line 9 +9 +1 ++ +MR10 +Interrupt Mask on line 10 +10 +1 ++ +MR11 +Interrupt Mask on line 11 +11 +1 ++ +MR12 +Interrupt Mask on line 12 +12 +1 ++ +MR13 +Interrupt Mask on line 13 +13 +1 ++ +MR14 +Interrupt Mask on line 14 +14 +1 ++ +MR15 +Interrupt Mask on line 15 +15 +1 ++ +MR16 +Interrupt Mask on line 16 +16 +1 ++ +MR17 +Interrupt Mask on line 17 +17 +1 ++ +MR18 +Interrupt Mask on line 18 +18 +1 ++ +MR19 +Interrupt Mask on line 19 +19 +1 ++ +MR20 +Interrupt Mask on line 20 +20 +1 ++ +MR21 +Interrupt Mask on line 21 +21 +1 ++ +MR22 +Interrupt Mask on line 22 +22 +1 ++ +EMR +EMR +Event mask register (EXTI_EMR) +0x4 +0x20 +read-write +0x00000000 ++ ++ +MR0 +Event Mask on line 0 +0 +1 ++ +MR1 +Event Mask on line 1 +1 +1 ++ +MR2 +Event Mask on line 2 +2 +1 ++ +MR3 +Event Mask on line 3 +3 +1 ++ +MR4 +Event Mask on line 4 +4 +1 ++ +MR5 +Event Mask on line 5 +5 +1 ++ +MR6 +Event Mask on line 6 +6 +1 ++ +MR7 +Event Mask on line 7 +7 +1 ++ +MR8 +Event Mask on line 8 +8 +1 ++ +MR9 +Event Mask on line 9 +9 +1 ++ +MR10 +Event Mask on line 10 +10 +1 ++ +MR11 +Event Mask on line 11 +11 +1 ++ +MR12 +Event Mask on line 12 +12 +1 ++ +MR13 +Event Mask on line 13 +13 +1 ++ +MR14 +Event Mask on line 14 +14 +1 ++ +MR15 +Event Mask on line 15 +15 +1 ++ +MR16 +Event Mask on line 16 +16 +1 ++ +MR17 +Event Mask on line 17 +17 +1 ++ +MR18 +Event Mask on line 18 +18 +1 ++ +MR19 +Event Mask on line 19 +19 +1 ++ +MR20 +Event Mask on line 20 +20 +1 ++ +MR21 +Event Mask on line 21 +21 +1 ++ +MR22 +Event Mask on line 22 +22 +1 ++ +RTSR +RTSR +Rising Trigger selection register + (EXTI_RTSR) +0x8 +0x20 +read-write +0x00000000 ++ ++ +TR0 +Rising trigger event configuration of + line 0 +0 +1 ++ +TR1 +Rising trigger event configuration of + line 1 +1 +1 ++ +TR2 +Rising trigger event configuration of + line 2 +2 +1 ++ +TR3 +Rising trigger event configuration of + line 3 +3 +1 ++ +TR4 +Rising trigger event configuration of + line 4 +4 +1 ++ +TR5 +Rising trigger event configuration of + line 5 +5 +1 ++ +TR6 +Rising trigger event configuration of + line 6 +6 +1 ++ +TR7 +Rising trigger event configuration of + line 7 +7 +1 ++ +TR8 +Rising trigger event configuration of + line 8 +8 +1 ++ +TR9 +Rising trigger event configuration of + line 9 +9 +1 ++ +TR10 +Rising trigger event configuration of + line 10 +10 +1 ++ +TR11 +Rising trigger event configuration of + line 11 +11 +1 ++ +TR12 +Rising trigger event configuration of + line 12 +12 +1 ++ +TR13 +Rising trigger event configuration of + line 13 +13 +1 ++ +TR14 +Rising trigger event configuration of + line 14 +14 +1 ++ +TR15 +Rising trigger event configuration of + line 15 +15 +1 ++ +TR16 +Rising trigger event configuration of + line 16 +16 +1 ++ +TR17 +Rising trigger event configuration of + line 17 +17 +1 ++ +TR18 +Rising trigger event configuration of + line 18 +18 +1 ++ +TR19 +Rising trigger event configuration of + line 19 +19 +1 ++ +TR20 +Rising trigger event configuration of + line 20 +20 +1 ++ +TR21 +Rising trigger event configuration of + line 21 +21 +1 ++ +TR22 +Rising trigger event configuration of + line 22 +22 +1 ++ +FTSR +FTSR +Falling Trigger selection register + (EXTI_FTSR) +0xC +0x20 +read-write +0x00000000 ++ ++ +TR0 +Falling trigger event configuration of + line 0 +0 +1 ++ +TR1 +Falling trigger event configuration of + line 1 +1 +1 ++ +TR2 +Falling trigger event configuration of + line 2 +2 +1 ++ +TR3 +Falling trigger event configuration of + line 3 +3 +1 ++ +TR4 +Falling trigger event configuration of + line 4 +4 +1 ++ +TR5 +Falling trigger event configuration of + line 5 +5 +1 ++ +TR6 +Falling trigger event configuration of + line 6 +6 +1 ++ +TR7 +Falling trigger event configuration of + line 7 +7 +1 ++ +TR8 +Falling trigger event configuration of + line 8 +8 +1 ++ +TR9 +Falling trigger event configuration of + line 9 +9 +1 ++ +TR10 +Falling trigger event configuration of + line 10 +10 +1 ++ +TR11 +Falling trigger event configuration of + line 11 +11 +1 ++ +TR12 +Falling trigger event configuration of + line 12 +12 +1 ++ +TR13 +Falling trigger event configuration of + line 13 +13 +1 ++ +TR14 +Falling trigger event configuration of + line 14 +14 +1 ++ +TR15 +Falling trigger event configuration of + line 15 +15 +1 ++ +TR16 +Falling trigger event configuration of + line 16 +16 +1 ++ +TR17 +Falling trigger event configuration of + line 17 +17 +1 ++ +TR18 +Falling trigger event configuration of + line 18 +18 +1 ++ +TR19 +Falling trigger event configuration of + line 19 +19 +1 ++ +TR20 +Falling trigger event configuration of + line 20 +20 +1 ++ +TR21 +Falling trigger event configuration of + line 21 +21 +1 ++ +TR22 +Falling trigger event configuration of + line 22 +22 +1 ++ +SWIER +SWIER +Software interrupt event register + (EXTI_SWIER) +0x10 +0x20 +read-write +0x00000000 ++ ++ +SWIER0 +Software Interrupt on line + 0 +0 +1 ++ +SWIER1 +Software Interrupt on line + 1 +1 +1 ++ +SWIER2 +Software Interrupt on line + 2 +2 +1 ++ +SWIER3 +Software Interrupt on line + 3 +3 +1 ++ +SWIER4 +Software Interrupt on line + 4 +4 +1 ++ +SWIER5 +Software Interrupt on line + 5 +5 +1 ++ +SWIER6 +Software Interrupt on line + 6 +6 +1 ++ +SWIER7 +Software Interrupt on line + 7 +7 +1 ++ +SWIER8 +Software Interrupt on line + 8 +8 +1 ++ +SWIER9 +Software Interrupt on line + 9 +9 +1 ++ +SWIER10 +Software Interrupt on line + 10 +10 +1 ++ +SWIER11 +Software Interrupt on line + 11 +11 +1 ++ +SWIER12 +Software Interrupt on line + 12 +12 +1 ++ +SWIER13 +Software Interrupt on line + 13 +13 +1 ++ +SWIER14 +Software Interrupt on line + 14 +14 +1 ++ +SWIER15 +Software Interrupt on line + 15 +15 +1 ++ +SWIER16 +Software Interrupt on line + 16 +16 +1 ++ +SWIER17 +Software Interrupt on line + 17 +17 +1 ++ +SWIER18 +Software Interrupt on line + 18 +18 +1 ++ +SWIER19 +Software Interrupt on line + 19 +19 +1 ++ +SWIER20 +Software Interrupt on line + 20 +20 +1 ++ +SWIER21 +Software Interrupt on line + 21 +21 +1 ++ +SWIER22 +Software Interrupt on line + 22 +22 +1 ++ +PR +PR +Pending register (EXTI_PR) +0x14 +0x20 +read-write +0x00000000 ++ ++ +PR0 +Pending bit 0 +0 +1 ++ +PR1 +Pending bit 1 +1 +1 ++ +PR2 +Pending bit 2 +2 +1 ++ +PR3 +Pending bit 3 +3 +1 ++ +PR4 +Pending bit 4 +4 +1 ++ +PR5 +Pending bit 5 +5 +1 ++ +PR6 +Pending bit 6 +6 +1 ++ +PR7 +Pending bit 7 +7 +1 ++ +PR8 +Pending bit 8 +8 +1 ++ +PR9 +Pending bit 9 +9 +1 ++ +PR10 +Pending bit 10 +10 +1 ++ +PR11 +Pending bit 11 +11 +1 ++ +PR12 +Pending bit 12 +12 +1 ++ +PR13 +Pending bit 13 +13 +1 ++ +PR14 +Pending bit 14 +14 +1 ++ +PR15 +Pending bit 15 +15 +1 ++ +PR16 +Pending bit 16 +16 +1 ++ +PR17 +Pending bit 17 +17 +1 ++ +PR18 +Pending bit 18 +18 +1 ++ +PR19 +Pending bit 19 +19 +1 ++ +PR20 +Pending bit 20 +20 +1 ++ +PR21 +Pending bit 21 +21 +1 ++ +PR22 +Pending bit 22 +22 +1 ++ +OTG_HS_GLOBAL +USB on the go high speed +USB_OTG_HS +0x40040000 ++ +0x0 +0x131 +registers ++ +OTG_HS_EP1_OUT +USB On The Go HS End Point 1 Out global + interrupt +74 ++ +OTG_HS_EP1_IN +USB On The Go HS End Point 1 In global + interrupt +75 ++ +OTG_HS_WKUP +USB On The Go HS Wakeup through EXTI + interrupt +76 ++ +OTG_HS +USB On The Go HS global + interrupt +77 ++ ++ +OTG_HS_GOTGCTL +OTG_HS_GOTGCTL +OTG_HS control and status + register +0x0 +32 +0x00000800 ++ ++ +SRQSCS +Session request success +0 +1 +read-only ++ +SRQ +Session request +1 +1 +read-write ++ +HNGSCS +Host negotiation success +8 +1 +read-only ++ +HNPRQ +HNP request +9 +1 +read-write ++ +HSHNPEN +Host set HNP enable +10 +1 +read-write ++ +DHNPEN +Device HNP enabled +11 +1 +read-write ++ +CIDSTS +Connector ID status +16 +1 +read-only ++ +DBCT +Long/short debounce time +17 +1 +read-only ++ +ASVLD +A-session valid +18 +1 +read-only ++ +BSVLD +B-session valid +19 +1 +read-only ++ +OTG_HS_GOTGINT +OTG_HS_GOTGINT +OTG_HS interrupt register +0x4 +32 +read-write +0x0 ++ ++ +SEDET +Session end detected +2 +1 ++ +SRSSCHG +Session request success status + change +8 +1 ++ +HNSSCHG +Host negotiation success status + change +9 +1 ++ +HNGDET +Host negotiation detected +17 +1 ++ +ADTOCHG +A-device timeout change +18 +1 ++ +DBCDNE +Debounce done +19 +1 ++ +OTG_HS_GAHBCFG +OTG_HS_GAHBCFG +OTG_HS AHB configuration + register +0x8 +32 +read-write +0x0 ++ ++ +GINT +Global interrupt mask +0 +1 ++ +HBSTLEN +Burst length/type +1 +4 ++ +DMAEN +DMA enable +5 +1 ++ +TXFELVL +TxFIFO empty level +7 +1 ++ +PTXFELVL +Periodic TxFIFO empty + level +8 +1 ++ +OTG_HS_GUSBCFG +OTG_HS_GUSBCFG +OTG_HS USB configuration + register +0xC +32 +0x00000A00 ++ ++ +TOCAL +FS timeout calibration +0 +3 +read-write ++ +PHYSEL +USB 2.0 high-speed ULPI PHY or USB 1.1 + full-speed serial transceiver select +6 +1 +write-only ++ +SRPCAP +SRP-capable +8 +1 +read-write ++ +HNPCAP +HNP-capable +9 +1 +read-write ++ +TRDT +USB turnaround time +10 +4 +read-write ++ +PHYLPCS +PHY Low-power clock select +15 +1 +read-write ++ +ULPIFSLS +ULPI FS/LS select +17 +1 +read-write ++ +ULPIAR +ULPI Auto-resume +18 +1 +read-write ++ +ULPICSM +ULPI Clock SuspendM +19 +1 +read-write ++ +ULPIEVBUSD +ULPI External VBUS Drive +20 +1 +read-write ++ +ULPIEVBUSI +ULPI external VBUS + indicator +21 +1 +read-write ++ +TSDPS +TermSel DLine pulsing + selection +22 +1 +read-write ++ +PCCI +Indicator complement +23 +1 +read-write ++ +PTCI +Indicator pass through +24 +1 +read-write ++ +ULPIIPD +ULPI interface protect + disable +25 +1 +read-write ++ +FHMOD +Forced host mode +29 +1 +read-write ++ +FDMOD +Forced peripheral mode +30 +1 +read-write ++ +CTXPKT +Corrupt Tx packet +31 +1 +read-write ++ +OTG_HS_GRSTCTL +OTG_HS_GRSTCTL +OTG_HS reset register +0x10 +32 +0x20000000 ++ ++ +CSRST +Core soft reset +0 +1 +read-write ++ +HSRST +HCLK soft reset +1 +1 +read-write ++ +FCRST +Host frame counter reset +2 +1 +read-write ++ +RXFFLSH +RxFIFO flush +4 +1 +read-write ++ +TXFFLSH +TxFIFO flush +5 +1 +read-write ++ +TXFNUM +TxFIFO number +6 +5 +read-write ++ +DMAREQ +DMA request signal +30 +1 +read-only ++ +AHBIDL +AHB master idle +31 +1 +read-only ++ +OTG_HS_GINTSTS +OTG_HS_GINTSTS +OTG_HS core interrupt register +0x14 +32 +0x04000020 ++ ++ +CMOD +Current mode of operation +0 +1 +read-only ++ +MMIS +Mode mismatch interrupt +1 +1 +read-write ++ +OTGINT +OTG interrupt +2 +1 +read-only ++ +SOF +Start of frame +3 +1 +read-write ++ +RXFLVL +RxFIFO nonempty +4 +1 +read-only ++ +NPTXFE +Nonperiodic TxFIFO empty +5 +1 +read-only ++ +GINAKEFF +Global IN nonperiodic NAK + effective +6 +1 +read-only ++ +BOUTNAKEFF +Global OUT NAK effective +7 +1 +read-only ++ +ESUSP +Early suspend +10 +1 +read-write ++ +USBSUSP +USB suspend +11 +1 +read-write ++ +USBRST +USB reset +12 +1 +read-write ++ +ENUMDNE +Enumeration done +13 +1 +read-write ++ +ISOODRP +Isochronous OUT packet dropped + interrupt +14 +1 +read-write ++ +EOPF +End of periodic frame + interrupt +15 +1 +read-write ++ +IEPINT +IN endpoint interrupt +18 +1 +read-only ++ +OEPINT +OUT endpoint interrupt +19 +1 +read-only ++ +IISOIXFR +Incomplete isochronous IN + transfer +20 +1 +read-write ++ +PXFR_INCOMPISOOUT +Incomplete periodic + transfer +21 +1 +read-write ++ +DATAFSUSP +Data fetch suspended +22 +1 +read-write ++ +HPRTINT +Host port interrupt +24 +1 +read-only ++ +HCINT +Host channels interrupt +25 +1 +read-only ++ +PTXFE +Periodic TxFIFO empty +26 +1 +read-only ++ +CIDSCHG +Connector ID status change +28 +1 +read-write ++ +DISCINT +Disconnect detected + interrupt +29 +1 +read-write ++ +SRQINT +Session request/new session detected + interrupt +30 +1 +read-write ++ +WKUINT +Resume/remote wakeup detected + interrupt +31 +1 +read-write ++ +OTG_HS_GINTMSK +OTG_HS_GINTMSK +OTG_HS interrupt mask register +0x18 +32 +0x0 ++ ++ +MMISM +Mode mismatch interrupt + mask +1 +1 +read-write ++ +OTGINT +OTG interrupt mask +2 +1 +read-write ++ +SOFM +Start of frame mask +3 +1 +read-write ++ +RXFLVLM +Receive FIFO nonempty mask +4 +1 +read-write ++ +NPTXFEM +Nonperiodic TxFIFO empty + mask +5 +1 +read-write ++ +GINAKEFFM +Global nonperiodic IN NAK effective + mask +6 +1 +read-write ++ +GONAKEFFM +Global OUT NAK effective + mask +7 +1 +read-write ++ +ESUSPM +Early suspend mask +10 +1 +read-write ++ +USBSUSPM +USB suspend mask +11 +1 +read-write ++ +USBRST +USB reset mask +12 +1 +read-write ++ +ENUMDNEM +Enumeration done mask +13 +1 +read-write ++ +ISOODRPM +Isochronous OUT packet dropped interrupt + mask +14 +1 +read-write ++ +EOPFM +End of periodic frame interrupt + mask +15 +1 +read-write ++ +EPMISM +Endpoint mismatch interrupt + mask +17 +1 +read-write ++ +IEPINT +IN endpoints interrupt + mask +18 +1 +read-write ++ +OEPINT +OUT endpoints interrupt + mask +19 +1 +read-write ++ +IISOIXFRM +Incomplete isochronous IN transfer + mask +20 +1 +read-write ++ +PXFRM_IISOOXFRM +Incomplete periodic transfer + mask +21 +1 +read-write ++ +FSUSPM +Data fetch suspended mask +22 +1 +read-write ++ +PRTIM +Host port interrupt mask +24 +1 +read-only ++ +HCIM +Host channels interrupt + mask +25 +1 +read-write ++ +PTXFEM +Periodic TxFIFO empty mask +26 +1 +read-write ++ +CIDSCHGM +Connector ID status change + mask +28 +1 +read-write ++ +DISCINT +Disconnect detected interrupt + mask +29 +1 +read-write ++ +SRQIM +Session request/new session detected + interrupt mask +30 +1 +read-write ++ +WUIM +Resume/remote wakeup detected interrupt + mask +31 +1 +read-write ++ +OTG_HS_GRXSTSR_Host +OTG_HS_GRXSTSR_Host +OTG_HS Receive status debug read register + (host mode) +0x1C +32 +read-only +0x0 ++ ++ +CHNUM +Channel number +0 +4 ++ +BCNT +Byte count +4 +11 ++ +DPID +Data PID +15 +2 ++ +PKTSTS +Packet status +17 +4 ++ +OTG_HS_GRXSTSP_Host +OTG_HS_GRXSTSP_Host +OTG_HS status read and pop register (host + mode) +0x20 +32 +read-only +0x0 ++ ++ +CHNUM +Channel number +0 +4 ++ +BCNT +Byte count +4 +11 ++ +DPID +Data PID +15 +2 ++ +PKTSTS +Packet status +17 +4 ++ +OTG_HS_GRXFSIZ +OTG_HS_GRXFSIZ +OTG_HS Receive FIFO size + register +0x24 +32 +read-write +0x00000200 ++ ++ +RXFD +RxFIFO depth +0 +16 ++ +OTG_HS_GNPTXFSIZ_Host +OTG_HS_GNPTXFSIZ_Host +OTG_HS nonperiodic transmit FIFO size + register (host mode) +0x28 +32 +read-write +0x00000200 ++ ++ +NPTXFSA +Nonperiodic transmit RAM start + address +0 +16 ++ +NPTXFD +Nonperiodic TxFIFO depth +16 +16 ++ +OTG_HS_TX0FSIZ_Peripheral +OTG_HS_TX0FSIZ_Peripheral +Endpoint 0 transmit FIFO size (peripheral + mode) +OTG_HS_GNPTXFSIZ_Host +0x28 +32 +read-write +0x00000200 ++ ++ +TX0FSA +Endpoint 0 transmit RAM start + address +0 +16 ++ +TX0FD +Endpoint 0 TxFIFO depth +16 +16 ++ +OTG_HS_GNPTXSTS +OTG_HS_GNPTXSTS +OTG_HS nonperiodic transmit FIFO/queue + status register +0x2C +32 +read-only +0x00080200 ++ ++ +NPTXFSAV +Nonperiodic TxFIFO space + available +0 +16 ++ +NPTQXSAV +Nonperiodic transmit request queue space + available +16 +8 ++ +NPTXQTOP +Top of the nonperiodic transmit request + queue +24 +7 ++ +OTG_HS_GCCFG +OTG_HS_GCCFG +OTG_HS general core configuration + register +0x38 +32 +read-write +0x0 ++ ++ +PWRDWN +Power down +16 +1 ++ +I2CPADEN +Enable I2C bus connection for the + external I2C PHY interface +17 +1 ++ +VBUSASEN +Enable the VBUS sensing + device +18 +1 ++ +VBUSBSEN +Enable the VBUS sensing + device +19 +1 ++ +SOFOUTEN +SOF output enable +20 +1 ++ +NOVBUSSENS +VBUS sensing disable + option +21 +1 ++ +OTG_HS_CID +OTG_HS_CID +OTG_HS core ID register +0x3C +32 +read-write +0x00001200 ++ ++ +PRODUCT_ID +Product ID field +0 +32 ++ +OTG_HS_HPTXFSIZ +OTG_HS_HPTXFSIZ +OTG_HS Host periodic transmit FIFO size + register +0x100 +32 +read-write +0x02000600 ++ ++ +PTXSA +Host periodic TxFIFO start + address +0 +16 ++ +PTXFD +Host periodic TxFIFO depth +16 +16 ++ +OTG_HS_DIEPTXF1 +OTG_HS_DIEPTXF1 +OTG_HS device IN endpoint transmit FIFO size + register +0x104 +32 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFOx transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +OTG_HS_DIEPTXF2 +OTG_HS_DIEPTXF2 +OTG_HS device IN endpoint transmit FIFO size + register +0x108 +32 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFOx transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +OTG_HS_DIEPTXF3 +OTG_HS_DIEPTXF3 +OTG_HS device IN endpoint transmit FIFO size + register +0x11C +32 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFOx transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +OTG_HS_DIEPTXF4 +OTG_HS_DIEPTXF4 +OTG_HS device IN endpoint transmit FIFO size + register +0x120 +32 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFOx transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +OTG_HS_DIEPTXF5 +OTG_HS_DIEPTXF5 +OTG_HS device IN endpoint transmit FIFO size + register +0x124 +32 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFOx transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +OTG_HS_DIEPTXF6 +OTG_HS_DIEPTXF6 +OTG_HS device IN endpoint transmit FIFO size + register +0x128 +32 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFOx transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +OTG_HS_DIEPTXF7 +OTG_HS_DIEPTXF7 +OTG_HS device IN endpoint transmit FIFO size + register +0x12C +32 +read-write +0x02000400 ++ ++ +INEPTXSA +IN endpoint FIFOx transmit RAM start + address +0 +16 ++ +INEPTXFD +IN endpoint TxFIFO depth +16 +16 ++ +OTG_HS_GRXSTSR_Peripheral +OTG_HS_GRXSTSR_Peripheral +OTG_HS Receive status debug read register + (peripheral mode mode) +OTG_HS_GRXSTSR_Host +0x1C +32 +read-only +0x0 ++ ++ +EPNUM +Endpoint number +0 +4 ++ +BCNT +Byte count +4 +11 ++ +DPID +Data PID +15 +2 ++ +PKTSTS +Packet status +17 +4 ++ +FRMNUM +Frame number +21 +4 ++ +OTG_HS_GRXSTSP_Peripheral +OTG_HS_GRXSTSP_Peripheral +OTG_HS status read and pop register + (peripheral mode) +OTG_HS_GRXSTSP_Host +0x20 +32 +read-only +0x0 ++ ++ +EPNUM +Endpoint number +0 +4 ++ +BCNT +Byte count +4 +11 ++ +DPID +Data PID +15 +2 ++ +PKTSTS +Packet status +17 +4 ++ +FRMNUM +Frame number +21 +4 ++ +OTG_HS_HOST +USB on the go high speed +USB_OTG_HS +0x40040400 ++ +0x0 +0x400 +registers ++ ++ +OTG_HS_HCFG +OTG_HS_HCFG +OTG_HS host configuration + register +0x0 +32 +0x0 ++ ++ +FSLSPCS +FS/LS PHY clock select +0 +2 +read-write ++ +FSLSS +FS- and LS-only support +2 +1 +read-only ++ +OTG_HS_HFIR +OTG_HS_HFIR +OTG_HS Host frame interval + register +0x4 +32 +read-write +0x0000EA60 ++ ++ +FRIVL +Frame interval +0 +16 ++ +OTG_HS_HFNUM +OTG_HS_HFNUM +OTG_HS host frame number/frame time + remaining register +0x8 +32 +read-only +0x00003FFF ++ ++ +FRNUM +Frame number +0 +16 ++ +FTREM +Frame time remaining +16 +16 ++ +OTG_HS_HPTXSTS +OTG_HS_HPTXSTS +OTG_HS_Host periodic transmit FIFO/queue + status register +0x10 +32 +0x00080100 ++ ++ +PTXFSAVL +Periodic transmit data FIFO space + available +0 +16 +read-write ++ +PTXQSAV +Periodic transmit request queue space + available +16 +8 +read-only ++ +PTXQTOP +Top of the periodic transmit request + queue +24 +8 +read-only ++ +OTG_HS_HAINT +OTG_HS_HAINT +OTG_HS Host all channels interrupt + register +0x14 +32 +read-only +0x0 ++ ++ +HAINT +Channel interrupts +0 +16 ++ +OTG_HS_HAINTMSK +OTG_HS_HAINTMSK +OTG_HS host all channels interrupt mask + register +0x18 +32 +read-write +0x0 ++ ++ +HAINTM +Channel interrupt mask +0 +16 ++ +OTG_HS_HPRT +OTG_HS_HPRT +OTG_HS host port control and status + register +0x40 +32 +0x0 ++ ++ +PCSTS +Port connect status +0 +1 +read-only ++ +PCDET +Port connect detected +1 +1 +read-write ++ +PENA +Port enable +2 +1 +read-write ++ +PENCHNG +Port enable/disable change +3 +1 +read-write ++ +POCA +Port overcurrent active +4 +1 +read-only ++ +POCCHNG +Port overcurrent change +5 +1 +read-write ++ +PRES +Port resume +6 +1 +read-write ++ +PSUSP +Port suspend +7 +1 +read-write ++ +PRST +Port reset +8 +1 +read-write ++ +PLSTS +Port line status +10 +2 +read-only ++ +PPWR +Port power +12 +1 +read-write ++ +PTCTL +Port test control +13 +4 +read-write ++ +PSPD +Port speed +17 +2 +read-only ++ +OTG_HS_HCCHAR0 +OTG_HS_HCCHAR0 +OTG_HS host channel-0 characteristics + register +0x100 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR1 +OTG_HS_HCCHAR1 +OTG_HS host channel-1 characteristics + register +0x120 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR2 +OTG_HS_HCCHAR2 +OTG_HS host channel-2 characteristics + register +0x140 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR3 +OTG_HS_HCCHAR3 +OTG_HS host channel-3 characteristics + register +0x160 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR4 +OTG_HS_HCCHAR4 +OTG_HS host channel-4 characteristics + register +0x180 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR5 +OTG_HS_HCCHAR5 +OTG_HS host channel-5 characteristics + register +0x1A0 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR6 +OTG_HS_HCCHAR6 +OTG_HS host channel-6 characteristics + register +0x1C0 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR7 +OTG_HS_HCCHAR7 +OTG_HS host channel-7 characteristics + register +0x1E0 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR8 +OTG_HS_HCCHAR8 +OTG_HS host channel-8 characteristics + register +0x200 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR9 +OTG_HS_HCCHAR9 +OTG_HS host channel-9 characteristics + register +0x220 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR10 +OTG_HS_HCCHAR10 +OTG_HS host channel-10 characteristics + register +0x240 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCCHAR11 +OTG_HS_HCCHAR11 +OTG_HS host channel-11 characteristics + register +0x260 +32 +read-write +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 ++ +EPNUM +Endpoint number +11 +4 ++ +EPDIR +Endpoint direction +15 +1 ++ +LSDEV +Low-speed device +17 +1 ++ +EPTYP +Endpoint type +18 +2 ++ +MC +Multi Count (MC) / Error Count + (EC) +20 +2 ++ +DAD +Device address +22 +7 ++ +ODDFRM +Odd frame +29 +1 ++ +CHDIS +Channel disable +30 +1 ++ +CHENA +Channel enable +31 +1 ++ +OTG_HS_HCSPLT0 +OTG_HS_HCSPLT0 +OTG_HS host channel-0 split control + register +0x104 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT1 +OTG_HS_HCSPLT1 +OTG_HS host channel-1 split control + register +0x124 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT2 +OTG_HS_HCSPLT2 +OTG_HS host channel-2 split control + register +0x144 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT3 +OTG_HS_HCSPLT3 +OTG_HS host channel-3 split control + register +0x164 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT4 +OTG_HS_HCSPLT4 +OTG_HS host channel-4 split control + register +0x184 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT5 +OTG_HS_HCSPLT5 +OTG_HS host channel-5 split control + register +0x1A4 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT6 +OTG_HS_HCSPLT6 +OTG_HS host channel-6 split control + register +0x1C4 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT7 +OTG_HS_HCSPLT7 +OTG_HS host channel-7 split control + register +0x1E4 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT8 +OTG_HS_HCSPLT8 +OTG_HS host channel-8 split control + register +0x204 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT9 +OTG_HS_HCSPLT9 +OTG_HS host channel-9 split control + register +0x224 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT10 +OTG_HS_HCSPLT10 +OTG_HS host channel-10 split control + register +0x244 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCSPLT11 +OTG_HS_HCSPLT11 +OTG_HS host channel-11 split control + register +0x264 +32 +read-write +0x0 ++ ++ +PRTADDR +Port address +0 +7 ++ +HUBADDR +Hub address +7 +7 ++ +XACTPOS +XACTPOS +14 +2 ++ +COMPLSPLT +Do complete split +16 +1 ++ +SPLITEN +Split enable +31 +1 ++ +OTG_HS_HCINT0 +OTG_HS_HCINT0 +OTG_HS host channel-11 interrupt + register +0x108 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT1 +OTG_HS_HCINT1 +OTG_HS host channel-1 interrupt + register +0x128 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT2 +OTG_HS_HCINT2 +OTG_HS host channel-2 interrupt + register +0x148 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT3 +OTG_HS_HCINT3 +OTG_HS host channel-3 interrupt + register +0x168 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT4 +OTG_HS_HCINT4 +OTG_HS host channel-4 interrupt + register +0x188 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT5 +OTG_HS_HCINT5 +OTG_HS host channel-5 interrupt + register +0x1A8 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT6 +OTG_HS_HCINT6 +OTG_HS host channel-6 interrupt + register +0x1C8 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT7 +OTG_HS_HCINT7 +OTG_HS host channel-7 interrupt + register +0x1E8 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT8 +OTG_HS_HCINT8 +OTG_HS host channel-8 interrupt + register +0x208 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT9 +OTG_HS_HCINT9 +OTG_HS host channel-9 interrupt + register +0x228 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT10 +OTG_HS_HCINT10 +OTG_HS host channel-10 interrupt + register +0x248 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINT11 +OTG_HS_HCINT11 +OTG_HS host channel-11 interrupt + register +0x268 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed +0 +1 ++ +CHH +Channel halted +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALL +STALL response received + interrupt +3 +1 ++ +NAK +NAK response received + interrupt +4 +1 ++ +ACK +ACK response received/transmitted + interrupt +5 +1 ++ +NYET +Response received + interrupt +6 +1 ++ +TXERR +Transaction error +7 +1 ++ +BBERR +Babble error +8 +1 ++ +FRMOR +Frame overrun +9 +1 ++ +DTERR +Data toggle error +10 +1 ++ +OTG_HS_HCINTMSK0 +OTG_HS_HCINTMSK0 +OTG_HS host channel-11 interrupt mask + register +0x10C +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK1 +OTG_HS_HCINTMSK1 +OTG_HS host channel-1 interrupt mask + register +0x12C +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK2 +OTG_HS_HCINTMSK2 +OTG_HS host channel-2 interrupt mask + register +0x14C +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK3 +OTG_HS_HCINTMSK3 +OTG_HS host channel-3 interrupt mask + register +0x16C +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK4 +OTG_HS_HCINTMSK4 +OTG_HS host channel-4 interrupt mask + register +0x18C +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK5 +OTG_HS_HCINTMSK5 +OTG_HS host channel-5 interrupt mask + register +0x1AC +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK6 +OTG_HS_HCINTMSK6 +OTG_HS host channel-6 interrupt mask + register +0x1CC +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK7 +OTG_HS_HCINTMSK7 +OTG_HS host channel-7 interrupt mask + register +0x1EC +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK8 +OTG_HS_HCINTMSK8 +OTG_HS host channel-8 interrupt mask + register +0x20C +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK9 +OTG_HS_HCINTMSK9 +OTG_HS host channel-9 interrupt mask + register +0x22C +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK10 +OTG_HS_HCINTMSK10 +OTG_HS host channel-10 interrupt mask + register +0x24C +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCINTMSK11 +OTG_HS_HCINTMSK11 +OTG_HS host channel-11 interrupt mask + register +0x26C +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed mask +0 +1 ++ +CHHM +Channel halted mask +1 +1 ++ +AHBERR +AHB error +2 +1 ++ +STALLM +STALL response received interrupt + mask +3 +1 ++ +NAKM +NAK response received interrupt + mask +4 +1 ++ +ACKM +ACK response received/transmitted + interrupt mask +5 +1 ++ +NYET +response received interrupt + mask +6 +1 ++ +TXERRM +Transaction error mask +7 +1 ++ +BBERRM +Babble error mask +8 +1 ++ +FRMORM +Frame overrun mask +9 +1 ++ +DTERRM +Data toggle error mask +10 +1 ++ +OTG_HS_HCTSIZ0 +OTG_HS_HCTSIZ0 +OTG_HS host channel-11 transfer size + register +0x110 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ1 +OTG_HS_HCTSIZ1 +OTG_HS host channel-1 transfer size + register +0x130 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ2 +OTG_HS_HCTSIZ2 +OTG_HS host channel-2 transfer size + register +0x150 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ3 +OTG_HS_HCTSIZ3 +OTG_HS host channel-3 transfer size + register +0x170 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ4 +OTG_HS_HCTSIZ4 +OTG_HS host channel-4 transfer size + register +0x190 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ5 +OTG_HS_HCTSIZ5 +OTG_HS host channel-5 transfer size + register +0x1B0 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ6 +OTG_HS_HCTSIZ6 +OTG_HS host channel-6 transfer size + register +0x1D0 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ7 +OTG_HS_HCTSIZ7 +OTG_HS host channel-7 transfer size + register +0x1F0 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ8 +OTG_HS_HCTSIZ8 +OTG_HS host channel-8 transfer size + register +0x210 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ9 +OTG_HS_HCTSIZ9 +OTG_HS host channel-9 transfer size + register +0x230 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ10 +OTG_HS_HCTSIZ10 +OTG_HS host channel-10 transfer size + register +0x250 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCTSIZ11 +OTG_HS_HCTSIZ11 +OTG_HS host channel-11 transfer size + register +0x270 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +DPID +Data PID +29 +2 ++ +OTG_HS_HCDMA0 +OTG_HS_HCDMA0 +OTG_HS host channel-0 DMA address + register +0x114 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA1 +OTG_HS_HCDMA1 +OTG_HS host channel-1 DMA address + register +0x134 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA2 +OTG_HS_HCDMA2 +OTG_HS host channel-2 DMA address + register +0x154 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA3 +OTG_HS_HCDMA3 +OTG_HS host channel-3 DMA address + register +0x174 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA4 +OTG_HS_HCDMA4 +OTG_HS host channel-4 DMA address + register +0x194 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA5 +OTG_HS_HCDMA5 +OTG_HS host channel-5 DMA address + register +0x1B4 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA6 +OTG_HS_HCDMA6 +OTG_HS host channel-6 DMA address + register +0x1D4 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA7 +OTG_HS_HCDMA7 +OTG_HS host channel-7 DMA address + register +0x1F4 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA8 +OTG_HS_HCDMA8 +OTG_HS host channel-8 DMA address + register +0x214 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA9 +OTG_HS_HCDMA9 +OTG_HS host channel-9 DMA address + register +0x234 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA10 +OTG_HS_HCDMA10 +OTG_HS host channel-10 DMA address + register +0x254 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_HCDMA11 +OTG_HS_HCDMA11 +OTG_HS host channel-11 DMA address + register +0x274 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_DEVICE +USB on the go high speed +USB_OTG_HS +0x40040800 ++ +0x0 +0x400 +registers ++ ++ +OTG_HS_DCFG +OTG_HS_DCFG +OTG_HS device configuration + register +0x0 +32 +read-write +0x02200000 ++ ++ +DSPD +Device speed +0 +2 ++ +NZLSOHSK +Nonzero-length status OUT + handshake +2 +1 ++ +DAD +Device address +4 +7 ++ +PFIVL +Periodic (micro)frame + interval +11 +2 ++ +PERSCHIVL +Periodic scheduling + interval +24 +2 ++ +OTG_HS_DCTL +OTG_HS_DCTL +OTG_HS device control register +0x4 +32 +0x0 ++ ++ +RWUSIG +Remote wakeup signaling +0 +1 +read-write ++ +SDIS +Soft disconnect +1 +1 +read-write ++ +GINSTS +Global IN NAK status +2 +1 +read-only ++ +GONSTS +Global OUT NAK status +3 +1 +read-only ++ +TCTL +Test control +4 +3 +read-write ++ +SGINAK +Set global IN NAK +7 +1 +write-only ++ +CGINAK +Clear global IN NAK +8 +1 +write-only ++ +SGONAK +Set global OUT NAK +9 +1 +write-only ++ +CGONAK +Clear global OUT NAK +10 +1 +write-only ++ +POPRGDNE +Power-on programming done +11 +1 +read-write ++ +OTG_HS_DSTS +OTG_HS_DSTS +OTG_HS device status register +0x8 +32 +read-only +0x00000010 ++ ++ +SUSPSTS +Suspend status +0 +1 ++ +ENUMSPD +Enumerated speed +1 +2 ++ +EERR +Erratic error +3 +1 ++ +FNSOF +Frame number of the received + SOF +8 +14 ++ +OTG_HS_DIEPMSK +OTG_HS_DIEPMSK +OTG_HS device IN endpoint common interrupt + mask register +0x10 +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed interrupt + mask +0 +1 ++ +EPDM +Endpoint disabled interrupt + mask +1 +1 ++ +TOM +Timeout condition mask (nonisochronous + endpoints) +3 +1 ++ +ITTXFEMSK +IN token received when TxFIFO empty + mask +4 +1 ++ +INEPNMM +IN token received with EP mismatch + mask +5 +1 ++ +INEPNEM +IN endpoint NAK effective + mask +6 +1 ++ +TXFURM +FIFO underrun mask +8 +1 ++ +BIM +BNA interrupt mask +9 +1 ++ +OTG_HS_DOEPMSK +OTG_HS_DOEPMSK +OTG_HS device OUT endpoint common interrupt + mask register +0x14 +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed interrupt + mask +0 +1 ++ +EPDM +Endpoint disabled interrupt + mask +1 +1 ++ +STUPM +SETUP phase done mask +3 +1 ++ +OTEPDM +OUT token received when endpoint + disabled mask +4 +1 ++ +B2BSTUP +Back-to-back SETUP packets received + mask +6 +1 ++ +OPEM +OUT packet error mask +8 +1 ++ +BOIM +BNA interrupt mask +9 +1 ++ +OTG_HS_DAINT +OTG_HS_DAINT +OTG_HS device all endpoints interrupt + register +0x18 +32 +read-only +0x0 ++ ++ +IEPINT +IN endpoint interrupt bits +0 +16 ++ +OEPINT +OUT endpoint interrupt + bits +16 +16 ++ +OTG_HS_DAINTMSK +OTG_HS_DAINTMSK +OTG_HS all endpoints interrupt mask + register +0x1C +32 +read-write +0x0 ++ ++ +IEPM +IN EP interrupt mask bits +0 +16 ++ +OEPM +OUT EP interrupt mask bits +16 +16 ++ +OTG_HS_DVBUSDIS +OTG_HS_DVBUSDIS +OTG_HS device VBUS discharge time + register +0x28 +32 +read-write +0x000017D7 ++ ++ +VBUSDT +Device VBUS discharge time +0 +16 ++ +OTG_HS_DVBUSPULSE +OTG_HS_DVBUSPULSE +OTG_HS device VBUS pulsing time + register +0x2C +32 +read-write +0x000005B8 ++ ++ +DVBUSP +Device VBUS pulsing time +0 +12 ++ +OTG_HS_DTHRCTL +OTG_HS_DTHRCTL +OTG_HS Device threshold control + register +0x30 +32 +read-write +0x0 ++ ++ +NONISOTHREN +Nonisochronous IN endpoints threshold + enable +0 +1 ++ +ISOTHREN +ISO IN endpoint threshold + enable +1 +1 ++ +TXTHRLEN +Transmit threshold length +2 +9 ++ +RXTHREN +Receive threshold enable +16 +1 ++ +RXTHRLEN +Receive threshold length +17 +9 ++ +ARPEN +Arbiter parking enable +27 +1 ++ +OTG_HS_DIEPEMPMSK +OTG_HS_DIEPEMPMSK +OTG_HS device IN endpoint FIFO empty + interrupt mask register +0x34 +32 +read-write +0x0 ++ ++ +INEPTXFEM +IN EP Tx FIFO empty interrupt mask + bits +0 +16 ++ +OTG_HS_DEACHINT +OTG_HS_DEACHINT +OTG_HS device each endpoint interrupt + register +0x38 +32 +read-write +0x0 ++ ++ +IEP1INT +IN endpoint 1interrupt bit +1 +1 ++ +OEP1INT +OUT endpoint 1 interrupt + bit +17 +1 ++ +OTG_HS_DEACHINTMSK +OTG_HS_DEACHINTMSK +OTG_HS device each endpoint interrupt + register mask +0x3C +32 +read-write +0x0 ++ ++ +IEP1INTM +IN Endpoint 1 interrupt mask + bit +1 +1 ++ +OEP1INTM +OUT Endpoint 1 interrupt mask + bit +17 +1 ++ +OTG_HS_DIEPEACHMSK1 +OTG_HS_DIEPEACHMSK1 +OTG_HS device each in endpoint-1 interrupt + register +0x40 +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed interrupt + mask +0 +1 ++ +EPDM +Endpoint disabled interrupt + mask +1 +1 ++ +TOM +Timeout condition mask (nonisochronous + endpoints) +3 +1 ++ +ITTXFEMSK +IN token received when TxFIFO empty + mask +4 +1 ++ +INEPNMM +IN token received with EP mismatch + mask +5 +1 ++ +INEPNEM +IN endpoint NAK effective + mask +6 +1 ++ +TXFURM +FIFO underrun mask +8 +1 ++ +BIM +BNA interrupt mask +9 +1 ++ +NAKM +NAK interrupt mask +13 +1 ++ +OTG_HS_DOEPEACHMSK1 +OTG_HS_DOEPEACHMSK1 +OTG_HS device each OUT endpoint-1 interrupt + register +0x80 +32 +read-write +0x0 ++ ++ +XFRCM +Transfer completed interrupt + mask +0 +1 ++ +EPDM +Endpoint disabled interrupt + mask +1 +1 ++ +TOM +Timeout condition mask +3 +1 ++ +ITTXFEMSK +IN token received when TxFIFO empty + mask +4 +1 ++ +INEPNMM +IN token received with EP mismatch + mask +5 +1 ++ +INEPNEM +IN endpoint NAK effective + mask +6 +1 ++ +TXFURM +OUT packet error mask +8 +1 ++ +BIM +BNA interrupt mask +9 +1 ++ +BERRM +Bubble error interrupt + mask +12 +1 ++ +NAKM +NAK interrupt mask +13 +1 ++ +NYETM +NYET interrupt mask +14 +1 ++ +OTG_HS_DIEPCTL0 +OTG_HS_DIEPCTL0 +OTG device endpoint-0 control + register +0x100 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even/odd frame +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +TXFNUM +TxFIFO number +22 +4 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DIEPCTL1 +OTG_HS_DIEPCTL1 +OTG device endpoint-1 control + register +0x120 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even/odd frame +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +TXFNUM +TxFIFO number +22 +4 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DIEPCTL2 +OTG_HS_DIEPCTL2 +OTG device endpoint-2 control + register +0x140 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even/odd frame +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +TXFNUM +TxFIFO number +22 +4 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DIEPCTL3 +OTG_HS_DIEPCTL3 +OTG device endpoint-3 control + register +0x160 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even/odd frame +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +TXFNUM +TxFIFO number +22 +4 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DIEPCTL4 +OTG_HS_DIEPCTL4 +OTG device endpoint-4 control + register +0x180 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even/odd frame +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +TXFNUM +TxFIFO number +22 +4 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DIEPCTL5 +OTG_HS_DIEPCTL5 +OTG device endpoint-5 control + register +0x1A0 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even/odd frame +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +TXFNUM +TxFIFO number +22 +4 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DIEPCTL6 +OTG_HS_DIEPCTL6 +OTG device endpoint-6 control + register +0x1C0 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even/odd frame +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +TXFNUM +TxFIFO number +22 +4 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DIEPCTL7 +OTG_HS_DIEPCTL7 +OTG device endpoint-7 control + register +0x1E0 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even/odd frame +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +TXFNUM +TxFIFO number +22 +4 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DIEPINT0 +OTG_HS_DIEPINT0 +OTG device endpoint-0 interrupt + register +0x108 +32 +0x00000080 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 +read-write ++ +EPDISD +Endpoint disabled + interrupt +1 +1 +read-write ++ +TOC +Timeout condition +3 +1 +read-write ++ +ITTXFE +IN token received when TxFIFO is + empty +4 +1 +read-write ++ +INEPNE +IN endpoint NAK effective +6 +1 +read-write ++ +TXFE +Transmit FIFO empty +7 +1 +read-only ++ +TXFIFOUDRN +Transmit Fifo Underrun +8 +1 +read-write ++ +BNA +Buffer not available + interrupt +9 +1 +read-write ++ +PKTDRPSTS +Packet dropped status +11 +1 +read-write ++ +BERR +Babble error interrupt +12 +1 +read-write ++ +NAK +NAK interrupt +13 +1 +read-write ++ +OTG_HS_DIEPINT1 +OTG_HS_DIEPINT1 +OTG device endpoint-1 interrupt + register +0x128 +32 +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 +read-write ++ +EPDISD +Endpoint disabled + interrupt +1 +1 +read-write ++ +TOC +Timeout condition +3 +1 +read-write ++ +ITTXFE +IN token received when TxFIFO is + empty +4 +1 +read-write ++ +INEPNE +IN endpoint NAK effective +6 +1 +read-write ++ +TXFE +Transmit FIFO empty +7 +1 +read-only ++ +TXFIFOUDRN +Transmit Fifo Underrun +8 +1 +read-write ++ +BNA +Buffer not available + interrupt +9 +1 +read-write ++ +PKTDRPSTS +Packet dropped status +11 +1 +read-write ++ +BERR +Babble error interrupt +12 +1 +read-write ++ +NAK +NAK interrupt +13 +1 +read-write ++ +OTG_HS_DIEPINT2 +OTG_HS_DIEPINT2 +OTG device endpoint-2 interrupt + register +0x148 +32 +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 +read-write ++ +EPDISD +Endpoint disabled + interrupt +1 +1 +read-write ++ +TOC +Timeout condition +3 +1 +read-write ++ +ITTXFE +IN token received when TxFIFO is + empty +4 +1 +read-write ++ +INEPNE +IN endpoint NAK effective +6 +1 +read-write ++ +TXFE +Transmit FIFO empty +7 +1 +read-only ++ +TXFIFOUDRN +Transmit Fifo Underrun +8 +1 +read-write ++ +BNA +Buffer not available + interrupt +9 +1 +read-write ++ +PKTDRPSTS +Packet dropped status +11 +1 +read-write ++ +BERR +Babble error interrupt +12 +1 +read-write ++ +NAK +NAK interrupt +13 +1 +read-write ++ +OTG_HS_DIEPINT3 +OTG_HS_DIEPINT3 +OTG device endpoint-3 interrupt + register +0x168 +32 +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 +read-write ++ +EPDISD +Endpoint disabled + interrupt +1 +1 +read-write ++ +TOC +Timeout condition +3 +1 +read-write ++ +ITTXFE +IN token received when TxFIFO is + empty +4 +1 +read-write ++ +INEPNE +IN endpoint NAK effective +6 +1 +read-write ++ +TXFE +Transmit FIFO empty +7 +1 +read-only ++ +TXFIFOUDRN +Transmit Fifo Underrun +8 +1 +read-write ++ +BNA +Buffer not available + interrupt +9 +1 +read-write ++ +PKTDRPSTS +Packet dropped status +11 +1 +read-write ++ +BERR +Babble error interrupt +12 +1 +read-write ++ +NAK +NAK interrupt +13 +1 +read-write ++ +OTG_HS_DIEPINT4 +OTG_HS_DIEPINT4 +OTG device endpoint-4 interrupt + register +0x188 +32 +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 +read-write ++ +EPDISD +Endpoint disabled + interrupt +1 +1 +read-write ++ +TOC +Timeout condition +3 +1 +read-write ++ +ITTXFE +IN token received when TxFIFO is + empty +4 +1 +read-write ++ +INEPNE +IN endpoint NAK effective +6 +1 +read-write ++ +TXFE +Transmit FIFO empty +7 +1 +read-only ++ +TXFIFOUDRN +Transmit Fifo Underrun +8 +1 +read-write ++ +BNA +Buffer not available + interrupt +9 +1 +read-write ++ +PKTDRPSTS +Packet dropped status +11 +1 +read-write ++ +BERR +Babble error interrupt +12 +1 +read-write ++ +NAK +NAK interrupt +13 +1 +read-write ++ +OTG_HS_DIEPINT5 +OTG_HS_DIEPINT5 +OTG device endpoint-5 interrupt + register +0x1A8 +32 +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 +read-write ++ +EPDISD +Endpoint disabled + interrupt +1 +1 +read-write ++ +TOC +Timeout condition +3 +1 +read-write ++ +ITTXFE +IN token received when TxFIFO is + empty +4 +1 +read-write ++ +INEPNE +IN endpoint NAK effective +6 +1 +read-write ++ +TXFE +Transmit FIFO empty +7 +1 +read-only ++ +TXFIFOUDRN +Transmit Fifo Underrun +8 +1 +read-write ++ +BNA +Buffer not available + interrupt +9 +1 +read-write ++ +PKTDRPSTS +Packet dropped status +11 +1 +read-write ++ +BERR +Babble error interrupt +12 +1 +read-write ++ +NAK +NAK interrupt +13 +1 +read-write ++ +OTG_HS_DIEPINT6 +OTG_HS_DIEPINT6 +OTG device endpoint-6 interrupt + register +0x1C8 +32 +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 +read-write ++ +EPDISD +Endpoint disabled + interrupt +1 +1 +read-write ++ +TOC +Timeout condition +3 +1 +read-write ++ +ITTXFE +IN token received when TxFIFO is + empty +4 +1 +read-write ++ +INEPNE +IN endpoint NAK effective +6 +1 +read-write ++ +TXFE +Transmit FIFO empty +7 +1 +read-only ++ +TXFIFOUDRN +Transmit Fifo Underrun +8 +1 +read-write ++ +BNA +Buffer not available + interrupt +9 +1 +read-write ++ +PKTDRPSTS +Packet dropped status +11 +1 +read-write ++ +BERR +Babble error interrupt +12 +1 +read-write ++ +NAK +NAK interrupt +13 +1 +read-write ++ +OTG_HS_DIEPINT7 +OTG_HS_DIEPINT7 +OTG device endpoint-7 interrupt + register +0x1E8 +32 +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 +read-write ++ +EPDISD +Endpoint disabled + interrupt +1 +1 +read-write ++ +TOC +Timeout condition +3 +1 +read-write ++ +ITTXFE +IN token received when TxFIFO is + empty +4 +1 +read-write ++ +INEPNE +IN endpoint NAK effective +6 +1 +read-write ++ +TXFE +Transmit FIFO empty +7 +1 +read-only ++ +TXFIFOUDRN +Transmit Fifo Underrun +8 +1 +read-write ++ +BNA +Buffer not available + interrupt +9 +1 +read-write ++ +PKTDRPSTS +Packet dropped status +11 +1 +read-write ++ +BERR +Babble error interrupt +12 +1 +read-write ++ +NAK +NAK interrupt +13 +1 +read-write ++ +OTG_HS_DIEPTSIZ0 +OTG_HS_DIEPTSIZ0 +OTG_HS device IN endpoint 0 transfer size + register +0x110 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +7 ++ +PKTCNT +Packet count +19 +2 ++ +OTG_HS_DIEPDMA1 +OTG_HS_DIEPDMA1 +OTG_HS device endpoint-1 DMA address + register +0x114 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_DIEPDMA2 +OTG_HS_DIEPDMA2 +OTG_HS device endpoint-2 DMA address + register +0x134 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_DIEPDMA3 +OTG_HS_DIEPDMA3 +OTG_HS device endpoint-3 DMA address + register +0x154 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_DIEPDMA4 +OTG_HS_DIEPDMA4 +OTG_HS device endpoint-4 DMA address + register +0x174 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_DIEPDMA5 +OTG_HS_DIEPDMA5 +OTG_HS device endpoint-5 DMA address + register +0x194 +32 +read-write +0x0 ++ ++ +DMAADDR +DMA address +0 +32 ++ +OTG_HS_DTXFSTS0 +OTG_HS_DTXFSTS0 +OTG_HS device IN endpoint transmit FIFO + status register +0x118 +32 +read-only +0x0 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + avail +0 +16 ++ +OTG_HS_DTXFSTS1 +OTG_HS_DTXFSTS1 +OTG_HS device IN endpoint transmit FIFO + status register +0x138 +32 +read-only +0x0 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + avail +0 +16 ++ +OTG_HS_DTXFSTS2 +OTG_HS_DTXFSTS2 +OTG_HS device IN endpoint transmit FIFO + status register +0x158 +32 +read-only +0x0 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + avail +0 +16 ++ +OTG_HS_DTXFSTS3 +OTG_HS_DTXFSTS3 +OTG_HS device IN endpoint transmit FIFO + status register +0x178 +32 +read-only +0x0 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + avail +0 +16 ++ +OTG_HS_DTXFSTS4 +OTG_HS_DTXFSTS4 +OTG_HS device IN endpoint transmit FIFO + status register +0x198 +32 +read-only +0x0 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + avail +0 +16 ++ +OTG_HS_DTXFSTS5 +OTG_HS_DTXFSTS5 +OTG_HS device IN endpoint transmit FIFO + status register +0x1B8 +32 +read-only +0x0 ++ ++ +INEPTFSAV +IN endpoint TxFIFO space + avail +0 +16 ++ +OTG_HS_DIEPTSIZ1 +OTG_HS_DIEPTSIZ1 +OTG_HS device endpoint transfer size + register +0x130 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +MCNT +Multi count +29 +2 ++ +OTG_HS_DIEPTSIZ2 +OTG_HS_DIEPTSIZ2 +OTG_HS device endpoint transfer size + register +0x150 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +MCNT +Multi count +29 +2 ++ +OTG_HS_DIEPTSIZ3 +OTG_HS_DIEPTSIZ3 +OTG_HS device endpoint transfer size + register +0x170 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +MCNT +Multi count +29 +2 ++ +OTG_HS_DIEPTSIZ4 +OTG_HS_DIEPTSIZ4 +OTG_HS device endpoint transfer size + register +0x190 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +MCNT +Multi count +29 +2 ++ +OTG_HS_DIEPTSIZ5 +OTG_HS_DIEPTSIZ5 +OTG_HS device endpoint transfer size + register +0x1B0 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +MCNT +Multi count +29 +2 ++ +OTG_HS_DOEPCTL0 +OTG_HS_DOEPCTL0 +OTG_HS device control OUT endpoint 0 control + register +0x300 +32 +0x00008000 ++ ++ +MPSIZ +Maximum packet size +0 +2 +read-only ++ +USBAEP +USB active endpoint +15 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-only ++ +SNPM +Snoop mode +20 +1 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-only ++ +EPENA +Endpoint enable +31 +1 +write-only ++ +OTG_HS_DOEPCTL1 +OTG_HS_DOEPCTL1 +OTG device endpoint-1 control + register +0x320 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even odd frame/Endpoint data + PID +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +SNPM +Snoop mode +20 +1 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID/Set even + frame +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DOEPCTL2 +OTG_HS_DOEPCTL2 +OTG device endpoint-2 control + register +0x340 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even odd frame/Endpoint data + PID +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +SNPM +Snoop mode +20 +1 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID/Set even + frame +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DOEPCTL3 +OTG_HS_DOEPCTL3 +OTG device endpoint-3 control + register +0x360 +32 +0x0 ++ ++ +MPSIZ +Maximum packet size +0 +11 +read-write ++ +USBAEP +USB active endpoint +15 +1 +read-write ++ +EONUM_DPID +Even odd frame/Endpoint data + PID +16 +1 +read-only ++ +NAKSTS +NAK status +17 +1 +read-only ++ +EPTYP +Endpoint type +18 +2 +read-write ++ +SNPM +Snoop mode +20 +1 +read-write ++ +Stall +STALL handshake +21 +1 +read-write ++ +CNAK +Clear NAK +26 +1 +write-only ++ +SNAK +Set NAK +27 +1 +write-only ++ +SD0PID_SEVNFRM +Set DATA0 PID/Set even + frame +28 +1 +write-only ++ +SODDFRM +Set odd frame +29 +1 +write-only ++ +EPDIS +Endpoint disable +30 +1 +read-write ++ +EPENA +Endpoint enable +31 +1 +read-write ++ +OTG_HS_DOEPINT0 +OTG_HS_DOEPINT0 +OTG_HS device endpoint-0 interrupt + register +0x308 +32 +read-write +0x00000080 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 ++ +EPDISD +Endpoint disabled + interrupt +1 +1 ++ +STUP +SETUP phase done +3 +1 ++ +OTEPDIS +OUT token received when endpoint + disabled +4 +1 ++ +B2BSTUP +Back-to-back SETUP packets + received +6 +1 ++ +NYET +NYET interrupt +14 +1 ++ +OTG_HS_DOEPINT1 +OTG_HS_DOEPINT1 +OTG_HS device endpoint-1 interrupt + register +0x328 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 ++ +EPDISD +Endpoint disabled + interrupt +1 +1 ++ +STUP +SETUP phase done +3 +1 ++ +OTEPDIS +OUT token received when endpoint + disabled +4 +1 ++ +B2BSTUP +Back-to-back SETUP packets + received +6 +1 ++ +NYET +NYET interrupt +14 +1 ++ +OTG_HS_DOEPINT2 +OTG_HS_DOEPINT2 +OTG_HS device endpoint-2 interrupt + register +0x348 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 ++ +EPDISD +Endpoint disabled + interrupt +1 +1 ++ +STUP +SETUP phase done +3 +1 ++ +OTEPDIS +OUT token received when endpoint + disabled +4 +1 ++ +B2BSTUP +Back-to-back SETUP packets + received +6 +1 ++ +NYET +NYET interrupt +14 +1 ++ +OTG_HS_DOEPINT3 +OTG_HS_DOEPINT3 +OTG_HS device endpoint-3 interrupt + register +0x368 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 ++ +EPDISD +Endpoint disabled + interrupt +1 +1 ++ +STUP +SETUP phase done +3 +1 ++ +OTEPDIS +OUT token received when endpoint + disabled +4 +1 ++ +B2BSTUP +Back-to-back SETUP packets + received +6 +1 ++ +NYET +NYET interrupt +14 +1 ++ +OTG_HS_DOEPINT4 +OTG_HS_DOEPINT4 +OTG_HS device endpoint-4 interrupt + register +0x388 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 ++ +EPDISD +Endpoint disabled + interrupt +1 +1 ++ +STUP +SETUP phase done +3 +1 ++ +OTEPDIS +OUT token received when endpoint + disabled +4 +1 ++ +B2BSTUP +Back-to-back SETUP packets + received +6 +1 ++ +NYET +NYET interrupt +14 +1 ++ +OTG_HS_DOEPINT5 +OTG_HS_DOEPINT5 +OTG_HS device endpoint-5 interrupt + register +0x3A8 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 ++ +EPDISD +Endpoint disabled + interrupt +1 +1 ++ +STUP +SETUP phase done +3 +1 ++ +OTEPDIS +OUT token received when endpoint + disabled +4 +1 ++ +B2BSTUP +Back-to-back SETUP packets + received +6 +1 ++ +NYET +NYET interrupt +14 +1 ++ +OTG_HS_DOEPINT6 +OTG_HS_DOEPINT6 +OTG_HS device endpoint-6 interrupt + register +0x3C8 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 ++ +EPDISD +Endpoint disabled + interrupt +1 +1 ++ +STUP +SETUP phase done +3 +1 ++ +OTEPDIS +OUT token received when endpoint + disabled +4 +1 ++ +B2BSTUP +Back-to-back SETUP packets + received +6 +1 ++ +NYET +NYET interrupt +14 +1 ++ +OTG_HS_DOEPINT7 +OTG_HS_DOEPINT7 +OTG_HS device endpoint-7 interrupt + register +0x3E8 +32 +read-write +0x0 ++ ++ +XFRC +Transfer completed + interrupt +0 +1 ++ +EPDISD +Endpoint disabled + interrupt +1 +1 ++ +STUP +SETUP phase done +3 +1 ++ +OTEPDIS +OUT token received when endpoint + disabled +4 +1 ++ +B2BSTUP +Back-to-back SETUP packets + received +6 +1 ++ +NYET +NYET interrupt +14 +1 ++ +OTG_HS_DOEPTSIZ0 +OTG_HS_DOEPTSIZ0 +OTG_HS device endpoint-1 transfer size + register +0x310 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +7 ++ +PKTCNT +Packet count +19 +1 ++ +STUPCNT +SETUP packet count +29 +2 ++ +OTG_HS_DOEPTSIZ1 +OTG_HS_DOEPTSIZ1 +OTG_HS device endpoint-2 transfer size + register +0x330 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +RXDPID_STUPCNT +Received data PID/SETUP packet + count +29 +2 ++ +OTG_HS_DOEPTSIZ2 +OTG_HS_DOEPTSIZ2 +OTG_HS device endpoint-3 transfer size + register +0x350 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +RXDPID_STUPCNT +Received data PID/SETUP packet + count +29 +2 ++ +OTG_HS_DOEPTSIZ3 +OTG_HS_DOEPTSIZ3 +OTG_HS device endpoint-4 transfer size + register +0x370 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +RXDPID_STUPCNT +Received data PID/SETUP packet + count +29 +2 ++ +OTG_HS_DOEPTSIZ4 +OTG_HS_DOEPTSIZ4 +OTG_HS device endpoint-5 transfer size + register +0x390 +32 +read-write +0x0 ++ ++ +XFRSIZ +Transfer size +0 +19 ++ +PKTCNT +Packet count +19 +10 ++ +RXDPID_STUPCNT +Received data PID/SETUP packet + count +29 +2 ++ +OTG_HS_PWRCLK +USB on the go high speed +USB_OTG_HS +0x40040E00 ++ +0x0 +0x3F200 +registers ++ ++ +OTG_HS_PCGCR +OTG_HS_PCGCR +Power and clock gating control + register +0x0 +32 +read-write +0x0 ++ ++ +STPPCLK +Stop PHY clock +0 +1 ++ +GATEHCLK +Gate HCLK +1 +1 ++ +PHYSUSP +PHY suspended +4 +1 ++ +NVIC +Nested Vectored Interrupt + Controller +NVIC +0xE000E100 ++ +0x0 +0x351 +registers ++ ++ +ISER0 +ISER0 +Interrupt Set-Enable Register +0x0 +0x20 +read-write +0x00000000 ++ ++ +SETENA +SETENA +0 +32 ++ +ISER1 +ISER1 +Interrupt Set-Enable Register +0x4 +0x20 +read-write +0x00000000 ++ ++ +SETENA +SETENA +0 +32 ++ +ISER2 +ISER2 +Interrupt Set-Enable Register +0x8 +0x20 +read-write +0x00000000 ++ ++ +SETENA +SETENA +0 +32 ++ +ICER0 +ICER0 +Interrupt Clear-Enable + Register +0x80 +0x20 +read-write +0x00000000 ++ ++ +CLRENA +CLRENA +0 +32 ++ +ICER1 +ICER1 +Interrupt Clear-Enable + Register +0x84 +0x20 +read-write +0x00000000 ++ ++ +CLRENA +CLRENA +0 +32 ++ +ICER2 +ICER2 +Interrupt Clear-Enable + Register +0x88 +0x20 +read-write +0x00000000 ++ ++ +CLRENA +CLRENA +0 +32 ++ +ISPR0 +ISPR0 +Interrupt Set-Pending Register +0x100 +0x20 +read-write +0x00000000 ++ ++ +SETPEND +SETPEND +0 +32 ++ +ISPR1 +ISPR1 +Interrupt Set-Pending Register +0x104 +0x20 +read-write +0x00000000 ++ ++ +SETPEND +SETPEND +0 +32 ++ +ISPR2 +ISPR2 +Interrupt Set-Pending Register +0x108 +0x20 +read-write +0x00000000 ++ ++ +SETPEND +SETPEND +0 +32 ++ +ICPR0 +ICPR0 +Interrupt Clear-Pending + Register +0x180 +0x20 +read-write +0x00000000 ++ ++ +CLRPEND +CLRPEND +0 +32 ++ +ICPR1 +ICPR1 +Interrupt Clear-Pending + Register +0x184 +0x20 +read-write +0x00000000 ++ ++ +CLRPEND +CLRPEND +0 +32 ++ +ICPR2 +ICPR2 +Interrupt Clear-Pending + Register +0x188 +0x20 +read-write +0x00000000 ++ ++ +CLRPEND +CLRPEND +0 +32 ++ +IABR0 +IABR0 +Interrupt Active Bit Register +0x200 +0x20 +read-only +0x00000000 ++ ++ +ACTIVE +ACTIVE +0 +32 ++ +IABR1 +IABR1 +Interrupt Active Bit Register +0x204 +0x20 +read-only +0x00000000 ++ ++ +ACTIVE +ACTIVE +0 +32 ++ +IABR2 +IABR2 +Interrupt Active Bit Register +0x208 +0x20 +read-only +0x00000000 ++ ++ +ACTIVE +ACTIVE +0 +32 ++ +IPR0 +IPR0 +Interrupt Priority Register +0x300 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR1 +IPR1 +Interrupt Priority Register +0x304 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR2 +IPR2 +Interrupt Priority Register +0x308 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR3 +IPR3 +Interrupt Priority Register +0x30C +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR4 +IPR4 +Interrupt Priority Register +0x310 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR5 +IPR5 +Interrupt Priority Register +0x314 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR6 +IPR6 +Interrupt Priority Register +0x318 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR7 +IPR7 +Interrupt Priority Register +0x31C +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR8 +IPR8 +Interrupt Priority Register +0x320 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR9 +IPR9 +Interrupt Priority Register +0x324 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR10 +IPR10 +Interrupt Priority Register +0x328 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR11 +IPR11 +Interrupt Priority Register +0x32C +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR12 +IPR12 +Interrupt Priority Register +0x330 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR13 +IPR13 +Interrupt Priority Register +0x334 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR14 +IPR14 +Interrupt Priority Register +0x338 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR15 +IPR15 +Interrupt Priority Register +0x33C +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR16 +IPR16 +Interrupt Priority Register +0x340 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR17 +IPR17 +Interrupt Priority Register +0x344 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR18 +IPR18 +Interrupt Priority Register +0x348 +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +IPR19 +IPR19 +Interrupt Priority Register +0x34C +0x20 +read-write +0x00000000 ++ ++ +IPR_N0 +IPR_N0 +0 +8 ++ +IPR_N1 +IPR_N1 +8 +8 ++ +IPR_N2 +IPR_N2 +16 +8 ++ +IPR_N3 +IPR_N3 +24 +8 ++ +SAI1 +Serial audio interface +SAI1 +0x40015800 ++ +0x0 +0x400 +registers ++ ++ +SAI_ACR1 +SAI_ACR1 +SAI AConfiguration register 1 +0x4 +0x20 +read-write +0x00000040 ++ ++ +MCKDIV +Master clock divider +20 +4 ++ +MODE +Audio block mode +0 +2 ++ +PRTCFG +Protocol configuration +2 +2 ++ +DS +Data size +5 +3 ++ +LSBFIRST +Least significant bit + first +8 +1 ++ +CKSTR +Clock strobing edge +9 +1 ++ +SYNCEN +Synchronization enable +10 +2 ++ +MONO +Mono mode +12 +1 ++ +OUTDRIV +Output drive +13 +1 ++ +SAIAEN +Audio block enable +16 +1 ++ +DMAEN +DMA enable +17 +1 ++ +NODIV +No divider +19 +1 ++ +SAI_BCR1 +SAI_BCR1 +SAI BConfiguration register 1 +0x24 +0x20 +read-write +0x00000040 ++ ++ +MODE +Audio block mode +0 +2 ++ +PRTCFG +Protocol configuration +2 +2 ++ +DS +Data size +5 +3 ++ +LSBFIRST +Least significant bit + first +8 +1 ++ +CKSTR +Clock strobing edge +9 +1 ++ +SYNCEN +Synchronization enable +10 +2 ++ +MONO +Mono mode +12 +1 ++ +OUTDRIV +Output drive +13 +1 ++ +SAIBEN +Audio block enable +16 +1 ++ +DMAEN +DMA enable +17 +1 ++ +NODIV +No divider +19 +1 ++ +MCKDIV +Master clock divider +20 +4 ++ +SAI_ACR2 +SAI_ACR2 +SAI AConfiguration register 2 +0x8 +0x20 +read-write +0x00000040 ++ ++ +FTH +FIFO threshold +0 +3 ++ +FFLUSH +FIFO flush +3 +1 ++ +TRIS +Tristate management on data + line +4 +1 ++ +MUTE +Mute +5 +1 ++ +MUTEVAL +Mute value +6 +1 ++ +MUTECNT +Mute counter +7 +6 ++ +CPL +Complement bit +13 +1 ++ +COMP +Companding mode +14 +2 ++ +SAI_BCR2 +SAI_BCR2 +SAI BConfiguration register 2 +0x28 +0x20 +read-write +0x00000040 ++ ++ +FTH +FIFO threshold +0 +3 ++ +FFLUSH +FIFO flush +3 +1 ++ +TRIS +Tristate management on data + line +4 +1 ++ +MUTE +Mute +5 +1 ++ +MUTEVAL +Mute value +6 +1 ++ +MUTECNT +Mute counter +7 +6 ++ +CPL +Complement bit +13 +1 ++ +COMP +Companding mode +14 +2 ++ +SAI_AFRCR +SAI_AFRCR +SAI AFrame configuration + register +0xC +0x20 +0x00000007 ++ ++ +FRL +Frame length +0 +8 +read-write ++ +FSALL +Frame synchronization active level + length +8 +7 +read-write ++ +FSDEF +Frame synchronization + definition +16 +1 +read-only ++ +FSPOL +Frame synchronization + polarity +17 +1 +read-write ++ +FSOFF +Frame synchronization + offset +18 +1 +read-write ++ +SAI_BFRCR +SAI_BFRCR +SAI BFrame configuration + register +0x2C +0x20 +0x00000007 ++ ++ +FRL +Frame length +0 +8 +read-write ++ +FSALL +Frame synchronization active level + length +8 +7 +read-write ++ +FSDEF +Frame synchronization + definition +16 +1 +read-only ++ +FSPOL +Frame synchronization + polarity +17 +1 +read-write ++ +FSOFF +Frame synchronization + offset +18 +1 +read-write ++ +SAI_ASLOTR +SAI_ASLOTR +SAI ASlot register +0x10 +0x20 +read-write +0x00000000 ++ ++ +FBOFF +First bit offset +0 +5 ++ +SLOTSZ +Slot size +6 +2 ++ +NBSLOT +Number of slots in an audio + frame +8 +4 ++ +SLOTEN +Slot enable +16 +16 ++ +SAI_BSLOTR +SAI_BSLOTR +SAI BSlot register +0x30 +0x20 +read-write +0x00000000 ++ ++ +FBOFF +First bit offset +0 +5 ++ +SLOTSZ +Slot size +6 +2 ++ +NBSLOT +Number of slots in an audio + frame +8 +4 ++ +SLOTEN +Slot enable +16 +16 ++ +SAI_AIM +SAI_AIM +SAI AInterrupt mask register2 +0x14 +0x20 +read-write +0x00000000 ++ ++ +OVRUDRIE +Overrun/underrun interrupt + enable +0 +1 ++ +MUTEDETIE +Mute detection interrupt + enable +1 +1 ++ +WCKCFGIE +Wrong clock configuration interrupt + enable +2 +1 ++ +FREQIE +FIFO request interrupt + enable +3 +1 ++ +CNRDYIE +Codec not ready interrupt + enable +4 +1 ++ +AFSDETIE +Anticipated frame synchronization + detection interrupt enable +5 +1 ++ +LFSDETIE +Late frame synchronization detection + interrupt enable +6 +1 ++ +SAI_BIM +SAI_BIM +SAI BInterrupt mask register2 +0x34 +0x20 +read-write +0x00000000 ++ ++ +OVRUDRIE +Overrun/underrun interrupt + enable +0 +1 ++ +MUTEDETIE +Mute detection interrupt + enable +1 +1 ++ +WCKCFGIE +Wrong clock configuration interrupt + enable +2 +1 ++ +FREQIE +FIFO request interrupt + enable +3 +1 ++ +CNRDYIE +Codec not ready interrupt + enable +4 +1 ++ +AFSDETIE +Anticipated frame synchronization + detection interrupt enable +5 +1 ++ +LFSDETIE +Late frame synchronization detection + interrupt enable +6 +1 ++ +SAI_ASR +SAI_ASR +SAI AStatus register +0x18 +0x20 +read-only +0x00000008 ++ ++ +OVRUDR +Overrun / underrun +0 +1 ++ +MUTEDET +Mute detection +1 +1 ++ +WCKCFG +Wrong clock configuration + flag +2 +1 ++ +FREQ +FIFO request +3 +1 ++ +CNRDY +Codec not ready +4 +1 ++ +AFSDET +Anticipated frame synchronization + detection +5 +1 ++ +LFSDET +Late frame synchronization + detection +6 +1 ++ +FLTH +FIFO level threshold +16 +3 ++ +SAI_BSR +SAI_BSR +SAI BStatus register +0x38 +0x20 +read-only +0x00000008 ++ ++ +OVRUDR +Overrun / underrun +0 +1 ++ +MUTEDET +Mute detection +1 +1 ++ +WCKCFG +Wrong clock configuration + flag +2 +1 ++ +FREQ +FIFO request +3 +1 ++ +CNRDY +Codec not ready +4 +1 ++ +AFSDET +Anticipated frame synchronization + detection +5 +1 ++ +LFSDET +Late frame synchronization + detection +6 +1 ++ +FLTH +FIFO level threshold +16 +3 ++ +SAI_ACLRFR +SAI_ACLRFR +SAI AClear flag register +0x1C +0x20 +read-write +0x00000000 ++ ++ +COVRUDR +Clear overrun / underrun +0 +1 ++ +CMUTEDET +Mute detection flag +1 +1 ++ +CWCKCFG +Clear wrong clock configuration + flag +2 +1 ++ +CCNRDY +Clear codec not ready flag +4 +1 ++ +CAFSDET +Clear anticipated frame synchronization + detection flag +5 +1 ++ +CLFSDET +Clear late frame synchronization + detection flag +6 +1 ++ +SAI_BCLRFR +SAI_BCLRFR +SAI BClear flag register +0x3C +0x20 +read-write +0x00000000 ++ ++ +COVRUDR +Clear overrun / underrun +0 +1 ++ +CMUTEDET +Mute detection flag +1 +1 ++ +CWCKCFG +Clear wrong clock configuration + flag +2 +1 ++ +CCNRDY +Clear codec not ready flag +4 +1 ++ +CAFSDET +Clear anticipated frame synchronization + detection flag +5 +1 ++ +CLFSDET +Clear late frame synchronization + detection flag +6 +1 ++ +SAI_ADR +SAI_ADR +SAI AData register +0x20 +0x20 +read-write +0x00000000 ++ ++ +DATA +Data +0 +32 ++ +SAI_BDR +SAI_BDR +SAI BData register +0x40 +0x20 +read-write +0x00000000 ++ ++ +DATA +Data +0 +32 ++ +LTDC +LCD-TFT Controller +LTDC +0x40016800 ++ +0x0 +0x400 +registers ++ +LCD_TFT +LTDC global interrupt +88 ++ +LCD_TFT_1 +LTDC global error interrupt +89 ++ ++ +SSCR +SSCR +Synchronization Size Configuration + Register +0x8 +0x20 +read-write +0x00000000 ++ ++ +HSW +Horizontal Synchronization Width (in + units of pixel clock period) +16 +10 ++ +VSH +Vertical Synchronization Height (in + units of horizontal scan line) +0 +11 ++ +BPCR +BPCR +Back Porch Configuration + Register +0xC +0x20 +read-write +0x00000000 ++ ++ +AHBP +Accumulated Horizontal back porch (in + units of pixel clock period) +16 +10 ++ +AVBP +Accumulated Vertical back porch (in + units of horizontal scan line) +0 +11 ++ +AWCR +AWCR +Active Width Configuration + Register +0x10 +0x20 +read-write +0x00000000 ++ ++ +AAV +AAV +16 +10 ++ +AAH +Accumulated Active Height (in units of + horizontal scan line) +0 +11 ++ +TWCR +TWCR +Total Width Configuration + Register +0x14 +0x20 +read-write +0x00000000 ++ ++ +TOTALW +Total Width (in units of pixel clock + period) +16 +10 ++ +TOTALH +Total Height (in units of horizontal + scan line) +0 +11 ++ +GCR +GCR +Global Control Register +0x18 +0x20 +0x00002220 ++ ++ +HSPOL +Horizontal Synchronization + Polarity +31 +1 +read-write ++ +VSPOL +Vertical Synchronization + Polarity +30 +1 +read-write ++ +DEPOL +Data Enable Polarity +29 +1 +read-write ++ +PCPOL +Pixel Clock Polarity +28 +1 +read-write ++ +DEN +Dither Enable +16 +1 +read-write ++ +DRW +Dither Red Width +12 +3 +read-only ++ +DGW +Dither Green Width +8 +3 +read-only ++ +DBW +Dither Blue Width +4 +3 +read-only ++ +LTDCEN +LCD-TFT controller enable + bit +0 +1 +read-write ++ +SRCR +SRCR +Shadow Reload Configuration + Register +0x24 +0x20 +read-write +0x00000000 ++ ++ +VBR +Vertical Blanking Reload +1 +1 ++ +IMR +Immediate Reload +0 +1 ++ +BCCR +BCCR +Background Color Configuration + Register +0x2C +0x20 +read-write +0x00000000 ++ ++ +BC +Background Color Red value +0 +24 ++ +IER +IER +Interrupt Enable Register +0x34 +0x20 +read-write +0x00000000 ++ ++ +RRIE +Register Reload interrupt + enable +3 +1 ++ +TERRIE +Transfer Error Interrupt + Enable +2 +1 ++ +FUIE +FIFO Underrun Interrupt + Enable +1 +1 ++ +LIE +Line Interrupt Enable +0 +1 ++ +ISR +ISR +Interrupt Status Register +0x38 +0x20 +read-only +0x00000000 ++ ++ +RRIF +Register Reload Interrupt + Flag +3 +1 ++ +TERRIF +Transfer Error interrupt + flag +2 +1 ++ +FUIF +FIFO Underrun Interrupt + flag +1 +1 ++ +LIF +Line Interrupt flag +0 +1 ++ +ICR +ICR +Interrupt Clear Register +0x3C +0x20 +write-only +0x00000000 ++ ++ +CRRIF +Clears Register Reload Interrupt + Flag +3 +1 ++ +CTERRIF +Clears the Transfer Error Interrupt + Flag +2 +1 ++ +CFUIF +Clears the FIFO Underrun Interrupt + flag +1 +1 ++ +CLIF +Clears the Line Interrupt + Flag +0 +1 ++ +LIPCR +LIPCR +Line Interrupt Position Configuration + Register +0x40 +0x20 +read-write +0x00000000 ++ ++ +LIPOS +Line Interrupt Position +0 +11 ++ +CPSR +CPSR +Current Position Status + Register +0x44 +0x20 +read-only +0x00000000 ++ ++ +CXPOS +Current X Position +16 +16 ++ +CYPOS +Current Y Position +0 +16 ++ +CDSR +CDSR +Current Display Status + Register +0x48 +0x20 +read-only +0x0000000F ++ ++ +HSYNCS +Horizontal Synchronization display + Status +3 +1 ++ +VSYNCS +Vertical Synchronization display + Status +2 +1 ++ +HDES +Horizontal Data Enable display + Status +1 +1 ++ +VDES +Vertical Data Enable display + Status +0 +1 ++ +L1CR +L1CR +Layerx Control Register +0x84 +0x20 +read-write +0x00000000 ++ ++ +CLUTEN +Color Look-Up Table Enable +4 +1 ++ +COLKEN +Color Keying Enable +1 +1 ++ +LEN +Layer Enable +0 +1 ++ +L1WHPCR +L1WHPCR +Layerx Window Horizontal Position + Configuration Register +0x88 +0x20 +read-write +0x00000000 ++ ++ +WHSPPOS +Window Horizontal Stop + Position +16 +12 ++ +WHSTPOS +Window Horizontal Start + Position +0 +12 ++ +L1WVPCR +L1WVPCR +Layerx Window Vertical Position + Configuration Register +0x8C +0x20 +read-write +0x00000000 ++ ++ +WVSPPOS +Window Vertical Stop + Position +16 +11 ++ +WVSTPOS +Window Vertical Start + Position +0 +11 ++ +L1CKCR +L1CKCR +Layerx Color Keying Configuration + Register +0x90 +0x20 +read-write +0x00000000 ++ ++ +CKRED +Color Key Red value +16 +8 ++ +CKGREEN +Color Key Green value +8 +8 ++ +CKBLUE +Color Key Blue value +0 +8 ++ +L1PFCR +L1PFCR +Layerx Pixel Format Configuration + Register +0x94 +0x20 +read-write +0x00000000 ++ ++ +PF +Pixel Format +0 +3 ++ +L1CACR +L1CACR +Layerx Constant Alpha Configuration + Register +0x98 +0x20 +read-write +0x00000000 ++ ++ +CONSTA +Constant Alpha +0 +8 ++ +L1DCCR +L1DCCR +Layerx Default Color Configuration + Register +0x9C +0x20 +read-write +0x00000000 ++ ++ +DCALPHA +Default Color Alpha +24 +8 ++ +DCRED +Default Color Red +16 +8 ++ +DCGREEN +Default Color Green +8 +8 ++ +DCBLUE +Default Color Blue +0 +8 ++ +L1BFCR +L1BFCR +Layerx Blending Factors Configuration + Register +0xA0 +0x20 +read-write +0x00000607 ++ ++ +BF1 +Blending Factor 1 +8 +3 ++ +BF2 +Blending Factor 2 +0 +3 ++ +L1CFBAR +L1CFBAR +Layerx Color Frame Buffer Address + Register +0xAC +0x20 +read-write +0x00000000 ++ ++ +CFBADD +Color Frame Buffer Start + Address +0 +32 ++ +L1CFBLR +L1CFBLR +Layerx Color Frame Buffer Length + Register +0xB0 +0x20 +read-write +0x00000000 ++ ++ +CFBP +Color Frame Buffer Pitch in + bytes +16 +13 ++ +CFBLL +Color Frame Buffer Line + Length +0 +13 ++ +L1CFBLNR +L1CFBLNR +Layerx ColorFrame Buffer Line Number + Register +0xB4 +0x20 +read-write +0x00000000 ++ ++ +CFBLNBR +Frame Buffer Line Number +0 +11 ++ +L1CLUTWR +L1CLUTWR +Layerx CLUT Write Register +0xC4 +0x20 +write-only +0x00000000 ++ ++ +CLUTADD +CLUT Address +24 +8 ++ +RED +Red value +16 +8 ++ +GREEN +Green value +8 +8 ++ +BLUE +Blue value +0 +8 ++ +L2CR +L2CR +Layerx Control Register +0x104 +0x20 +read-write +0x00000000 ++ ++ +CLUTEN +Color Look-Up Table Enable +4 +1 ++ +COLKEN +Color Keying Enable +1 +1 ++ +LEN +Layer Enable +0 +1 ++ +L2WHPCR +L2WHPCR +Layerx Window Horizontal Position + Configuration Register +0x108 +0x20 +read-write +0x00000000 ++ ++ +WHSPPOS +Window Horizontal Stop + Position +16 +12 ++ +WHSTPOS +Window Horizontal Start + Position +0 +12 ++ +L2WVPCR +L2WVPCR +Layerx Window Vertical Position + Configuration Register +0x10C +0x20 +read-write +0x00000000 ++ ++ +WVSPPOS +Window Vertical Stop + Position +16 +11 ++ +WVSTPOS +Window Vertical Start + Position +0 +11 ++ +L2CKCR +L2CKCR +Layerx Color Keying Configuration + Register +0x110 +0x20 +read-write +0x00000000 ++ ++ +CKRED +Color Key Red value +15 +9 ++ +CKGREEN +Color Key Green value +8 +7 ++ +CKBLUE +Color Key Blue value +0 +8 ++ +L2PFCR +L2PFCR +Layerx Pixel Format Configuration + Register +0x114 +0x20 +read-write +0x00000000 ++ ++ +PF +Pixel Format +0 +3 ++ +L2CACR +L2CACR +Layerx Constant Alpha Configuration + Register +0x118 +0x20 +read-write +0x00000000 ++ ++ +CONSTA +Constant Alpha +0 +8 ++ +L2DCCR +L2DCCR +Layerx Default Color Configuration + Register +0x11C +0x20 +read-write +0x00000000 ++ ++ +DCALPHA +Default Color Alpha +24 +8 ++ +DCRED +Default Color Red +16 +8 ++ +DCGREEN +Default Color Green +8 +8 ++ +DCBLUE +Default Color Blue +0 +8 ++ +L2BFCR +L2BFCR +Layerx Blending Factors Configuration + Register +0x120 +0x20 +read-write +0x00000607 ++ ++ +BF1 +Blending Factor 1 +8 +3 ++ +BF2 +Blending Factor 2 +0 +3 ++ +L2CFBAR +L2CFBAR +Layerx Color Frame Buffer Address + Register +0x12C +0x20 +read-write +0x00000000 ++ ++ +CFBADD +Color Frame Buffer Start + Address +0 +32 ++ +L2CFBLR +L2CFBLR +Layerx Color Frame Buffer Length + Register +0x130 +0x20 +read-write +0x00000000 ++ ++ +CFBP +Color Frame Buffer Pitch in + bytes +16 +13 ++ +CFBLL +Color Frame Buffer Line + Length +0 +13 ++ +L2CFBLNR +L2CFBLNR +Layerx ColorFrame Buffer Line Number + Register +0x134 +0x20 +read-write +0x00000000 ++ ++ +CFBLNBR +Frame Buffer Line Number +0 +11 ++ +L2CLUTWR +L2CLUTWR +Layerx CLUT Write Register +0x144 +0x20 +write-only +0x00000000 ++ ++ +CLUTADD +CLUT Address +24 +8 ++ +RED +Red value +16 +8 ++ +GREEN +Green value +8 +8 ++ +BLUE +Blue value +0 +8 ++ +HASH +Hash processor +HASH +0x50060400 ++ +0x0 +0x400 +registers ++ +HASH_RNG +Hash and Rng global interrupt +80 ++ ++ +CR +CR +control register +0x0 +0x20 +0x00000000 ++ ++ +INIT +Initialize message digest + calculation +2 +1 +write-only ++ +DMAE +DMA enable +3 +1 +read-write ++ +DATATYPE +Data type selection +4 +2 +read-write ++ +MODE +Mode selection +6 +1 +read-write ++ +ALGO0 +Algorithm selection +7 +1 +read-write ++ +NBW +Number of words already + pushed +8 +4 +read-only ++ +DINNE +DIN not empty +12 +1 +read-only ++ +MDMAT +Multiple DMA Transfers +13 +1 +read-write ++ +LKEY +Long key selection +16 +1 +read-write ++ +ALGO1 +ALGO +18 +1 +read-write ++ +DIN +DIN +data input register +0x4 +0x20 +read-write +0x00000000 ++ ++ +DATAIN +Data input +0 +32 ++ +STR +STR +start register +0x8 +0x20 +0x00000000 ++ ++ +DCAL +Digest calculation +8 +1 +write-only ++ +NBLW +Number of valid bits in the last word of + the message +0 +5 +read-write ++ +HR0 +HR0 +digest registers +0xC +0x20 +read-only +0x00000000 ++ ++ +H0 +H0 +0 +32 ++ +HR1 +HR1 +digest registers +0x10 +0x20 +read-only +0x00000000 ++ ++ +H1 +H1 +0 +32 ++ +HR2 +HR2 +digest registers +0x14 +0x20 +read-only +0x00000000 ++ ++ +H2 +H2 +0 +32 ++ +HR3 +HR3 +digest registers +0x18 +0x20 +read-only +0x00000000 ++ ++ +H3 +H3 +0 +32 ++ +HR4 +HR4 +digest registers +0x1C +0x20 +read-only +0x00000000 ++ ++ +H4 +H4 +0 +32 ++ +IMR +IMR +interrupt enable register +0x20 +0x20 +read-write +0x00000000 ++ ++ +DCIE +Digest calculation completion interrupt + enable +1 +1 ++ +DINIE +Data input interrupt + enable +0 +1 ++ +SR +SR +status register +0x24 +0x20 +0x00000001 ++ ++ +BUSY +Busy bit +3 +1 +read-only ++ +DMAS +DMA Status +2 +1 +read-only ++ +DCIS +Digest calculation completion interrupt + status +1 +1 +read-write ++ +DINIS +Data input interrupt + status +0 +1 +read-write ++ +CSR0 +CSR0 +context swap registers +0xF8 +0x20 +read-write +0x00000000 ++ ++ +CSR0 +CSR0 +0 +32 ++ +CSR1 +CSR1 +context swap registers +0xFC +0x20 +read-write +0x00000000 ++ ++ +CSR1 +CSR1 +0 +32 ++ +CSR2 +CSR2 +context swap registers +0x100 +0x20 +read-write +0x00000000 ++ ++ +CSR2 +CSR2 +0 +32 ++ +CSR3 +CSR3 +context swap registers +0x104 +0x20 +read-write +0x00000000 ++ ++ +CSR3 +CSR3 +0 +32 ++ +CSR4 +CSR4 +context swap registers +0x108 +0x20 +read-write +0x00000000 ++ ++ +CSR4 +CSR4 +0 +32 ++ +CSR5 +CSR5 +context swap registers +0x10C +0x20 +read-write +0x00000000 ++ ++ +CSR5 +CSR5 +0 +32 ++ +CSR6 +CSR6 +context swap registers +0x110 +0x20 +read-write +0x00000000 ++ ++ +CSR6 +CSR6 +0 +32 ++ +CSR7 +CSR7 +context swap registers +0x114 +0x20 +read-write +0x00000000 ++ ++ +CSR7 +CSR7 +0 +32 ++ +CSR8 +CSR8 +context swap registers +0x118 +0x20 +read-write +0x00000000 ++ ++ +CSR8 +CSR8 +0 +32 ++ +CSR9 +CSR9 +context swap registers +0x11C +0x20 +read-write +0x00000000 ++ ++ +CSR9 +CSR9 +0 +32 ++ +CSR10 +CSR10 +context swap registers +0x120 +0x20 +read-write +0x00000000 ++ ++ +CSR10 +CSR10 +0 +32 ++ +CSR11 +CSR11 +context swap registers +0x124 +0x20 +read-write +0x00000000 ++ ++ +CSR11 +CSR11 +0 +32 ++ +CSR12 +CSR12 +context swap registers +0x128 +0x20 +read-write +0x00000000 ++ ++ +CSR12 +CSR12 +0 +32 ++ +CSR13 +CSR13 +context swap registers +0x12C +0x20 +read-write +0x00000000 ++ ++ +CSR13 +CSR13 +0 +32 ++ +CSR14 +CSR14 +context swap registers +0x130 +0x20 +read-write +0x00000000 ++ ++ +CSR14 +CSR14 +0 +32 ++ +CSR15 +CSR15 +context swap registers +0x134 +0x20 +read-write +0x00000000 ++ ++ +CSR15 +CSR15 +0 +32 ++ +CSR16 +CSR16 +context swap registers +0x138 +0x20 +read-write +0x00000000 ++ ++ +CSR16 +CSR16 +0 +32 ++ +CSR17 +CSR17 +context swap registers +0x13C +0x20 +read-write +0x00000000 ++ ++ +CSR17 +CSR17 +0 +32 ++ +CSR18 +CSR18 +context swap registers +0x140 +0x20 +read-write +0x00000000 ++ ++ +CSR18 +CSR18 +0 +32 ++ +CSR19 +CSR19 +context swap registers +0x144 +0x20 +read-write +0x00000000 ++ ++ +CSR19 +CSR19 +0 +32 ++ +CSR20 +CSR20 +context swap registers +0x148 +0x20 +read-write +0x00000000 ++ ++ +CSR20 +CSR20 +0 +32 ++ +CSR21 +CSR21 +context swap registers +0x14C +0x20 +read-write +0x00000000 ++ ++ +CSR21 +CSR21 +0 +32 ++ +CSR22 +CSR22 +context swap registers +0x150 +0x20 +read-write +0x00000000 ++ ++ +CSR22 +CSR22 +0 +32 ++ +CSR23 +CSR23 +context swap registers +0x154 +0x20 +read-write +0x00000000 ++ ++ +CSR23 +CSR23 +0 +32 ++ +CSR24 +CSR24 +context swap registers +0x158 +0x20 +read-write +0x00000000 ++ ++ +CSR24 +CSR24 +0 +32 ++ +CSR25 +CSR25 +context swap registers +0x15C +0x20 +read-write +0x00000000 ++ ++ +CSR25 +CSR25 +0 +32 ++ +CSR26 +CSR26 +context swap registers +0x160 +0x20 +read-write +0x00000000 ++ ++ +CSR26 +CSR26 +0 +32 ++ +CSR27 +CSR27 +context swap registers +0x164 +0x20 +read-write +0x00000000 ++ ++ +CSR27 +CSR27 +0 +32 ++ +CSR28 +CSR28 +context swap registers +0x168 +0x20 +read-write +0x00000000 ++ ++ +CSR28 +CSR28 +0 +32 ++ +CSR29 +CSR29 +context swap registers +0x16C +0x20 +read-write +0x00000000 ++ ++ +CSR29 +CSR29 +0 +32 ++ +CSR30 +CSR30 +context swap registers +0x170 +0x20 +read-write +0x00000000 ++ ++ +CSR30 +CSR30 +0 +32 ++ +CSR31 +CSR31 +context swap registers +0x174 +0x20 +read-write +0x00000000 ++ ++ +CSR31 +CSR31 +0 +32 ++ +CSR32 +CSR32 +context swap registers +0x178 +0x20 +read-write +0x00000000 ++ ++ +CSR32 +CSR32 +0 +32 ++ +CSR33 +CSR33 +context swap registers +0x17C +0x20 +read-write +0x00000000 ++ ++ +CSR33 +CSR33 +0 +32 ++ +CSR34 +CSR34 +context swap registers +0x180 +0x20 +read-write +0x00000000 ++ ++ +CSR34 +CSR34 +0 +32 ++ +CSR35 +CSR35 +context swap registers +0x184 +0x20 +read-write +0x00000000 ++ ++ +CSR35 +CSR35 +0 +32 ++ +CSR36 +CSR36 +context swap registers +0x188 +0x20 +read-write +0x00000000 ++ ++ +CSR36 +CSR36 +0 +32 ++ +CSR37 +CSR37 +context swap registers +0x18C +0x20 +read-write +0x00000000 ++ ++ +CSR37 +CSR37 +0 +32 ++ +CSR38 +CSR38 +context swap registers +0x190 +0x20 +read-write +0x00000000 ++ ++ +CSR38 +CSR38 +0 +32 ++ +CSR39 +CSR39 +context swap registers +0x194 +0x20 +read-write +0x00000000 ++ ++ +CSR39 +CSR39 +0 +32 ++ +CSR40 +CSR40 +context swap registers +0x198 +0x20 +read-write +0x00000000 ++ ++ +CSR40 +CSR40 +0 +32 ++ +CSR41 +CSR41 +context swap registers +0x19C +0x20 +read-write +0x00000000 ++ ++ +CSR41 +CSR41 +0 +32 ++ +CSR42 +CSR42 +context swap registers +0x1A0 +0x20 +read-write +0x00000000 ++ ++ +CSR42 +CSR42 +0 +32 ++ +CSR43 +CSR43 +context swap registers +0x1A4 +0x20 +read-write +0x00000000 ++ ++ +CSR43 +CSR43 +0 +32 ++ +CSR44 +CSR44 +context swap registers +0x1A8 +0x20 +read-write +0x00000000 ++ ++ +CSR44 +CSR44 +0 +32 ++ +CSR45 +CSR45 +context swap registers +0x1AC +0x20 +read-write +0x00000000 ++ ++ +CSR45 +CSR45 +0 +32 ++ +CSR46 +CSR46 +context swap registers +0x1B0 +0x20 +read-write +0x00000000 ++ ++ +CSR46 +CSR46 +0 +32 ++ +CSR47 +CSR47 +context swap registers +0x1B4 +0x20 +read-write +0x00000000 ++ ++ +CSR47 +CSR47 +0 +32 ++ +CSR48 +CSR48 +context swap registers +0x1B8 +0x20 +read-write +0x00000000 ++ ++ +CSR48 +CSR48 +0 +32 ++ +CSR49 +CSR49 +context swap registers +0x1BC +0x20 +read-write +0x00000000 ++ ++ +CSR49 +CSR49 +0 +32 ++ +CSR50 +CSR50 +context swap registers +0x1C0 +0x20 +read-write +0x00000000 ++ ++ +CSR50 +CSR50 +0 +32 ++ +CSR51 +CSR51 +context swap registers +0x1C4 +0x20 +read-write +0x00000000 ++ ++ +CSR51 +CSR51 +0 +32 ++ +CSR52 +CSR52 +context swap registers +0x1C8 +0x20 +read-write +0x00000000 ++ ++ +CSR52 +CSR52 +0 +32 ++ +CSR53 +CSR53 +context swap registers +0x1CC +0x20 +read-write +0x00000000 ++ ++ +CSR53 +CSR53 +0 +32 ++ +HASH_HR0 +HASH_HR0 +HASH digest register +0x310 +0x20 +read-only +0x00000000 ++ ++ +H0 +H0 +0 +32 ++ +HASH_HR1 +HASH_HR1 +read-only +0x314 +0x20 +read-only +0x00000000 ++ ++ +H1 +H1 +0 +32 ++ +HASH_HR2 +HASH_HR2 +read-only +0x318 +0x20 +read-only +0x00000000 ++ ++ +H2 +H2 +0 +32 ++ +HASH_HR3 +HASH_HR3 +read-only +0x31C +0x20 +read-only +0x00000000 ++ ++ +H3 +H3 +0 +32 ++ +HASH_HR4 +HASH_HR4 +read-only +0x320 +0x20 +read-only +0x00000000 ++ ++ +H4 +H4 +0 +32 ++ +HASH_HR5 +HASH_HR5 +read-only +0x324 +0x20 +read-only +0x00000000 ++ ++ +H5 +H5 +0 +32 ++ +HASH_HR6 +HASH_HR6 +read-only +0x328 +0x20 +read-only +0x00000000 ++ ++ +H6 +H6 +0 +32 ++ +HASH_HR7 +HASH_HR7 +read-only +0x32C +0x20 +read-only +0x00000000 ++ ++ +H7 +H7 +0 +32 ++ +CRYP +Cryptographic processor +CRYP +0x50060000 ++ +0x0 +0x400 +registers ++ +CRYP +CRYP crypto global interrupt +79 ++ ++ +CR +CR +control register +0x0 +0x20 +0x00000000 ++ ++ +ALGODIR +Algorithm direction +2 +1 +read-write ++ +ALGOMODE0 +Algorithm mode +3 +3 +read-write ++ +DATATYPE +Data type selection +6 +2 +read-write ++ +KEYSIZE +Key size selection (AES mode + only) +8 +2 +read-write ++ +FFLUSH +FIFO flush +14 +1 +write-only ++ +CRYPEN +Cryptographic processor + enable +15 +1 +read-write ++ +GCM_CCMPH +GCM_CCMPH +16 +2 +read-write ++ +ALGOMODE3 +ALGOMODE +19 +1 +read-write ++ +SR +SR +status register +0x4 +0x20 +read-only +0x00000003 ++ ++ +BUSY +Busy bit +4 +1 ++ +OFFU +Output FIFO full +3 +1 ++ +OFNE +Output FIFO not empty +2 +1 ++ +IFNF +Input FIFO not full +1 +1 ++ +IFEM +Input FIFO empty +0 +1 ++ +DIN +DIN +data input register +0x8 +0x20 +read-write +0x00000000 ++ ++ +DATAIN +Data input +0 +32 ++ +DOUT +DOUT +data output register +0xC +0x20 +read-only +0x00000000 ++ ++ +DATAOUT +Data output +0 +32 ++ +DMACR +DMACR +DMA control register +0x10 +0x20 +read-write +0x00000000 ++ ++ +DOEN +DMA output enable +1 +1 ++ +DIEN +DMA input enable +0 +1 ++ +IMSCR +IMSCR +interrupt mask set/clear + register +0x14 +0x20 +read-write +0x00000000 ++ ++ +OUTIM +Output FIFO service interrupt + mask +1 +1 ++ +INIM +Input FIFO service interrupt + mask +0 +1 ++ +RISR +RISR +raw interrupt status register +0x18 +0x20 +read-only +0x00000001 ++ ++ +OUTRIS +Output FIFO service raw interrupt + status +1 +1 ++ +INRIS +Input FIFO service raw interrupt + status +0 +1 ++ +MISR +MISR +masked interrupt status + register +0x1C +0x20 +read-only +0x00000000 ++ ++ +OUTMIS +Output FIFO service masked interrupt + status +1 +1 ++ +INMIS +Input FIFO service masked interrupt + status +0 +1 ++ +K0LR +K0LR +key registers +0x20 +0x20 +write-only +0x00000000 ++ ++ +b224 +b224 +0 +1 ++ +b225 +b225 +1 +1 ++ +b226 +b226 +2 +1 ++ +b227 +b227 +3 +1 ++ +b228 +b228 +4 +1 ++ +b229 +b229 +5 +1 ++ +b230 +b230 +6 +1 ++ +b231 +b231 +7 +1 ++ +b232 +b232 +8 +1 ++ +b233 +b233 +9 +1 ++ +b234 +b234 +10 +1 ++ +b235 +b235 +11 +1 ++ +b236 +b236 +12 +1 ++ +b237 +b237 +13 +1 ++ +b238 +b238 +14 +1 ++ +b239 +b239 +15 +1 ++ +b240 +b240 +16 +1 ++ +b241 +b241 +17 +1 ++ +b242 +b242 +18 +1 ++ +b243 +b243 +19 +1 ++ +b244 +b244 +20 +1 ++ +b245 +b245 +21 +1 ++ +b246 +b246 +22 +1 ++ +b247 +b247 +23 +1 ++ +b248 +b248 +24 +1 ++ +b249 +b249 +25 +1 ++ +b250 +b250 +26 +1 ++ +b251 +b251 +27 +1 ++ +b252 +b252 +28 +1 ++ +b253 +b253 +29 +1 ++ +b254 +b254 +30 +1 ++ +b255 +b255 +31 +1 ++ +K0RR +K0RR +key registers +0x24 +0x20 +write-only +0x00000000 ++ ++ +b192 +b192 +0 +1 ++ +b193 +b193 +1 +1 ++ +b194 +b194 +2 +1 ++ +b195 +b195 +3 +1 ++ +b196 +b196 +4 +1 ++ +b197 +b197 +5 +1 ++ +b198 +b198 +6 +1 ++ +b199 +b199 +7 +1 ++ +b200 +b200 +8 +1 ++ +b201 +b201 +9 +1 ++ +b202 +b202 +10 +1 ++ +b203 +b203 +11 +1 ++ +b204 +b204 +12 +1 ++ +b205 +b205 +13 +1 ++ +b206 +b206 +14 +1 ++ +b207 +b207 +15 +1 ++ +b208 +b208 +16 +1 ++ +b209 +b209 +17 +1 ++ +b210 +b210 +18 +1 ++ +b211 +b211 +19 +1 ++ +b212 +b212 +20 +1 ++ +b213 +b213 +21 +1 ++ +b214 +b214 +22 +1 ++ +b215 +b215 +23 +1 ++ +b216 +b216 +24 +1 ++ +b217 +b217 +25 +1 ++ +b218 +b218 +26 +1 ++ +b219 +b219 +27 +1 ++ +b220 +b220 +28 +1 ++ +b221 +b221 +29 +1 ++ +b222 +b222 +30 +1 ++ +b223 +b223 +31 +1 ++ +K1LR +K1LR +key registers +0x28 +0x20 +write-only +0x00000000 ++ ++ +b160 +b160 +0 +1 ++ +b161 +b161 +1 +1 ++ +b162 +b162 +2 +1 ++ +b163 +b163 +3 +1 ++ +b164 +b164 +4 +1 ++ +b165 +b165 +5 +1 ++ +b166 +b166 +6 +1 ++ +b167 +b167 +7 +1 ++ +b168 +b168 +8 +1 ++ +b169 +b169 +9 +1 ++ +b170 +b170 +10 +1 ++ +b171 +b171 +11 +1 ++ +b172 +b172 +12 +1 ++ +b173 +b173 +13 +1 ++ +b174 +b174 +14 +1 ++ +b175 +b175 +15 +1 ++ +b176 +b176 +16 +1 ++ +b177 +b177 +17 +1 ++ +b178 +b178 +18 +1 ++ +b179 +b179 +19 +1 ++ +b180 +b180 +20 +1 ++ +b181 +b181 +21 +1 ++ +b182 +b182 +22 +1 ++ +b183 +b183 +23 +1 ++ +b184 +b184 +24 +1 ++ +b185 +b185 +25 +1 ++ +b186 +b186 +26 +1 ++ +b187 +b187 +27 +1 ++ +b188 +b188 +28 +1 ++ +b189 +b189 +29 +1 ++ +b190 +b190 +30 +1 ++ +b191 +b191 +31 +1 ++ +K1RR +K1RR +key registers +0x2C +0x20 +write-only +0x00000000 ++ ++ +b128 +b128 +0 +1 ++ +b129 +b129 +1 +1 ++ +b130 +b130 +2 +1 ++ +b131 +b131 +3 +1 ++ +b132 +b132 +4 +1 ++ +b133 +b133 +5 +1 ++ +b134 +b134 +6 +1 ++ +b135 +b135 +7 +1 ++ +b136 +b136 +8 +1 ++ +b137 +b137 +9 +1 ++ +b138 +b138 +10 +1 ++ +b139 +b139 +11 +1 ++ +b140 +b140 +12 +1 ++ +b141 +b141 +13 +1 ++ +b142 +b142 +14 +1 ++ +b143 +b143 +15 +1 ++ +b144 +b144 +16 +1 ++ +b145 +b145 +17 +1 ++ +b146 +b146 +18 +1 ++ +b147 +b147 +19 +1 ++ +b148 +b148 +20 +1 ++ +b149 +b149 +21 +1 ++ +b150 +b150 +22 +1 ++ +b151 +b151 +23 +1 ++ +b152 +b152 +24 +1 ++ +b153 +b153 +25 +1 ++ +b154 +b154 +26 +1 ++ +b155 +b155 +27 +1 ++ +b156 +b156 +28 +1 ++ +b157 +b157 +29 +1 ++ +b158 +b158 +30 +1 ++ +b159 +b159 +31 +1 ++ +K2LR +K2LR +key registers +0x30 +0x20 +write-only +0x00000000 ++ ++ +b96 +b96 +0 +1 ++ +b97 +b97 +1 +1 ++ +b98 +b98 +2 +1 ++ +b99 +b99 +3 +1 ++ +b100 +b100 +4 +1 ++ +b101 +b101 +5 +1 ++ +b102 +b102 +6 +1 ++ +b103 +b103 +7 +1 ++ +b104 +b104 +8 +1 ++ +b105 +b105 +9 +1 ++ +b106 +b106 +10 +1 ++ +b107 +b107 +11 +1 ++ +b108 +b108 +12 +1 ++ +b109 +b109 +13 +1 ++ +b110 +b110 +14 +1 ++ +b111 +b111 +15 +1 ++ +b112 +b112 +16 +1 ++ +b113 +b113 +17 +1 ++ +b114 +b114 +18 +1 ++ +b115 +b115 +19 +1 ++ +b116 +b116 +20 +1 ++ +b117 +b117 +21 +1 ++ +b118 +b118 +22 +1 ++ +b119 +b119 +23 +1 ++ +b120 +b120 +24 +1 ++ +b121 +b121 +25 +1 ++ +b122 +b122 +26 +1 ++ +b123 +b123 +27 +1 ++ +b124 +b124 +28 +1 ++ +b125 +b125 +29 +1 ++ +b126 +b126 +30 +1 ++ +b127 +b127 +31 +1 ++ +K2RR +K2RR +key registers +0x34 +0x20 +write-only +0x00000000 ++ ++ +b64 +b64 +0 +1 ++ +b65 +b65 +1 +1 ++ +b66 +b66 +2 +1 ++ +b67 +b67 +3 +1 ++ +b68 +b68 +4 +1 ++ +b69 +b69 +5 +1 ++ +b70 +b70 +6 +1 ++ +b71 +b71 +7 +1 ++ +b72 +b72 +8 +1 ++ +b73 +b73 +9 +1 ++ +b74 +b74 +10 +1 ++ +b75 +b75 +11 +1 ++ +b76 +b76 +12 +1 ++ +b77 +b77 +13 +1 ++ +b78 +b78 +14 +1 ++ +b79 +b79 +15 +1 ++ +b80 +b80 +16 +1 ++ +b81 +b81 +17 +1 ++ +b82 +b82 +18 +1 ++ +b83 +b83 +19 +1 ++ +b84 +b84 +20 +1 ++ +b85 +b85 +21 +1 ++ +b86 +b86 +22 +1 ++ +b87 +b87 +23 +1 ++ +b88 +b88 +24 +1 ++ +b89 +b89 +25 +1 ++ +b90 +b90 +26 +1 ++ +b91 +b91 +27 +1 ++ +b92 +b92 +28 +1 ++ +b93 +b93 +29 +1 ++ +b94 +b94 +30 +1 ++ +b95 +b95 +31 +1 ++ +K3LR +K3LR +key registers +0x38 +0x20 +write-only +0x00000000 ++ ++ +b32 +b32 +0 +1 ++ +b33 +b33 +1 +1 ++ +b34 +b34 +2 +1 ++ +b35 +b35 +3 +1 ++ +b36 +b36 +4 +1 ++ +b37 +b37 +5 +1 ++ +b38 +b38 +6 +1 ++ +b39 +b39 +7 +1 ++ +b40 +b40 +8 +1 ++ +b41 +b41 +9 +1 ++ +b42 +b42 +10 +1 ++ +b43 +b43 +11 +1 ++ +b44 +b44 +12 +1 ++ +b45 +b45 +13 +1 ++ +b46 +b46 +14 +1 ++ +b47 +b47 +15 +1 ++ +b48 +b48 +16 +1 ++ +b49 +b49 +17 +1 ++ +b50 +b50 +18 +1 ++ +b51 +b51 +19 +1 ++ +b52 +b52 +20 +1 ++ +b53 +b53 +21 +1 ++ +b54 +b54 +22 +1 ++ +b55 +b55 +23 +1 ++ +b56 +b56 +24 +1 ++ +b57 +b57 +25 +1 ++ +b58 +b58 +26 +1 ++ +b59 +b59 +27 +1 ++ +b60 +b60 +28 +1 ++ +b61 +b61 +29 +1 ++ +b62 +b62 +30 +1 ++ +b63 +b63 +31 +1 ++ +K3RR +K3RR +key registers +0x3C +0x20 +write-only +0x00000000 ++ ++ +b0 +b0 +0 +1 ++ +b1 +b1 +1 +1 ++ +b2 +b2 +2 +1 ++ +b3 +b3 +3 +1 ++ +b4 +b4 +4 +1 ++ +b5 +b5 +5 +1 ++ +b6 +b6 +6 +1 ++ +b7 +b7 +7 +1 ++ +b8 +b8 +8 +1 ++ +b9 +b9 +9 +1 ++ +b10 +b10 +10 +1 ++ +b11 +b11 +11 +1 ++ +b12 +b12 +12 +1 ++ +b13 +b13 +13 +1 ++ +b14 +b14 +14 +1 ++ +b15 +b15 +15 +1 ++ +b16 +b16 +16 +1 ++ +b17 +b17 +17 +1 ++ +b18 +b18 +18 +1 ++ +b19 +b19 +19 +1 ++ +b20 +b20 +20 +1 ++ +b21 +b21 +21 +1 ++ +b22 +b22 +22 +1 ++ +b23 +b23 +23 +1 ++ +b24 +b24 +24 +1 ++ +b25 +b25 +25 +1 ++ +b26 +b26 +26 +1 ++ +b27 +b27 +27 +1 ++ +b28 +b28 +28 +1 ++ +b29 +b29 +29 +1 ++ +b30 +b30 +30 +1 ++ +b31 +b31 +31 +1 ++ +IV0LR +IV0LR +initialization vector + registers +0x40 +0x20 +read-write +0x00000000 ++ ++ +IV31 +IV31 +0 +1 ++ +IV30 +IV30 +1 +1 ++ +IV29 +IV29 +2 +1 ++ +IV28 +IV28 +3 +1 ++ +IV27 +IV27 +4 +1 ++ +IV26 +IV26 +5 +1 ++ +IV25 +IV25 +6 +1 ++ +IV24 +IV24 +7 +1 ++ +IV23 +IV23 +8 +1 ++ +IV22 +IV22 +9 +1 ++ +IV21 +IV21 +10 +1 ++ +IV20 +IV20 +11 +1 ++ +IV19 +IV19 +12 +1 ++ +IV18 +IV18 +13 +1 ++ +IV17 +IV17 +14 +1 ++ +IV16 +IV16 +15 +1 ++ +IV15 +IV15 +16 +1 ++ +IV14 +IV14 +17 +1 ++ +IV13 +IV13 +18 +1 ++ +IV12 +IV12 +19 +1 ++ +IV11 +IV11 +20 +1 ++ +IV10 +IV10 +21 +1 ++ +IV9 +IV9 +22 +1 ++ +IV8 +IV8 +23 +1 ++ +IV7 +IV7 +24 +1 ++ +IV6 +IV6 +25 +1 ++ +IV5 +IV5 +26 +1 ++ +IV4 +IV4 +27 +1 ++ +IV3 +IV3 +28 +1 ++ +IV2 +IV2 +29 +1 ++ +IV1 +IV1 +30 +1 ++ +IV0 +IV0 +31 +1 ++ +IV0RR +IV0RR +initialization vector + registers +0x44 +0x20 +read-write +0x00000000 ++ ++ +IV63 +IV63 +0 +1 ++ +IV62 +IV62 +1 +1 ++ +IV61 +IV61 +2 +1 ++ +IV60 +IV60 +3 +1 ++ +IV59 +IV59 +4 +1 ++ +IV58 +IV58 +5 +1 ++ +IV57 +IV57 +6 +1 ++ +IV56 +IV56 +7 +1 ++ +IV55 +IV55 +8 +1 ++ +IV54 +IV54 +9 +1 ++ +IV53 +IV53 +10 +1 ++ +IV52 +IV52 +11 +1 ++ +IV51 +IV51 +12 +1 ++ +IV50 +IV50 +13 +1 ++ +IV49 +IV49 +14 +1 ++ +IV48 +IV48 +15 +1 ++ +IV47 +IV47 +16 +1 ++ +IV46 +IV46 +17 +1 ++ +IV45 +IV45 +18 +1 ++ +IV44 +IV44 +19 +1 ++ +IV43 +IV43 +20 +1 ++ +IV42 +IV42 +21 +1 ++ +IV41 +IV41 +22 +1 ++ +IV40 +IV40 +23 +1 ++ +IV39 +IV39 +24 +1 ++ +IV38 +IV38 +25 +1 ++ +IV37 +IV37 +26 +1 ++ +IV36 +IV36 +27 +1 ++ +IV35 +IV35 +28 +1 ++ +IV34 +IV34 +29 +1 ++ +IV33 +IV33 +30 +1 ++ +IV32 +IV32 +31 +1 ++ +IV1LR +IV1LR +initialization vector + registers +0x48 +0x20 +read-write +0x00000000 ++ ++ +IV95 +IV95 +0 +1 ++ +IV94 +IV94 +1 +1 ++ +IV93 +IV93 +2 +1 ++ +IV92 +IV92 +3 +1 ++ +IV91 +IV91 +4 +1 ++ +IV90 +IV90 +5 +1 ++ +IV89 +IV89 +6 +1 ++ +IV88 +IV88 +7 +1 ++ +IV87 +IV87 +8 +1 ++ +IV86 +IV86 +9 +1 ++ +IV85 +IV85 +10 +1 ++ +IV84 +IV84 +11 +1 ++ +IV83 +IV83 +12 +1 ++ +IV82 +IV82 +13 +1 ++ +IV81 +IV81 +14 +1 ++ +IV80 +IV80 +15 +1 ++ +IV79 +IV79 +16 +1 ++ +IV78 +IV78 +17 +1 ++ +IV77 +IV77 +18 +1 ++ +IV76 +IV76 +19 +1 ++ +IV75 +IV75 +20 +1 ++ +IV74 +IV74 +21 +1 ++ +IV73 +IV73 +22 +1 ++ +IV72 +IV72 +23 +1 ++ +IV71 +IV71 +24 +1 ++ +IV70 +IV70 +25 +1 ++ +IV69 +IV69 +26 +1 ++ +IV68 +IV68 +27 +1 ++ +IV67 +IV67 +28 +1 ++ +IV66 +IV66 +29 +1 ++ +IV65 +IV65 +30 +1 ++ +IV64 +IV64 +31 +1 ++ +IV1RR +IV1RR +initialization vector + registers +0x4C +0x20 +read-write +0x00000000 ++ ++ +IV127 +IV127 +0 +1 ++ +IV126 +IV126 +1 +1 ++ +IV125 +IV125 +2 +1 ++ +IV124 +IV124 +3 +1 ++ +IV123 +IV123 +4 +1 ++ +IV122 +IV122 +5 +1 ++ +IV121 +IV121 +6 +1 ++ +IV120 +IV120 +7 +1 ++ +IV119 +IV119 +8 +1 ++ +IV118 +IV118 +9 +1 ++ +IV117 +IV117 +10 +1 ++ +IV116 +IV116 +11 +1 ++ +IV115 +IV115 +12 +1 ++ +IV114 +IV114 +13 +1 ++ +IV113 +IV113 +14 +1 ++ +IV112 +IV112 +15 +1 ++ +IV111 +IV111 +16 +1 ++ +IV110 +IV110 +17 +1 ++ +IV109 +IV109 +18 +1 ++ +IV108 +IV108 +19 +1 ++ +IV107 +IV107 +20 +1 ++ +IV106 +IV106 +21 +1 ++ +IV105 +IV105 +22 +1 ++ +IV104 +IV104 +23 +1 ++ +IV103 +IV103 +24 +1 ++ +IV102 +IV102 +25 +1 ++ +IV101 +IV101 +26 +1 ++ +IV100 +IV100 +27 +1 ++ +IV99 +IV99 +28 +1 ++ +IV98 +IV98 +29 +1 ++ +IV97 +IV97 +30 +1 ++ +IV96 +IV96 +31 +1 ++ +CSGCMCCM0R +CSGCMCCM0R +context swap register +0x50 +0x20 +read-write +0x00000000 ++ ++ +CSGCMCCM0R +CSGCMCCM0R +0 +32 ++ +CSGCMCCM1R +CSGCMCCM1R +context swap register +0x54 +0x20 +read-write +0x00000000 ++ ++ +CSGCMCCM1R +CSGCMCCM1R +0 +32 ++ +CSGCMCCM2R +CSGCMCCM2R +context swap register +0x58 +0x20 +read-write +0x00000000 ++ ++ +CSGCMCCM2R +CSGCMCCM2R +0 +32 ++ +CSGCMCCM3R +CSGCMCCM3R +context swap register +0x5C +0x20 +read-write +0x00000000 ++ ++ +CSGCMCCM3R +CSGCMCCM3R +0 +32 ++ +CSGCMCCM4R +CSGCMCCM4R +context swap register +0x60 +0x20 +read-write +0x00000000 ++ ++ +CSGCMCCM4R +CSGCMCCM4R +0 +32 ++ +CSGCMCCM5R +CSGCMCCM5R +context swap register +0x64 +0x20 +read-write +0x00000000 ++ ++ +CSGCMCCM5R +CSGCMCCM5R +0 +32 ++ +CSGCMCCM6R +CSGCMCCM6R +context swap register +0x68 +0x20 +read-write +0x00000000 ++ ++ +CSGCMCCM6R +CSGCMCCM6R +0 +32 ++ +CSGCMCCM7R +CSGCMCCM7R +context swap register +0x6C +0x20 +read-write +0x00000000 ++ ++ +CSGCMCCM7R +CSGCMCCM7R +0 +32 ++ +CSGCM0R +CSGCM0R +context swap register +0x70 +0x20 +read-write +0x00000000 ++ ++ +CSGCM0R +CSGCM0R +0 +32 ++ +CSGCM1R +CSGCM1R +context swap register +0x74 +0x20 +read-write +0x00000000 ++ ++ +CSGCM1R +CSGCM1R +0 +32 ++ +CSGCM2R +CSGCM2R +context swap register +0x78 +0x20 +read-write +0x00000000 ++ ++ +CSGCM2R +CSGCM2R +0 +32 ++ +CSGCM3R +CSGCM3R +context swap register +0x7C +0x20 +read-write +0x00000000 ++ ++ +CSGCM3R +CSGCM3R +0 +32 ++ +CSGCM4R +CSGCM4R +context swap register +0x80 +0x20 +read-write +0x00000000 ++ ++ +CSGCM4R +CSGCM4R +0 +32 ++ +CSGCM5R +CSGCM5R +context swap register +0x84 +0x20 +read-write +0x00000000 ++ ++ +CSGCM5R +CSGCM5R +0 +32 ++ +CSGCM6R +CSGCM6R +context swap register +0x88 +0x20 +read-write +0x00000000 ++ ++ +CSGCM6R +CSGCM6R +0 +32 ++ +CSGCM7R +CSGCM7R +context swap register +0x8C +0x20 +read-write +0x00000000 ++ ++ +CSGCM7R +CSGCM7R +0 +32 ++ +FPU +Floting point unit +FPU +0xE000EF34 ++ +0x0 +0xD +registers ++ +FPU +Floating point unit interrupt +81 ++ +FPU +Floating point interrupt +81 ++ ++ +FPCCR +FPCCR +Floating-point context control + register +0x0 +0x20 +read-write +0x00000000 ++ ++ +LSPACT +LSPACT +0 +1 ++ +USER +USER +1 +1 ++ +THREAD +THREAD +3 +1 ++ +HFRDY +HFRDY +4 +1 ++ +MMRDY +MMRDY +5 +1 ++ +BFRDY +BFRDY +6 +1 ++ +MONRDY +MONRDY +8 +1 ++ +LSPEN +LSPEN +30 +1 ++ +ASPEN +ASPEN +31 +1 ++ +FPCAR +FPCAR +Floating-point context address + register +0x4 +0x20 +read-write +0x00000000 ++ ++ +ADDRESS +Location of unpopulated + floating-point +3 +29 ++ +FPSCR +FPSCR +Floating-point status control + register +0x8 +0x20 +read-write +0x00000000 ++ ++ +IOC +Invalid operation cumulative exception + bit +0 +1 ++ +DZC +Division by zero cumulative exception + bit. +1 +1 ++ +OFC +Overflow cumulative exception + bit +2 +1 ++ +UFC +Underflow cumulative exception + bit +3 +1 ++ +IXC +Inexact cumulative exception + bit +4 +1 ++ +IDC +Input denormal cumulative exception + bit. +7 +1 ++ +RMode +Rounding Mode control + field +22 +2 ++ +FZ +Flush-to-zero mode control + bit: +24 +1 ++ +DN +Default NaN mode control + bit +25 +1 ++ +AHP +Alternative half-precision control + bit +26 +1 ++ +V +Overflow condition code + flag +28 +1 ++ +C +Carry condition code flag +29 +1 ++ +Z +Zero condition code flag +30 +1 ++ +N +Negative condition code + flag +31 +1 ++ +MPU +Memory protection unit +MPU +0xE000ED90 ++ +0x0 +0x15 +registers ++ ++ +MPU_TYPER +MPU_TYPER +MPU type register +0x0 +0x20 +read-only +0X00000800 ++ ++ +SEPARATE +Separate flag +0 +1 ++ +DREGION +Number of MPU data regions +8 +8 ++ +IREGION +Number of MPU instruction + regions +16 +8 ++ +MPU_CTRL +MPU_CTRL +MPU control register +0x4 +0x20 +read-only +0X00000000 ++ ++ +ENABLE +Enables the MPU +0 +1 ++ +HFNMIENA +Enables the operation of MPU during hard + fault +1 +1 ++ +PRIVDEFENA +Enable priviliged software access to + default memory map +2 +1 ++ +MPU_RNR +MPU_RNR +MPU region number register +0x8 +0x20 +read-write +0X00000000 ++ ++ +REGION +MPU region +0 +8 ++ +MPU_RBAR +MPU_RBAR +MPU region base address + register +0xC +0x20 +read-write +0X00000000 ++ ++ +REGION +MPU region field +0 +4 ++ +VALID +MPU region number valid +4 +1 ++ +ADDR +Region base address field +5 +27 ++ +MPU_RASR +MPU_RASR +MPU region attribute and size + register +0x10 +0x20 +read-write +0X00000000 ++ ++ +ENABLE +Region enable bit. +0 +1 ++ +SIZE +Size of the MPU protection + region +1 +5 ++ +SRD +Subregion disable bits +8 +8 ++ +B +memory attribute +16 +1 ++ +C +memory attribute +17 +1 ++ +S +Shareable memory attribute +18 +1 ++ +TEX +memory attribute +19 +3 ++ +AP +Access permission +24 +3 ++ +XN +Instruction access disable + bit +28 +1 ++ +STK +SysTick timer +STK +0xE000E010 ++ +0x0 +0x11 +registers ++ ++ +CTRL +CTRL +SysTick control and status + register +0x0 +0x20 +read-write +0X00000000 ++ ++ +ENABLE +Counter enable +0 +1 ++ +TICKINT +SysTick exception request + enable +1 +1 ++ +CLKSOURCE +Clock source selection +2 +1 ++ +COUNTFLAG +COUNTFLAG +16 +1 ++ +LOAD +LOAD +SysTick reload value register +0x4 +0x20 +read-write +0X00000000 ++ ++ +RELOAD +RELOAD value +0 +24 ++ +VAL +VAL +SysTick current value register +0x8 +0x20 +read-write +0X00000000 ++ ++ +CURRENT +Current counter value +0 +24 ++ +CALIB +CALIB +SysTick calibration value + register +0xC +0x20 +read-write +0X00000000 ++ ++ +TENMS +Calibration value +0 +24 ++ +SKEW +SKEW flag: Indicates whether the TENMS + value is exact +30 +1 ++ +NOREF +NOREF flag. Reads as zero +31 +1 ++ +SCB +System control block +SCB +0xE000ED00 ++ +0x0 +0x41 +registers ++ ++ +CPUID +CPUID +CPUID base register +0x0 +0x20 +read-only +0x410FC241 ++ ++ +Revision +Revision number +0 +4 ++ +PartNo +Part number of the + processor +4 +12 ++ +Constant +Reads as 0xF +16 +4 ++ +Variant +Variant number +20 +4 ++ +Implementer +Implementer code +24 +8 ++ +ICSR +ICSR +Interrupt control and state + register +0x4 +0x20 +read-write +0x00000000 ++ ++ +VECTACTIVE +Active vector +0 +9 ++ +RETTOBASE +Return to base level +11 +1 ++ +VECTPENDING +Pending vector +12 +7 ++ +ISRPENDING +Interrupt pending flag +22 +1 ++ +PENDSTCLR +SysTick exception clear-pending + bit +25 +1 ++ +PENDSTSET +SysTick exception set-pending + bit +26 +1 ++ +PENDSVCLR +PendSV clear-pending bit +27 +1 ++ +PENDSVSET +PendSV set-pending bit +28 +1 ++ +NMIPENDSET +NMI set-pending bit. +31 +1 ++ +VTOR +VTOR +Vector table offset register +0x8 +0x20 +read-write +0x00000000 ++ ++ +TBLOFF +Vector table base offset + field +9 +21 ++ +AIRCR +AIRCR +Application interrupt and reset control + register +0xC +0x20 +read-write +0x00000000 ++ ++ +VECTRESET +VECTRESET +0 +1 ++ +VECTCLRACTIVE +VECTCLRACTIVE +1 +1 ++ +SYSRESETREQ +SYSRESETREQ +2 +1 ++ +PRIGROUP +PRIGROUP +8 +3 ++ +ENDIANESS +ENDIANESS +15 +1 ++ +VECTKEYSTAT +Register key +16 +16 ++ +SCR +SCR +System control register +0x10 +0x20 +read-write +0x00000000 ++ ++ +SLEEPONEXIT +SLEEPONEXIT +1 +1 ++ +SLEEPDEEP +SLEEPDEEP +2 +1 ++ +SEVEONPEND +Send Event on Pending bit +4 +1 ++ +CCR +CCR +Configuration and control + register +0x14 +0x20 +read-write +0x00000000 ++ ++ +NONBASETHRDENA +Configures how the processor enters + Thread mode +0 +1 ++ +USERSETMPEND +USERSETMPEND +1 +1 ++ +UNALIGN__TRP +UNALIGN_ TRP +3 +1 ++ +DIV_0_TRP +DIV_0_TRP +4 +1 ++ +BFHFNMIGN +BFHFNMIGN +8 +1 ++ +STKALIGN +STKALIGN +9 +1 ++ +SHPR1 +SHPR1 +System handler priority + registers +0x18 +0x20 +read-write +0x00000000 ++ ++ +PRI_4 +Priority of system handler + 4 +0 +8 ++ +PRI_5 +Priority of system handler + 5 +8 +8 ++ +PRI_6 +Priority of system handler + 6 +16 +8 ++ +SHPR2 +SHPR2 +System handler priority + registers +0x1C +0x20 +read-write +0x00000000 ++ ++ +PRI_11 +Priority of system handler + 11 +24 +8 ++ +SHPR3 +SHPR3 +System handler priority + registers +0x20 +0x20 +read-write +0x00000000 ++ ++ +PRI_14 +Priority of system handler + 14 +16 +8 ++ +PRI_15 +Priority of system handler + 15 +24 +8 ++ +SHCRS +SHCRS +System handler control and state + register +0x24 +0x20 +read-write +0x00000000 ++ ++ +MEMFAULTACT +Memory management fault exception active + bit +0 +1 ++ +BUSFAULTACT +Bus fault exception active + bit +1 +1 ++ +USGFAULTACT +Usage fault exception active + bit +3 +1 ++ +SVCALLACT +SVC call active bit +7 +1 ++ +MONITORACT +Debug monitor active bit +8 +1 ++ +PENDSVACT +PendSV exception active + bit +10 +1 ++ +SYSTICKACT +SysTick exception active + bit +11 +1 ++ +USGFAULTPENDED +Usage fault exception pending + bit +12 +1 ++ +MEMFAULTPENDED +Memory management fault exception + pending bit +13 +1 ++ +BUSFAULTPENDED +Bus fault exception pending + bit +14 +1 ++ +SVCALLPENDED +SVC call pending bit +15 +1 ++ +MEMFAULTENA +Memory management fault enable + bit +16 +1 ++ +BUSFAULTENA +Bus fault enable bit +17 +1 ++ +USGFAULTENA +Usage fault enable bit +18 +1 ++ +CFSR_UFSR_BFSR_MMFSR +CFSR_UFSR_BFSR_MMFSR +Configurable fault status + register +0x28 +0x20 +read-write +0x00000000 ++ ++ +IACCVIOL +Instruction access violation + flag +1 +1 ++ +MUNSTKERR +Memory manager fault on unstacking for a + return from exception +3 +1 ++ +MSTKERR +Memory manager fault on stacking for + exception entry. +4 +1 ++ +MLSPERR +MLSPERR +5 +1 ++ +MMARVALID +Memory Management Fault Address Register + (MMAR) valid flag +7 +1 ++ +IBUSERR +Instruction bus error +8 +1 ++ +PRECISERR +Precise data bus error +9 +1 ++ +IMPRECISERR +Imprecise data bus error +10 +1 ++ +UNSTKERR +Bus fault on unstacking for a return + from exception +11 +1 ++ +STKERR +Bus fault on stacking for exception + entry +12 +1 ++ +LSPERR +Bus fault on floating-point lazy state + preservation +13 +1 ++ +BFARVALID +Bus Fault Address Register (BFAR) valid + flag +15 +1 ++ +UNDEFINSTR +Undefined instruction usage + fault +16 +1 ++ +INVSTATE +Invalid state usage fault +17 +1 ++ +INVPC +Invalid PC load usage + fault +18 +1 ++ +NOCP +No coprocessor usage + fault. +19 +1 ++ +UNALIGNED +Unaligned access usage + fault +24 +1 ++ +DIVBYZERO +Divide by zero usage fault +25 +1 ++ +HFSR +HFSR +Hard fault status register +0x2C +0x20 +read-write +0x00000000 ++ ++ +VECTTBL +Vector table hard fault +1 +1 ++ +FORCED +Forced hard fault +30 +1 ++ +DEBUG_VT +Reserved for Debug use +31 +1 ++ +MMFAR +MMFAR +Memory management fault address + register +0x34 +0x20 +read-write +0x00000000 ++ ++ +MMFAR +Memory management fault + address +0 +32 ++ +BFAR +BFAR +Bus fault address register +0x38 +0x20 +read-write +0x00000000 ++ ++ +BFAR +Bus fault address +0 +32 ++ +AFSR +AFSR +Auxiliary fault status + register +0x3C +0x20 +read-write +0x00000000 ++ ++ +IMPDEF +Implementation defined +0 +32 ++ +NVIC_STIR +Nested vectored interrupt + controller +NVIC +0xE000EF00 ++ +0x0 +0x5 +registers ++ ++ +STIR +STIR +Software trigger interrupt + register +0x0 +0x20 +read-write +0x00000000 ++ ++ +INTID +Software generated interrupt + ID +0 +9 ++ +FPU_CPACR +Floating point unit CPACR +FPU +0xE000ED88 ++ +0x0 +0x5 +registers ++ ++ +CPACR +CPACR +Coprocessor access control + register +0x0 +0x20 +read-write +0x0000000 ++ ++ +CP +CP +20 +4 ++ +SCB_ACTRL +System control block ACTLR +SCB +0xE000E008 ++ +0x0 +0x5 +registers ++ ++ +ACTRL +ACTRL +Auxiliary control register +0x0 +0x20 +read-write +0x00000000 ++ ++ +DISMCYCINT +DISMCYCINT +0 +1 ++ +DISDEFWBUF +DISDEFWBUF +1 +1 ++ +DISFOLD +DISFOLD +2 +1 ++ +DISFPCA +DISFPCA +8 +1 ++ +DISOOFP +DISOOFP +9 +1 ++** +** Redistribution and use in source and binary forms, with or without modification, +** are permitted provided that the following conditions are met: +** 1. Redistributions of source code must retain the above copyright notice, +** this list of conditions and the following disclaimer. +** 2. Redistributions in binary form must reproduce the above copyright notice, +** this list of conditions and the following disclaimer in the documentation +** and/or other materials provided with the distribution. +** 3. Neither the name of STMicroelectronics nor the names of its contributors +** may be used to endorse or promote products derived from this software +** without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +** AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +** CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +** OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +** +***************************************************************************** +*/ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Highest address of the user mode stack */ +_estack = ORIGIN(RAM) + LENGTH(RAM); /* end of RAM */ +/* Generate a link error if heap and stack don't fit into RAM */ +_Min_Heap_Size = 0x5000; /* required amount of heap */ +_Min_Stack_Size = 0x5000; /* required amount of stack */ + +/* Specify the memory areas */ +MEMORY +{ +RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K +CCMRAM (xrw) : ORIGIN = 0x10000000, LENGTH = 64K +FLASH (rx) : ORIGIN = 0x8000000, LENGTH = 1024K +} + +/* Define output sections */ +SECTIONS +{ + /* The startup code goes first into FLASH */ + .isr_vector : + { + . = ALIGN(4); + KEEP(*(.isr_vector)) /* Startup code */ + . = ALIGN(4); + } >FLASH + + /* The program code and other data goes into FLASH */ + .text : + { + . = ALIGN(4); + *(.text) /* .text sections (code) */ + *(.text*) /* .text* sections (code) */ + *(.glue_7) /* glue arm to thumb code */ + *(.glue_7t) /* glue thumb to arm code */ + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; /* define a global symbols at end of code */ + } >FLASH + + /* Constant data goes into FLASH */ + .rodata : + { + . = ALIGN(4); + *(.rodata) /* .rodata sections (constants, strings, etc.) */ + *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ + . = ALIGN(4); + } >FLASH + + .ARM.extab : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >FLASH + .ARM : { + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + } >FLASH + + .preinit_array : + { + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + } >FLASH + .init_array : + { + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + } >FLASH + .fini_array : + { + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + } >FLASH + + /* used by the startup to initialize data */ + _sidata = LOADADDR(.data); + + /* Initialized data sections goes into RAM, load LMA copy after code */ + .data : + { + . = ALIGN(4); + _sdata = .; /* create a global symbol at data start */ + *(.data) /* .data sections */ + *(.data*) /* .data* sections */ + + . = ALIGN(4); + _edata = .; /* define a global symbol at data end */ + } >RAM AT> FLASH + + _siccmram = LOADADDR(.ccmram); + + /* CCM-RAM section + * + * IMPORTANT NOTE! + * If initialized variables will be placed in this section, + * the startup code needs to be modified to copy the init-values. + */ + .ccmram : + { + . = ALIGN(4); + _sccmram = .; /* create a global symbol at ccmram start */ + *(.ccmram) + *(.ccmram*) + + . = ALIGN(4); + _eccmram = .; /* create a global symbol at ccmram end */ + } >CCMRAM AT> FLASH + + + /* Uninitialized data section */ + . = ALIGN(4); + .bss : + { + /* This is used by the startup in order to initialize the .bss secion */ + _sbss = .; /* define a global symbol at bss start */ + __bss_start__ = _sbss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _ebss = .; /* define a global symbol at bss end */ + __bss_end__ = _ebss; + } >RAM + + /* User_heap_stack section, used to check that there is enough RAM left */ + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(8); + } >RAM + + + + /* Remove information from the standard libraries */ + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} + + diff --git a/Src/adc.c b/Src/adc.c new file mode 100644 index 0000000..864e3c4 --- /dev/null +++ b/Src/adc.c @@ -0,0 +1,135 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file adc.c + * @brief This file provides code for the configuration + * of the ADC instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "adc.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +ADC_HandleTypeDef hadc1; +DMA_HandleTypeDef hdma_adc1; + +/* ADC1 init function */ +void MX_ADC1_Init(void) +{ + + /* USER CODE BEGIN ADC1_Init 0 */ + + /* USER CODE END ADC1_Init 0 */ + + ADC_ChannelConfTypeDef sConfig = {0}; + + /* USER CODE BEGIN ADC1_Init 1 */ + + /* USER CODE END ADC1_Init 1 */ + + /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) + */ + hadc1.Instance = ADC1; + hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV6; + hadc1.Init.Resolution = ADC_RESOLUTION_12B; + hadc1.Init.ScanConvMode = DISABLE; + hadc1.Init.ContinuousConvMode = DISABLE; + hadc1.Init.DiscontinuousConvMode = DISABLE; + hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; + hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START; + hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT; + hadc1.Init.NbrOfConversion = 1; + hadc1.Init.DMAContinuousRequests = DISABLE; + hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV; + if (HAL_ADC_Init(&hadc1) != HAL_OK) + { + Error_Handler(); + } + + /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time. + */ + sConfig.Channel = ADC_CHANNEL_TEMPSENSOR; + sConfig.Rank = 1; + sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES; + if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN ADC1_Init 2 */ + + /* USER CODE END ADC1_Init 2 */ + +} + +void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle) +{ + + if(adcHandle->Instance==ADC1) + { + /* USER CODE BEGIN ADC1_MspInit 0 */ + + /* USER CODE END ADC1_MspInit 0 */ + /* ADC1 clock enable */ + __HAL_RCC_ADC1_CLK_ENABLE(); + + /* ADC1 DMA Init */ + /* ADC1 Init */ + hdma_adc1.Instance = DMA2_Stream4; + hdma_adc1.Init.Channel = DMA_CHANNEL_0; + hdma_adc1.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_adc1.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_adc1.Init.MemInc = DMA_MINC_ENABLE; + hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD; + hdma_adc1.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD; + hdma_adc1.Init.Mode = DMA_NORMAL; + hdma_adc1.Init.Priority = DMA_PRIORITY_LOW; + hdma_adc1.Init.FIFOMode = DMA_FIFOMODE_DISABLE; + if (HAL_DMA_Init(&hdma_adc1) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc1); + + /* USER CODE BEGIN ADC1_MspInit 1 */ + + /* USER CODE END ADC1_MspInit 1 */ + } +} + +void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle) +{ + + if(adcHandle->Instance==ADC1) + { + /* USER CODE BEGIN ADC1_MspDeInit 0 */ + + /* USER CODE END ADC1_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_ADC1_CLK_DISABLE(); + + /* ADC1 DMA DeInit */ + HAL_DMA_DeInit(adcHandle->DMA_Handle); + /* USER CODE BEGIN ADC1_MspDeInit 1 */ + + /* USER CODE END ADC1_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/can.c b/Src/can.c new file mode 100644 index 0000000..41173da --- /dev/null +++ b/Src/can.c @@ -0,0 +1,224 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file can.c + * @brief This file provides code for the configuration + * of the CAN instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "can.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +CAN_HandleTypeDef hcan1; +CAN_HandleTypeDef hcan2; + +/* CAN1 init function */ +void MX_CAN1_Init(void) +{ + + /* USER CODE BEGIN CAN1_Init 0 */ + + /* USER CODE END CAN1_Init 0 */ + + /* USER CODE BEGIN CAN1_Init 1 */ + + /* USER CODE END CAN1_Init 1 */ + hcan1.Instance = CAN1; + hcan1.Init.Prescaler = 3; + hcan1.Init.Mode = CAN_MODE_NORMAL; + hcan1.Init.SyncJumpWidth = CAN_SJW_1TQ; + hcan1.Init.TimeSeg1 = CAN_BS1_10TQ; + hcan1.Init.TimeSeg2 = CAN_BS2_3TQ; + hcan1.Init.TimeTriggeredMode = DISABLE; + hcan1.Init.AutoBusOff = DISABLE; + hcan1.Init.AutoWakeUp = DISABLE; + hcan1.Init.AutoRetransmission = ENABLE; + hcan1.Init.ReceiveFifoLocked = DISABLE; + hcan1.Init.TransmitFifoPriority = ENABLE; + if (HAL_CAN_Init(&hcan1) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN CAN1_Init 2 */ + + /* USER CODE END CAN1_Init 2 */ + +} +/* CAN2 init function */ +void MX_CAN2_Init(void) +{ + + /* USER CODE BEGIN CAN2_Init 0 */ + + /* USER CODE END CAN2_Init 0 */ + + /* USER CODE BEGIN CAN2_Init 1 */ + + /* USER CODE END CAN2_Init 1 */ + hcan2.Instance = CAN2; + hcan2.Init.Prescaler = 3; + hcan2.Init.Mode = CAN_MODE_NORMAL; + hcan2.Init.SyncJumpWidth = CAN_SJW_1TQ; + hcan2.Init.TimeSeg1 = CAN_BS1_10TQ; + hcan2.Init.TimeSeg2 = CAN_BS2_3TQ; + hcan2.Init.TimeTriggeredMode = DISABLE; + hcan2.Init.AutoBusOff = DISABLE; + hcan2.Init.AutoWakeUp = DISABLE; + hcan2.Init.AutoRetransmission = ENABLE; + hcan2.Init.ReceiveFifoLocked = DISABLE; + hcan2.Init.TransmitFifoPriority = ENABLE; + if (HAL_CAN_Init(&hcan2) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN CAN2_Init 2 */ + + /* USER CODE END CAN2_Init 2 */ + +} + +static uint32_t HAL_RCC_CAN1_CLK_ENABLED=0; + +void HAL_CAN_MspInit(CAN_HandleTypeDef* canHandle) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(canHandle->Instance==CAN1) + { + /* USER CODE BEGIN CAN1_MspInit 0 */ + + /* USER CODE END CAN1_MspInit 0 */ + /* CAN1 clock enable */ + HAL_RCC_CAN1_CLK_ENABLED++; + if(HAL_RCC_CAN1_CLK_ENABLED==1){ + __HAL_RCC_CAN1_CLK_ENABLE(); + } + + __HAL_RCC_GPIOD_CLK_ENABLE(); + /**CAN1 GPIO Configuration + PD0 ------> CAN1_RX + PD1 ------> CAN1_TX + */ + GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF9_CAN1; + HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); + + /* CAN1 interrupt Init */ + HAL_NVIC_SetPriority(CAN1_RX0_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(CAN1_RX0_IRQn); + HAL_NVIC_SetPriority(CAN1_RX1_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(CAN1_RX1_IRQn); + /* USER CODE BEGIN CAN1_MspInit 1 */ + + /* USER CODE END CAN1_MspInit 1 */ + } + else if(canHandle->Instance==CAN2) + { + /* USER CODE BEGIN CAN2_MspInit 0 */ + + /* USER CODE END CAN2_MspInit 0 */ + /* CAN2 clock enable */ + __HAL_RCC_CAN2_CLK_ENABLE(); + HAL_RCC_CAN1_CLK_ENABLED++; + if(HAL_RCC_CAN1_CLK_ENABLED==1){ + __HAL_RCC_CAN1_CLK_ENABLE(); + } + + __HAL_RCC_GPIOB_CLK_ENABLE(); + /**CAN2 GPIO Configuration + PB5 ------> CAN2_RX + PB6 ------> CAN2_TX + */ + GPIO_InitStruct.Pin = GPIO_PIN_5|GPIO_PIN_6; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF9_CAN2; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + /* CAN2 interrupt Init */ + HAL_NVIC_SetPriority(CAN2_RX0_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(CAN2_RX0_IRQn); + HAL_NVIC_SetPriority(CAN2_RX1_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(CAN2_RX1_IRQn); + /* USER CODE BEGIN CAN2_MspInit 1 */ + + /* USER CODE END CAN2_MspInit 1 */ + } +} + +void HAL_CAN_MspDeInit(CAN_HandleTypeDef* canHandle) +{ + + if(canHandle->Instance==CAN1) + { + /* USER CODE BEGIN CAN1_MspDeInit 0 */ + + /* USER CODE END CAN1_MspDeInit 0 */ + /* Peripheral clock disable */ + HAL_RCC_CAN1_CLK_ENABLED--; + if(HAL_RCC_CAN1_CLK_ENABLED==0){ + __HAL_RCC_CAN1_CLK_DISABLE(); + } + + /**CAN1 GPIO Configuration + PD0 ------> CAN1_RX + PD1 ------> CAN1_TX + */ + HAL_GPIO_DeInit(GPIOD, GPIO_PIN_0|GPIO_PIN_1); + + /* CAN1 interrupt Deinit */ + HAL_NVIC_DisableIRQ(CAN1_RX0_IRQn); + HAL_NVIC_DisableIRQ(CAN1_RX1_IRQn); + /* USER CODE BEGIN CAN1_MspDeInit 1 */ + + /* USER CODE END CAN1_MspDeInit 1 */ + } + else if(canHandle->Instance==CAN2) + { + /* USER CODE BEGIN CAN2_MspDeInit 0 */ + + /* USER CODE END CAN2_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_CAN2_CLK_DISABLE(); + HAL_RCC_CAN1_CLK_ENABLED--; + if(HAL_RCC_CAN1_CLK_ENABLED==0){ + __HAL_RCC_CAN1_CLK_DISABLE(); + } + + /**CAN2 GPIO Configuration + PB5 ------> CAN2_RX + PB6 ------> CAN2_TX + */ + HAL_GPIO_DeInit(GPIOB, GPIO_PIN_5|GPIO_PIN_6); + + /* CAN2 interrupt Deinit */ + HAL_NVIC_DisableIRQ(CAN2_RX0_IRQn); + HAL_NVIC_DisableIRQ(CAN2_RX1_IRQn); + /* USER CODE BEGIN CAN2_MspDeInit 1 */ + + /* USER CODE END CAN2_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/crc.c b/Src/crc.c new file mode 100644 index 0000000..7683ef1 --- /dev/null +++ b/Src/crc.c @@ -0,0 +1,85 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file crc.c + * @brief This file provides code for the configuration + * of the CRC instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "crc.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +CRC_HandleTypeDef hcrc; + +/* CRC init function */ +void MX_CRC_Init(void) +{ + + /* USER CODE BEGIN CRC_Init 0 */ + + /* USER CODE END CRC_Init 0 */ + + /* USER CODE BEGIN CRC_Init 1 */ + + /* USER CODE END CRC_Init 1 */ + hcrc.Instance = CRC; + if (HAL_CRC_Init(&hcrc) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN CRC_Init 2 */ + + /* USER CODE END CRC_Init 2 */ + +} + +void HAL_CRC_MspInit(CRC_HandleTypeDef* crcHandle) +{ + + if(crcHandle->Instance==CRC) + { + /* USER CODE BEGIN CRC_MspInit 0 */ + + /* USER CODE END CRC_MspInit 0 */ + /* CRC clock enable */ + __HAL_RCC_CRC_CLK_ENABLE(); + /* USER CODE BEGIN CRC_MspInit 1 */ + + /* USER CODE END CRC_MspInit 1 */ + } +} + +void HAL_CRC_MspDeInit(CRC_HandleTypeDef* crcHandle) +{ + + if(crcHandle->Instance==CRC) + { + /* USER CODE BEGIN CRC_MspDeInit 0 */ + + /* USER CODE END CRC_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_CRC_CLK_DISABLE(); + /* USER CODE BEGIN CRC_MspDeInit 1 */ + + /* USER CODE END CRC_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/dac.c b/Src/dac.c new file mode 100644 index 0000000..13b81ef --- /dev/null +++ b/Src/dac.c @@ -0,0 +1,116 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file dac.c + * @brief This file provides code for the configuration + * of the DAC instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "dac.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +DAC_HandleTypeDef hdac; + +/* DAC init function */ +void MX_DAC_Init(void) +{ + + /* USER CODE BEGIN DAC_Init 0 */ + + /* USER CODE END DAC_Init 0 */ + + DAC_ChannelConfTypeDef sConfig = {0}; + + /* USER CODE BEGIN DAC_Init 1 */ + + /* USER CODE END DAC_Init 1 */ + + /** DAC Initialization + */ + hdac.Instance = DAC; + if (HAL_DAC_Init(&hdac) != HAL_OK) + { + Error_Handler(); + } + + /** DAC channel OUT2 config + */ + sConfig.DAC_Trigger = DAC_TRIGGER_NONE; + sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE; + if (HAL_DAC_ConfigChannel(&hdac, &sConfig, DAC_CHANNEL_2) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN DAC_Init 2 */ + + /* USER CODE END DAC_Init 2 */ + +} + +void HAL_DAC_MspInit(DAC_HandleTypeDef* dacHandle) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(dacHandle->Instance==DAC) + { + /* USER CODE BEGIN DAC_MspInit 0 */ + + /* USER CODE END DAC_MspInit 0 */ + /* DAC clock enable */ + __HAL_RCC_DAC_CLK_ENABLE(); + + __HAL_RCC_GPIOA_CLK_ENABLE(); + /**DAC GPIO Configuration + PA5 ------> DAC_OUT2 + */ + GPIO_InitStruct.Pin = GPIO_PIN_5; + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* USER CODE BEGIN DAC_MspInit 1 */ + + /* USER CODE END DAC_MspInit 1 */ + } +} + +void HAL_DAC_MspDeInit(DAC_HandleTypeDef* dacHandle) +{ + + if(dacHandle->Instance==DAC) + { + /* USER CODE BEGIN DAC_MspDeInit 0 */ + + /* USER CODE END DAC_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_DAC_CLK_DISABLE(); + + /**DAC GPIO Configuration + PA5 ------> DAC_OUT2 + */ + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_5); + + /* USER CODE BEGIN DAC_MspDeInit 1 */ + + /* USER CODE END DAC_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/dma.c b/Src/dma.c new file mode 100644 index 0000000..a1959ee --- /dev/null +++ b/Src/dma.c @@ -0,0 +1,89 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file dma.c + * @brief This file provides code for the configuration + * of all the requested memory to memory DMA transfers. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "dma.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/*----------------------------------------------------------------------------*/ +/* Configure DMA */ +/*----------------------------------------------------------------------------*/ + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/** + * Enable DMA controller clock + */ +void MX_DMA_Init(void) +{ + + /* DMA controller clock enable */ + __HAL_RCC_DMA2_CLK_ENABLE(); + __HAL_RCC_DMA1_CLK_ENABLE(); + + /* DMA interrupt init */ + /* DMA1_Stream1_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Stream1_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA1_Stream1_IRQn); + /* DMA1_Stream2_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Stream2_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA1_Stream2_IRQn); + /* DMA1_Stream3_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Stream3_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA1_Stream3_IRQn); + /* DMA1_Stream4_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Stream4_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA1_Stream4_IRQn); + /* DMA1_Stream7_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA1_Stream7_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA1_Stream7_IRQn); + /* DMA2_Stream0_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA2_Stream0_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA2_Stream0_IRQn); + /* DMA2_Stream2_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA2_Stream2_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA2_Stream2_IRQn); + /* DMA2_Stream3_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA2_Stream3_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA2_Stream3_IRQn); + /* DMA2_Stream4_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA2_Stream4_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA2_Stream4_IRQn); + /* DMA2_Stream5_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA2_Stream5_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA2_Stream5_IRQn); + /* DMA2_Stream6_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA2_Stream6_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA2_Stream6_IRQn); + /* DMA2_Stream7_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(DMA2_Stream7_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(DMA2_Stream7_IRQn); + +} + +/* USER CODE BEGIN 2 */ + +/* USER CODE END 2 */ + diff --git a/Src/freertos.c b/Src/freertos.c new file mode 100644 index 0000000..cfed21a --- /dev/null +++ b/Src/freertos.c @@ -0,0 +1,135 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * File Name : freertos.c + * Description : Code for freertos applications + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "FreeRTOS.h" +#include "task.h" +#include "main.h" +#include "cmsis_os.h" + +/* Private includes ----------------------------------------------------------*/ +/* USER CODE BEGIN Includes */ + +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* USER CODE BEGIN PTD */ + +/* USER CODE END PTD */ + +/* Private define ------------------------------------------------------------*/ +/* USER CODE BEGIN PD */ + +/* USER CODE END PD */ + +/* Private macro -------------------------------------------------------------*/ +/* USER CODE BEGIN PM */ + +/* USER CODE END PM */ + +/* Private variables ---------------------------------------------------------*/ +/* USER CODE BEGIN Variables */ + +/* USER CODE END Variables */ +osThreadId defaultTaskHandle; + +/* Private function prototypes -----------------------------------------------*/ +/* USER CODE BEGIN FunctionPrototypes */ + +/* USER CODE END FunctionPrototypes */ + +void StartDefaultTask(void const * argument); + +extern void MX_USB_DEVICE_Init(void); +void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */ + +/* GetIdleTaskMemory prototype (linked to static allocation support) */ +void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); + +/* USER CODE BEGIN GET_IDLE_TASK_MEMORY */ +static StaticTask_t xIdleTaskTCBBuffer; +static StackType_t xIdleStack[configMINIMAL_STACK_SIZE]; + +void vApplicationGetIdleTaskMemory(StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize) +{ + *ppxIdleTaskTCBBuffer = &xIdleTaskTCBBuffer; + *ppxIdleTaskStackBuffer = &xIdleStack[0]; + *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE; + /* place for user code */ +} +/* USER CODE END GET_IDLE_TASK_MEMORY */ + +/** + * @brief FreeRTOS initialization + * @param None + * @retval None + */ +void MX_FREERTOS_Init(void) { + /* USER CODE BEGIN Init */ + + /* USER CODE END Init */ + + /* USER CODE BEGIN RTOS_MUTEX */ + /* add mutexes, ... */ + /* USER CODE END RTOS_MUTEX */ + + /* USER CODE BEGIN RTOS_SEMAPHORES */ + /* add semaphores, ... */ + /* USER CODE END RTOS_SEMAPHORES */ + + /* USER CODE BEGIN RTOS_TIMERS */ + /* start timers, add new ones, ... */ + /* USER CODE END RTOS_TIMERS */ + + /* USER CODE BEGIN RTOS_QUEUES */ + /* add queues, ... */ + /* USER CODE END RTOS_QUEUES */ + + /* Create the thread(s) */ + /* definition and creation of defaultTask */ + osThreadDef(defaultTask, StartDefaultTask, osPriorityNormal, 0, 128); + defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL); + + /* USER CODE BEGIN RTOS_THREADS */ + /* add threads, ... */ + + /* USER CODE END RTOS_THREADS */ + +} + +/* USER CODE BEGIN Header_StartDefaultTask */ +/** + * @brief Function implementing the defaultTask thread. + * @param argument: Not used + * @retval None + */ +/* USER CODE END Header_StartDefaultTask */ +void StartDefaultTask(void const * argument) +{ + /* init code for USB_DEVICE */ + MX_USB_DEVICE_Init(); + /* USER CODE BEGIN StartDefaultTask */ + osThreadTerminate(NULL); // 避免空置和切换占用cpu + /* USER CODE END StartDefaultTask */ +} + +/* Private application code --------------------------------------------------*/ +/* USER CODE BEGIN Application */ + +/* USER CODE END Application */ diff --git a/Src/gpio.c b/Src/gpio.c new file mode 100644 index 0000000..52d965f --- /dev/null +++ b/Src/gpio.c @@ -0,0 +1,120 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file gpio.c + * @brief This file provides code for the configuration + * of all used GPIO pins. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "gpio.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/*----------------------------------------------------------------------------*/ +/* Configure GPIO */ +/*----------------------------------------------------------------------------*/ +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/** Configure pins as + * Analog + * Input + * Output + * EVENT_OUT + * EXTI +*/ +void MX_GPIO_Init(void) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + + /* GPIO Ports Clock Enable */ + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOG_CLK_ENABLE(); + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOD_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + __HAL_RCC_GPIOI_CLK_ENABLE(); + __HAL_RCC_GPIOF_CLK_ENABLE(); + __HAL_RCC_GPIOH_CLK_ENABLE(); + __HAL_RCC_GPIOE_CLK_ENABLE(); + + /*Configure GPIO pin Output Level */ + HAL_GPIO_WritePin(MAG_RST_GPIO_Port, MAG_RST_Pin, GPIO_PIN_RESET); + + /*Configure GPIO pin Output Level */ + HAL_GPIO_WritePin(CS1_ACCEL_GPIO_Port, CS1_ACCEL_Pin, GPIO_PIN_SET); + + /*Configure GPIO pin Output Level */ + HAL_GPIO_WritePin(CS1_GYRO_GPIO_Port, CS1_GYRO_Pin, GPIO_PIN_SET); + + /*Configure GPIO pin : PtPin */ + GPIO_InitStruct.Pin = MAG_RST_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + HAL_GPIO_Init(MAG_RST_GPIO_Port, &GPIO_InitStruct); + + /*Configure GPIO pin : PtPin */ + GPIO_InitStruct.Pin = INT_MAG_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING; + GPIO_InitStruct.Pull = GPIO_PULLUP; + HAL_GPIO_Init(INT_MAG_GPIO_Port, &GPIO_InitStruct); + + /*Configure GPIO pin : PtPin */ + GPIO_InitStruct.Pin = KEY_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_PULLUP; + HAL_GPIO_Init(KEY_GPIO_Port, &GPIO_InitStruct); + + /*Configure GPIO pin : PtPin */ + GPIO_InitStruct.Pin = CS1_ACCEL_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(CS1_ACCEL_GPIO_Port, &GPIO_InitStruct); + + /*Configure GPIO pins : PCPin PCPin */ + GPIO_InitStruct.Pin = INT_ACC_Pin|INT_GYRO_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /*Configure GPIO pin : PtPin */ + GPIO_InitStruct.Pin = CS1_GYRO_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(CS1_GYRO_GPIO_Port, &GPIO_InitStruct); + + /* EXTI interrupt init*/ + HAL_NVIC_SetPriority(EXTI3_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(EXTI3_IRQn); + + HAL_NVIC_SetPriority(EXTI4_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(EXTI4_IRQn); + + HAL_NVIC_SetPriority(EXTI9_5_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(EXTI9_5_IRQn); + +} + +/* USER CODE BEGIN 2 */ + +/* USER CODE END 2 */ diff --git a/Src/i2c.c b/Src/i2c.c new file mode 100644 index 0000000..0692fd5 --- /dev/null +++ b/Src/i2c.c @@ -0,0 +1,259 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file i2c.c + * @brief This file provides code for the configuration + * of the I2C instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "i2c.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +I2C_HandleTypeDef hi2c2; +I2C_HandleTypeDef hi2c3; +DMA_HandleTypeDef hdma_i2c2_rx; +DMA_HandleTypeDef hdma_i2c2_tx; + +/* I2C2 init function */ +void MX_I2C2_Init(void) +{ + + /* USER CODE BEGIN I2C2_Init 0 */ + + /* USER CODE END I2C2_Init 0 */ + + /* USER CODE BEGIN I2C2_Init 1 */ + + /* USER CODE END I2C2_Init 1 */ + hi2c2.Instance = I2C2; + hi2c2.Init.ClockSpeed = 400000; + hi2c2.Init.DutyCycle = I2C_DUTYCYCLE_2; + hi2c2.Init.OwnAddress1 = 0; + hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; + hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; + hi2c2.Init.OwnAddress2 = 0; + hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; + hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; + if (HAL_I2C_Init(&hi2c2) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN I2C2_Init 2 */ + + /* USER CODE END I2C2_Init 2 */ + +} +/* I2C3 init function */ +void MX_I2C3_Init(void) +{ + + /* USER CODE BEGIN I2C3_Init 0 */ + + /* USER CODE END I2C3_Init 0 */ + + /* USER CODE BEGIN I2C3_Init 1 */ + + /* USER CODE END I2C3_Init 1 */ + hi2c3.Instance = I2C3; + hi2c3.Init.ClockSpeed = 400000; + hi2c3.Init.DutyCycle = I2C_DUTYCYCLE_2; + hi2c3.Init.OwnAddress1 = 0; + hi2c3.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; + hi2c3.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE; + hi2c3.Init.OwnAddress2 = 0; + hi2c3.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE; + hi2c3.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; + if (HAL_I2C_Init(&hi2c3) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN I2C3_Init 2 */ + + /* USER CODE END I2C3_Init 2 */ + +} + +void HAL_I2C_MspInit(I2C_HandleTypeDef* i2cHandle) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(i2cHandle->Instance==I2C2) + { + /* USER CODE BEGIN I2C2_MspInit 0 */ + + /* USER CODE END I2C2_MspInit 0 */ + + __HAL_RCC_GPIOF_CLK_ENABLE(); + /**I2C2 GPIO Configuration + PF0 ------> I2C2_SDA + PF1 ------> I2C2_SCL + */ + GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1; + GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF4_I2C2; + HAL_GPIO_Init(GPIOF, &GPIO_InitStruct); + + /* I2C2 clock enable */ + __HAL_RCC_I2C2_CLK_ENABLE(); + + /* I2C2 DMA Init */ + /* I2C2_RX Init */ + hdma_i2c2_rx.Instance = DMA1_Stream2; + hdma_i2c2_rx.Init.Channel = DMA_CHANNEL_7; + hdma_i2c2_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_i2c2_rx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_i2c2_rx.Init.MemInc = DMA_MINC_ENABLE; + hdma_i2c2_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_i2c2_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_i2c2_rx.Init.Mode = DMA_NORMAL; + hdma_i2c2_rx.Init.Priority = DMA_PRIORITY_LOW; + hdma_i2c2_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE; + if (HAL_DMA_Init(&hdma_i2c2_rx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(i2cHandle,hdmarx,hdma_i2c2_rx); + + /* I2C2_TX Init */ + hdma_i2c2_tx.Instance = DMA1_Stream7; + hdma_i2c2_tx.Init.Channel = DMA_CHANNEL_7; + hdma_i2c2_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_i2c2_tx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_i2c2_tx.Init.MemInc = DMA_MINC_ENABLE; + hdma_i2c2_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_i2c2_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_i2c2_tx.Init.Mode = DMA_NORMAL; + hdma_i2c2_tx.Init.Priority = DMA_PRIORITY_LOW; + hdma_i2c2_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE; + if (HAL_DMA_Init(&hdma_i2c2_tx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(i2cHandle,hdmatx,hdma_i2c2_tx); + + /* I2C2 interrupt Init */ + HAL_NVIC_SetPriority(I2C2_EV_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(I2C2_EV_IRQn); + HAL_NVIC_SetPriority(I2C2_ER_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(I2C2_ER_IRQn); + /* USER CODE BEGIN I2C2_MspInit 1 */ + + /* USER CODE END I2C2_MspInit 1 */ + } + else if(i2cHandle->Instance==I2C3) + { + /* USER CODE BEGIN I2C3_MspInit 0 */ + + /* USER CODE END I2C3_MspInit 0 */ + + __HAL_RCC_GPIOC_CLK_ENABLE(); + __HAL_RCC_GPIOA_CLK_ENABLE(); + /**I2C3 GPIO Configuration + PC9 ------> I2C3_SDA + PA8 ------> I2C3_SCL + */ + GPIO_InitStruct.Pin = GPIO_PIN_9; + GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF4_I2C3; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = GPIO_PIN_8; + GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF4_I2C3; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* I2C3 clock enable */ + __HAL_RCC_I2C3_CLK_ENABLE(); + + /* I2C3 interrupt Init */ + HAL_NVIC_SetPriority(I2C3_EV_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(I2C3_EV_IRQn); + HAL_NVIC_SetPriority(I2C3_ER_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(I2C3_ER_IRQn); + /* USER CODE BEGIN I2C3_MspInit 1 */ + + /* USER CODE END I2C3_MspInit 1 */ + } +} + +void HAL_I2C_MspDeInit(I2C_HandleTypeDef* i2cHandle) +{ + + if(i2cHandle->Instance==I2C2) + { + /* USER CODE BEGIN I2C2_MspDeInit 0 */ + + /* USER CODE END I2C2_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_I2C2_CLK_DISABLE(); + + /**I2C2 GPIO Configuration + PF0 ------> I2C2_SDA + PF1 ------> I2C2_SCL + */ + HAL_GPIO_DeInit(GPIOF, GPIO_PIN_0); + + HAL_GPIO_DeInit(GPIOF, GPIO_PIN_1); + + /* I2C2 DMA DeInit */ + HAL_DMA_DeInit(i2cHandle->hdmarx); + HAL_DMA_DeInit(i2cHandle->hdmatx); + + /* I2C2 interrupt Deinit */ + HAL_NVIC_DisableIRQ(I2C2_EV_IRQn); + HAL_NVIC_DisableIRQ(I2C2_ER_IRQn); + /* USER CODE BEGIN I2C2_MspDeInit 1 */ + + /* USER CODE END I2C2_MspDeInit 1 */ + } + else if(i2cHandle->Instance==I2C3) + { + /* USER CODE BEGIN I2C3_MspDeInit 0 */ + + /* USER CODE END I2C3_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_I2C3_CLK_DISABLE(); + + /**I2C3 GPIO Configuration + PC9 ------> I2C3_SDA + PA8 ------> I2C3_SCL + */ + HAL_GPIO_DeInit(GPIOC, GPIO_PIN_9); + + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_8); + + /* I2C3 interrupt Deinit */ + HAL_NVIC_DisableIRQ(I2C3_EV_IRQn); + HAL_NVIC_DisableIRQ(I2C3_ER_IRQn); + /* USER CODE BEGIN I2C3_MspDeInit 1 */ + + /* USER CODE END I2C3_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/main.c b/Src/main.c new file mode 100644 index 0000000..ce57ebb --- /dev/null +++ b/Src/main.c @@ -0,0 +1,245 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file : main.c + * @brief : Main program body + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "main.h" +#include "cmsis_os.h" +#include "adc.h" +#include "can.h" +#include "crc.h" +#include "dac.h" +#include "dma.h" +#include "i2c.h" +#include "rng.h" +#include "rtc.h" +#include "spi.h" +#include "tim.h" +#include "usart.h" +#include "usb_device.h" +#include "gpio.h" + +/* Private includes ----------------------------------------------------------*/ +/* USER CODE BEGIN Includes */ +#include "robot.h" +#include "bsp_log.h" +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* USER CODE BEGIN PTD */ + +/* USER CODE END PTD */ + +/* Private define ------------------------------------------------------------*/ +/* USER CODE BEGIN PD */ +/* USER CODE END PD */ + +/* Private macro -------------------------------------------------------------*/ +/* USER CODE BEGIN PM */ + +/* USER CODE END PM */ + +/* Private variables ---------------------------------------------------------*/ + +/* USER CODE BEGIN PV */ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +void SystemClock_Config(void); +void MX_FREERTOS_Init(void); +/* USER CODE BEGIN PFP */ + +/* USER CODE END PFP */ + +/* Private user code ---------------------------------------------------------*/ +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/** + * @brief The application entry point. + * @retval int + */ +int main(void) +{ + /* USER CODE BEGIN 1 */ + + /* USER CODE END 1 */ + + /* MCU Configuration--------------------------------------------------------*/ + + /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ + HAL_Init(); + + /* USER CODE BEGIN Init */ + + /* USER CODE END Init */ + + /* Configure the system clock */ + SystemClock_Config(); + + /* USER CODE BEGIN SysInit */ + + /* USER CODE END SysInit */ + + /* Initialize all configured peripherals */ + MX_GPIO_Init(); + MX_DMA_Init(); + MX_ADC1_Init(); + MX_CAN1_Init(); + MX_CAN2_Init(); + MX_SPI1_Init(); + MX_TIM4_Init(); + MX_TIM5_Init(); + MX_USART3_UART_Init(); + MX_RNG_Init(); + MX_RTC_Init(); + MX_TIM1_Init(); + MX_TIM10_Init(); + MX_USART1_UART_Init(); + MX_USART6_UART_Init(); + MX_TIM8_Init(); + MX_I2C2_Init(); + MX_I2C3_Init(); + MX_SPI2_Init(); + MX_CRC_Init(); + MX_DAC_Init(); + /* USER CODE BEGIN 2 */ + RobotInit(); // 唯一的初始化函数 + LOGINFO("[main] SystemInit() and RobotInit() done"); + /* USER CODE END 2 */ + + /* Call init function for freertos objects (in freertos.c) */ + MX_FREERTOS_Init(); + + /* Start scheduler */ + osKernelStart(); + + /* We should never get here as control is now taken by the scheduler */ + /* Infinite loop */ + /* USER CODE BEGIN WHILE */ + while (1) + { + /* USER CODE END WHILE */ + + /* USER CODE BEGIN 3 */ + } + /* USER CODE END 3 */ +} + +/** + * @brief System Clock Configuration + * @retval None + */ +void SystemClock_Config(void) +{ + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; + + /** Configure the main internal regulator output voltage + */ + __HAL_RCC_PWR_CLK_ENABLE(); + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); + + /** Initializes the RCC Oscillators according to the specified parameters + * in the RCC_OscInitTypeDef structure. + */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_ON; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PLLM = 6; + RCC_OscInitStruct.PLL.PLLN = 168; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; + RCC_OscInitStruct.PLL.PLLQ = 7; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + Error_Handler(); + } + + /** Initializes the CPU, AHB and APB buses clocks + */ + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK + |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; + + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) + { + Error_Handler(); + } +} + +/* USER CODE BEGIN 4 */ + +/* USER CODE END 4 */ + +/** + * @brief Period elapsed callback in non blocking mode + * @note This function is called when TIM14 interrupt took place, inside + * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment + * a global variable "uwTick" used as application time base. + * @param htim : TIM handle + * @retval None + */ +void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) +{ + /* USER CODE BEGIN Callback 0 */ + + /* USER CODE END Callback 0 */ + if (htim->Instance == TIM14) { + HAL_IncTick(); + } + /* USER CODE BEGIN Callback 1 */ + + /* USER CODE END Callback 1 */ +} + +/** + * @brief This function is executed in case of error occurrence. + * @retval None + */ +void Error_Handler(void) +{ + /* USER CODE BEGIN Error_Handler_Debug */ + /* User can add his own implementation to report the HAL error return state */ + __disable_irq(); + while (1) + { + } + /* USER CODE END Error_Handler_Debug */ +} + +#ifdef USE_FULL_ASSERT +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t *file, uint32_t line) +{ + /* USER CODE BEGIN 6 */ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + /* USER CODE END 6 */ +} +#endif /* USE_FULL_ASSERT */ diff --git a/Src/rng.c b/Src/rng.c new file mode 100644 index 0000000..a1238ca --- /dev/null +++ b/Src/rng.c @@ -0,0 +1,85 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file rng.c + * @brief This file provides code for the configuration + * of the RNG instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "rng.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +RNG_HandleTypeDef hrng; + +/* RNG init function */ +void MX_RNG_Init(void) +{ + + /* USER CODE BEGIN RNG_Init 0 */ + + /* USER CODE END RNG_Init 0 */ + + /* USER CODE BEGIN RNG_Init 1 */ + + /* USER CODE END RNG_Init 1 */ + hrng.Instance = RNG; + if (HAL_RNG_Init(&hrng) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN RNG_Init 2 */ + + /* USER CODE END RNG_Init 2 */ + +} + +void HAL_RNG_MspInit(RNG_HandleTypeDef* rngHandle) +{ + + if(rngHandle->Instance==RNG) + { + /* USER CODE BEGIN RNG_MspInit 0 */ + + /* USER CODE END RNG_MspInit 0 */ + /* RNG clock enable */ + __HAL_RCC_RNG_CLK_ENABLE(); + /* USER CODE BEGIN RNG_MspInit 1 */ + + /* USER CODE END RNG_MspInit 1 */ + } +} + +void HAL_RNG_MspDeInit(RNG_HandleTypeDef* rngHandle) +{ + + if(rngHandle->Instance==RNG) + { + /* USER CODE BEGIN RNG_MspDeInit 0 */ + + /* USER CODE END RNG_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_RNG_CLK_DISABLE(); + /* USER CODE BEGIN RNG_MspDeInit 1 */ + + /* USER CODE END RNG_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/rtc.c b/Src/rtc.c new file mode 100644 index 0000000..a72520c --- /dev/null +++ b/Src/rtc.c @@ -0,0 +1,105 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file rtc.c + * @brief This file provides code for the configuration + * of the RTC instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "rtc.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +RTC_HandleTypeDef hrtc; + +/* RTC init function */ +void MX_RTC_Init(void) +{ + + /* USER CODE BEGIN RTC_Init 0 */ + + /* USER CODE END RTC_Init 0 */ + + /* USER CODE BEGIN RTC_Init 1 */ + + /* USER CODE END RTC_Init 1 */ + + /** Initialize RTC Only + */ + hrtc.Instance = RTC; + hrtc.Init.HourFormat = RTC_HOURFORMAT_24; + hrtc.Init.AsynchPrediv = 124; + hrtc.Init.SynchPrediv = 3199; + hrtc.Init.OutPut = RTC_OUTPUT_DISABLE; + hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; + hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; + if (HAL_RTC_Init(&hrtc) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN RTC_Init 2 */ + + /* USER CODE END RTC_Init 2 */ + +} + +void HAL_RTC_MspInit(RTC_HandleTypeDef* rtcHandle) +{ + + RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; + if(rtcHandle->Instance==RTC) + { + /* USER CODE BEGIN RTC_MspInit 0 */ + + /* USER CODE END RTC_MspInit 0 */ + + /** Initializes the peripherals clock + */ + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; + PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_HSE_DIV30; + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) + { + Error_Handler(); + } + + /* RTC clock enable */ + __HAL_RCC_RTC_ENABLE(); + /* USER CODE BEGIN RTC_MspInit 1 */ + + /* USER CODE END RTC_MspInit 1 */ + } +} + +void HAL_RTC_MspDeInit(RTC_HandleTypeDef* rtcHandle) +{ + + if(rtcHandle->Instance==RTC) + { + /* USER CODE BEGIN RTC_MspDeInit 0 */ + + /* USER CODE END RTC_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_RTC_DISABLE(); + /* USER CODE BEGIN RTC_MspDeInit 1 */ + + /* USER CODE END RTC_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/spi.c b/Src/spi.c new file mode 100644 index 0000000..d4680c8 --- /dev/null +++ b/Src/spi.c @@ -0,0 +1,311 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file spi.c + * @brief This file provides code for the configuration + * of the SPI instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "spi.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +SPI_HandleTypeDef hspi1; +SPI_HandleTypeDef hspi2; +DMA_HandleTypeDef hdma_spi1_rx; +DMA_HandleTypeDef hdma_spi1_tx; +DMA_HandleTypeDef hdma_spi2_rx; +DMA_HandleTypeDef hdma_spi2_tx; + +/* SPI1 init function */ +void MX_SPI1_Init(void) +{ + + /* USER CODE BEGIN SPI1_Init 0 */ + + /* USER CODE END SPI1_Init 0 */ + + /* USER CODE BEGIN SPI1_Init 1 */ + + /* USER CODE END SPI1_Init 1 */ + hspi1.Instance = SPI1; + hspi1.Init.Mode = SPI_MODE_MASTER; + hspi1.Init.Direction = SPI_DIRECTION_2LINES; + hspi1.Init.DataSize = SPI_DATASIZE_8BIT; + hspi1.Init.CLKPolarity = SPI_POLARITY_HIGH; + hspi1.Init.CLKPhase = SPI_PHASE_2EDGE; + hspi1.Init.NSS = SPI_NSS_SOFT; + hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; + hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB; + hspi1.Init.TIMode = SPI_TIMODE_DISABLE; + hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; + hspi1.Init.CRCPolynomial = 10; + if (HAL_SPI_Init(&hspi1) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN SPI1_Init 2 */ + + /* USER CODE END SPI1_Init 2 */ + +} +/* SPI2 init function */ +void MX_SPI2_Init(void) +{ + + /* USER CODE BEGIN SPI2_Init 0 */ + + /* USER CODE END SPI2_Init 0 */ + + /* USER CODE BEGIN SPI2_Init 1 */ + + /* USER CODE END SPI2_Init 1 */ + hspi2.Instance = SPI2; + hspi2.Init.Mode = SPI_MODE_MASTER; + hspi2.Init.Direction = SPI_DIRECTION_2LINES; + hspi2.Init.DataSize = SPI_DATASIZE_8BIT; + hspi2.Init.CLKPolarity = SPI_POLARITY_HIGH; + hspi2.Init.CLKPhase = SPI_PHASE_2EDGE; + hspi2.Init.NSS = SPI_NSS_SOFT; + hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_256; + hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB; + hspi2.Init.TIMode = SPI_TIMODE_DISABLE; + hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; + hspi2.Init.CRCPolynomial = 10; + if (HAL_SPI_Init(&hspi2) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN SPI2_Init 2 */ + + /* USER CODE END SPI2_Init 2 */ + +} + +void HAL_SPI_MspInit(SPI_HandleTypeDef* spiHandle) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(spiHandle->Instance==SPI1) + { + /* USER CODE BEGIN SPI1_MspInit 0 */ + + /* USER CODE END SPI1_MspInit 0 */ + /* SPI1 clock enable */ + __HAL_RCC_SPI1_CLK_ENABLE(); + + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOA_CLK_ENABLE(); + /**SPI1 GPIO Configuration + PB4 ------> SPI1_MISO + PB3 ------> SPI1_SCK + PA7 ------> SPI1_MOSI + */ + GPIO_InitStruct.Pin = GPIO_PIN_4|GPIO_PIN_3; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF5_SPI1; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = GPIO_PIN_7; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF5_SPI1; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* SPI1 DMA Init */ + /* SPI1_RX Init */ + hdma_spi1_rx.Instance = DMA2_Stream0; + hdma_spi1_rx.Init.Channel = DMA_CHANNEL_3; + hdma_spi1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_spi1_rx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_spi1_rx.Init.MemInc = DMA_MINC_ENABLE; + hdma_spi1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_spi1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_spi1_rx.Init.Mode = DMA_NORMAL; + hdma_spi1_rx.Init.Priority = DMA_PRIORITY_LOW; + hdma_spi1_rx.Init.FIFOMode = DMA_FIFOMODE_ENABLE; + hdma_spi1_rx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL; + hdma_spi1_rx.Init.MemBurst = DMA_MBURST_SINGLE; + hdma_spi1_rx.Init.PeriphBurst = DMA_PBURST_SINGLE; + if (HAL_DMA_Init(&hdma_spi1_rx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(spiHandle,hdmarx,hdma_spi1_rx); + + /* SPI1_TX Init */ + hdma_spi1_tx.Instance = DMA2_Stream3; + hdma_spi1_tx.Init.Channel = DMA_CHANNEL_3; + hdma_spi1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_spi1_tx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_spi1_tx.Init.MemInc = DMA_MINC_ENABLE; + hdma_spi1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_spi1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_spi1_tx.Init.Mode = DMA_NORMAL; + hdma_spi1_tx.Init.Priority = DMA_PRIORITY_LOW; + hdma_spi1_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE; + if (HAL_DMA_Init(&hdma_spi1_tx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(spiHandle,hdmatx,hdma_spi1_tx); + + /* SPI1 interrupt Init */ + HAL_NVIC_SetPriority(SPI1_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(SPI1_IRQn); + /* USER CODE BEGIN SPI1_MspInit 1 */ + + /* USER CODE END SPI1_MspInit 1 */ + } + else if(spiHandle->Instance==SPI2) + { + /* USER CODE BEGIN SPI2_MspInit 0 */ + + /* USER CODE END SPI2_MspInit 0 */ + /* SPI2 clock enable */ + __HAL_RCC_SPI2_CLK_ENABLE(); + + __HAL_RCC_GPIOB_CLK_ENABLE(); + /**SPI2 GPIO Configuration + PB13 ------> SPI2_SCK + PB14 ------> SPI2_MISO + PB15 ------> SPI2_MOSI + */ + GPIO_InitStruct.Pin = GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF5_SPI2; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + /* SPI2 DMA Init */ + /* SPI2_RX Init */ + hdma_spi2_rx.Instance = DMA1_Stream3; + hdma_spi2_rx.Init.Channel = DMA_CHANNEL_0; + hdma_spi2_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_spi2_rx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_spi2_rx.Init.MemInc = DMA_MINC_ENABLE; + hdma_spi2_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_spi2_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_spi2_rx.Init.Mode = DMA_NORMAL; + hdma_spi2_rx.Init.Priority = DMA_PRIORITY_LOW; + hdma_spi2_rx.Init.FIFOMode = DMA_FIFOMODE_ENABLE; + hdma_spi2_rx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL; + hdma_spi2_rx.Init.MemBurst = DMA_MBURST_SINGLE; + hdma_spi2_rx.Init.PeriphBurst = DMA_PBURST_SINGLE; + if (HAL_DMA_Init(&hdma_spi2_rx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(spiHandle,hdmarx,hdma_spi2_rx); + + /* SPI2_TX Init */ + hdma_spi2_tx.Instance = DMA1_Stream4; + hdma_spi2_tx.Init.Channel = DMA_CHANNEL_0; + hdma_spi2_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_spi2_tx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_spi2_tx.Init.MemInc = DMA_MINC_ENABLE; + hdma_spi2_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_spi2_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_spi2_tx.Init.Mode = DMA_NORMAL; + hdma_spi2_tx.Init.Priority = DMA_PRIORITY_LOW; + hdma_spi2_tx.Init.FIFOMode = DMA_FIFOMODE_ENABLE; + hdma_spi2_tx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL; + hdma_spi2_tx.Init.MemBurst = DMA_MBURST_SINGLE; + hdma_spi2_tx.Init.PeriphBurst = DMA_PBURST_SINGLE; + if (HAL_DMA_Init(&hdma_spi2_tx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(spiHandle,hdmatx,hdma_spi2_tx); + + /* SPI2 interrupt Init */ + HAL_NVIC_SetPriority(SPI2_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(SPI2_IRQn); + /* USER CODE BEGIN SPI2_MspInit 1 */ + + /* USER CODE END SPI2_MspInit 1 */ + } +} + +void HAL_SPI_MspDeInit(SPI_HandleTypeDef* spiHandle) +{ + + if(spiHandle->Instance==SPI1) + { + /* USER CODE BEGIN SPI1_MspDeInit 0 */ + + /* USER CODE END SPI1_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_SPI1_CLK_DISABLE(); + + /**SPI1 GPIO Configuration + PB4 ------> SPI1_MISO + PB3 ------> SPI1_SCK + PA7 ------> SPI1_MOSI + */ + HAL_GPIO_DeInit(GPIOB, GPIO_PIN_4|GPIO_PIN_3); + + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_7); + + /* SPI1 DMA DeInit */ + HAL_DMA_DeInit(spiHandle->hdmarx); + HAL_DMA_DeInit(spiHandle->hdmatx); + + /* SPI1 interrupt Deinit */ + HAL_NVIC_DisableIRQ(SPI1_IRQn); + /* USER CODE BEGIN SPI1_MspDeInit 1 */ + + /* USER CODE END SPI1_MspDeInit 1 */ + } + else if(spiHandle->Instance==SPI2) + { + /* USER CODE BEGIN SPI2_MspDeInit 0 */ + + /* USER CODE END SPI2_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_SPI2_CLK_DISABLE(); + + /**SPI2 GPIO Configuration + PB13 ------> SPI2_SCK + PB14 ------> SPI2_MISO + PB15 ------> SPI2_MOSI + */ + HAL_GPIO_DeInit(GPIOB, GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15); + + /* SPI2 DMA DeInit */ + HAL_DMA_DeInit(spiHandle->hdmarx); + HAL_DMA_DeInit(spiHandle->hdmatx); + + /* SPI2 interrupt Deinit */ + HAL_NVIC_DisableIRQ(SPI2_IRQn); + /* USER CODE BEGIN SPI2_MspDeInit 1 */ + + /* USER CODE END SPI2_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/stm32f4xx_hal_msp.c b/Src/stm32f4xx_hal_msp.c new file mode 100644 index 0000000..f569c97 --- /dev/null +++ b/Src/stm32f4xx_hal_msp.c @@ -0,0 +1,88 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file stm32f4xx_hal_msp.c + * @brief This file provides code for the MSP Initialization + * and de-Initialization codes. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" +/* USER CODE BEGIN Includes */ + +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* USER CODE BEGIN TD */ + +/* USER CODE END TD */ + +/* Private define ------------------------------------------------------------*/ +/* USER CODE BEGIN Define */ + +/* USER CODE END Define */ + +/* Private macro -------------------------------------------------------------*/ +/* USER CODE BEGIN Macro */ + +/* USER CODE END Macro */ + +/* Private variables ---------------------------------------------------------*/ +/* USER CODE BEGIN PV */ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +/* USER CODE BEGIN PFP */ + +/* USER CODE END PFP */ + +/* External functions --------------------------------------------------------*/ +/* USER CODE BEGIN ExternalFunctions */ + +/* USER CODE END ExternalFunctions */ + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ +/** + * Initializes the Global MSP. + */ +void HAL_MspInit(void) +{ + /* USER CODE BEGIN MspInit 0 */ + + /* USER CODE END MspInit 0 */ + + __HAL_RCC_SYSCFG_CLK_ENABLE(); + __HAL_RCC_PWR_CLK_ENABLE(); + + /* System interrupt init*/ + /* PendSV_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(PendSV_IRQn, 15, 0); + + /* Peripheral interrupt init */ + /* FLASH_IRQn interrupt configuration */ + HAL_NVIC_SetPriority(FLASH_IRQn, 6, 0); + HAL_NVIC_EnableIRQ(FLASH_IRQn); + + /* USER CODE BEGIN MspInit 1 */ + + /* USER CODE END MspInit 1 */ +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/stm32f4xx_hal_timebase_tim.c b/Src/stm32f4xx_hal_timebase_tim.c new file mode 100644 index 0000000..bc0c39e --- /dev/null +++ b/Src/stm32f4xx_hal_timebase_tim.c @@ -0,0 +1,136 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file stm32f4xx_hal_timebase_TIM.c + * @brief HAL time base based on the hardware TIM. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f4xx_hal.h" +#include "stm32f4xx_hal_tim.h" + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +TIM_HandleTypeDef htim14; +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief This function configures the TIM14 as a time base source. + * The time source is configured to have 1ms time base with a dedicated + * Tick interrupt priority. + * @note This function is called automatically at the beginning of program after + * reset by HAL_Init() or at any time when clock is configured, by HAL_RCC_ClockConfig(). + * @param TickPriority: Tick interrupt priority. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) +{ + RCC_ClkInitTypeDef clkconfig; + uint32_t uwTimclock, uwAPB1Prescaler = 0U; + + uint32_t uwPrescalerValue = 0U; + uint32_t pFLatency; + HAL_StatusTypeDef status; + + /* Enable TIM14 clock */ + __HAL_RCC_TIM14_CLK_ENABLE(); + + /* Get clock configuration */ + HAL_RCC_GetClockConfig(&clkconfig, &pFLatency); + + /* Get APB1 prescaler */ + uwAPB1Prescaler = clkconfig.APB1CLKDivider; + /* Compute TIM14 clock */ + if (uwAPB1Prescaler == RCC_HCLK_DIV1) + { + uwTimclock = HAL_RCC_GetPCLK1Freq(); + } + else + { + uwTimclock = 2UL * HAL_RCC_GetPCLK1Freq(); + } + + /* Compute the prescaler value to have TIM14 counter clock equal to 1MHz */ + uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000U) - 1U); + + /* Initialize TIM14 */ + htim14.Instance = TIM14; + + /* Initialize TIMx peripheral as follow: + + Period = [(TIM14CLK/1000) - 1]. to have a (1/1000) s time base. + + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock. + + ClockDivision = 0 + + Counter direction = Up + */ + htim14.Init.Period = (1000000U / 1000U) - 1U; + htim14.Init.Prescaler = uwPrescalerValue; + htim14.Init.ClockDivision = 0; + htim14.Init.CounterMode = TIM_COUNTERMODE_UP; + htim14.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + + status = HAL_TIM_Base_Init(&htim14); + if (status == HAL_OK) + { + /* Start the TIM time Base generation in interrupt mode */ + status = HAL_TIM_Base_Start_IT(&htim14); + if (status == HAL_OK) + { + /* Enable the TIM14 global Interrupt */ + HAL_NVIC_EnableIRQ(TIM8_TRG_COM_TIM14_IRQn); + /* Configure the SysTick IRQ priority */ + if (TickPriority < (1UL << __NVIC_PRIO_BITS)) + { + /* Configure the TIM IRQ priority */ + HAL_NVIC_SetPriority(TIM8_TRG_COM_TIM14_IRQn, TickPriority, 0U); + uwTickPrio = TickPriority; + } + else + { + status = HAL_ERROR; + } + } + } + + /* Return function status */ + return status; +} + +/** + * @brief Suspend Tick increment. + * @note Disable the tick increment by disabling TIM14 update interrupt. + * @param None + * @retval None + */ +void HAL_SuspendTick(void) +{ + /* Disable TIM14 update Interrupt */ + __HAL_TIM_DISABLE_IT(&htim14, TIM_IT_UPDATE); +} + +/** + * @brief Resume Tick increment. + * @note Enable the tick increment by Enabling TIM14 update interrupt. + * @param None + * @retval None + */ +void HAL_ResumeTick(void) +{ + /* Enable TIM14 Update interrupt */ + __HAL_TIM_ENABLE_IT(&htim14, TIM_IT_UPDATE); +} + diff --git a/Src/stm32f4xx_it.c b/Src/stm32f4xx_it.c new file mode 100644 index 0000000..fb06c6d --- /dev/null +++ b/Src/stm32f4xx_it.c @@ -0,0 +1,623 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file stm32f4xx_it.c + * @brief Interrupt Service Routines. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" +#include "stm32f4xx_it.h" +/* Private includes ----------------------------------------------------------*/ +/* USER CODE BEGIN Includes */ +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* USER CODE BEGIN TD */ + +/* USER CODE END TD */ + +/* Private define ------------------------------------------------------------*/ +/* USER CODE BEGIN PD */ + +/* USER CODE END PD */ + +/* Private macro -------------------------------------------------------------*/ +/* USER CODE BEGIN PM */ + +/* USER CODE END PM */ + +/* Private variables ---------------------------------------------------------*/ +/* USER CODE BEGIN PV */ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +/* USER CODE BEGIN PFP */ + +/* USER CODE END PFP */ + +/* Private user code ---------------------------------------------------------*/ +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/* External variables --------------------------------------------------------*/ +extern PCD_HandleTypeDef hpcd_USB_OTG_FS; +extern DMA_HandleTypeDef hdma_adc1; +extern CAN_HandleTypeDef hcan1; +extern CAN_HandleTypeDef hcan2; +extern DMA_HandleTypeDef hdma_i2c2_rx; +extern DMA_HandleTypeDef hdma_i2c2_tx; +extern I2C_HandleTypeDef hi2c2; +extern I2C_HandleTypeDef hi2c3; +extern DMA_HandleTypeDef hdma_spi1_rx; +extern DMA_HandleTypeDef hdma_spi1_tx; +extern DMA_HandleTypeDef hdma_spi2_rx; +extern DMA_HandleTypeDef hdma_spi2_tx; +extern SPI_HandleTypeDef hspi1; +extern SPI_HandleTypeDef hspi2; +extern TIM_HandleTypeDef htim8; +extern DMA_HandleTypeDef hdma_usart1_tx; +extern DMA_HandleTypeDef hdma_usart1_rx; +extern DMA_HandleTypeDef hdma_usart3_rx; +extern DMA_HandleTypeDef hdma_usart6_rx; +extern DMA_HandleTypeDef hdma_usart6_tx; +extern UART_HandleTypeDef huart1; +extern UART_HandleTypeDef huart3; +extern UART_HandleTypeDef huart6; +extern TIM_HandleTypeDef htim14; + +/* USER CODE BEGIN EV */ + +/* USER CODE END EV */ + +/******************************************************************************/ +/* Cortex-M4 Processor Interruption and Exception Handlers */ +/******************************************************************************/ +/** + * @brief This function handles Non maskable interrupt. + */ +void NMI_Handler(void) +{ + /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ + + /* USER CODE END NonMaskableInt_IRQn 0 */ + /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ + while (1) + { + } + /* USER CODE END NonMaskableInt_IRQn 1 */ +} + +/** + * @brief This function handles Hard fault interrupt. + */ +void HardFault_Handler(void) +{ + /* USER CODE BEGIN HardFault_IRQn 0 */ + asm("bx lr"); + /* USER CODE END HardFault_IRQn 0 */ + while (1) + { + /* USER CODE BEGIN W1_HardFault_IRQn 0 */ + asm("bx lr"); + /* USER CODE END W1_HardFault_IRQn 0 */ + } +} + +/** + * @brief This function handles Memory management fault. + */ +void MemManage_Handler(void) +{ + /* USER CODE BEGIN MemoryManagement_IRQn 0 */ + + /* USER CODE END MemoryManagement_IRQn 0 */ + while (1) + { + /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ + /* USER CODE END W1_MemoryManagement_IRQn 0 */ + } +} + +/** + * @brief This function handles Pre-fetch fault, memory access fault. + */ +void BusFault_Handler(void) +{ + /* USER CODE BEGIN BusFault_IRQn 0 */ + + /* USER CODE END BusFault_IRQn 0 */ + while (1) + { + /* USER CODE BEGIN W1_BusFault_IRQn 0 */ + /* USER CODE END W1_BusFault_IRQn 0 */ + } +} + +/** + * @brief This function handles Undefined instruction or illegal state. + */ +void UsageFault_Handler(void) +{ + /* USER CODE BEGIN UsageFault_IRQn 0 */ + + /* USER CODE END UsageFault_IRQn 0 */ + while (1) + { + /* USER CODE BEGIN W1_UsageFault_IRQn 0 */ + /* USER CODE END W1_UsageFault_IRQn 0 */ + } +} + +/** + * @brief This function handles Debug monitor. + */ +void DebugMon_Handler(void) +{ + /* USER CODE BEGIN DebugMonitor_IRQn 0 */ + + /* USER CODE END DebugMonitor_IRQn 0 */ + /* USER CODE BEGIN DebugMonitor_IRQn 1 */ + + /* USER CODE END DebugMonitor_IRQn 1 */ +} + +/******************************************************************************/ +/* STM32F4xx Peripheral Interrupt Handlers */ +/* Add here the Interrupt Handlers for the used peripherals. */ +/* For the available peripheral interrupt handler names, */ +/* please refer to the startup file (startup_stm32f4xx.s). */ +/******************************************************************************/ + +/** + * @brief This function handles Flash global interrupt. + */ +void FLASH_IRQHandler(void) +{ + /* USER CODE BEGIN FLASH_IRQn 0 */ + + /* USER CODE END FLASH_IRQn 0 */ + HAL_FLASH_IRQHandler(); + /* USER CODE BEGIN FLASH_IRQn 1 */ + + /* USER CODE END FLASH_IRQn 1 */ +} + +/** + * @brief This function handles EXTI line3 interrupt. + */ +void EXTI3_IRQHandler(void) +{ + /* USER CODE BEGIN EXTI3_IRQn 0 */ + + /* USER CODE END EXTI3_IRQn 0 */ + HAL_GPIO_EXTI_IRQHandler(INT_MAG_Pin); + /* USER CODE BEGIN EXTI3_IRQn 1 */ + + /* USER CODE END EXTI3_IRQn 1 */ +} + +/** + * @brief This function handles EXTI line4 interrupt. + */ +void EXTI4_IRQHandler(void) +{ + /* USER CODE BEGIN EXTI4_IRQn 0 */ + + /* USER CODE END EXTI4_IRQn 0 */ + HAL_GPIO_EXTI_IRQHandler(INT_ACC_Pin); + /* USER CODE BEGIN EXTI4_IRQn 1 */ + + /* USER CODE END EXTI4_IRQn 1 */ +} + +/** + * @brief This function handles DMA1 stream1 global interrupt. + */ +void DMA1_Stream1_IRQHandler(void) +{ + /* USER CODE BEGIN DMA1_Stream1_IRQn 0 */ + + /* USER CODE END DMA1_Stream1_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_usart3_rx); + /* USER CODE BEGIN DMA1_Stream1_IRQn 1 */ + + /* USER CODE END DMA1_Stream1_IRQn 1 */ +} + +/** + * @brief This function handles DMA1 stream2 global interrupt. + */ +void DMA1_Stream2_IRQHandler(void) +{ + /* USER CODE BEGIN DMA1_Stream2_IRQn 0 */ + + /* USER CODE END DMA1_Stream2_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_i2c2_rx); + /* USER CODE BEGIN DMA1_Stream2_IRQn 1 */ + + /* USER CODE END DMA1_Stream2_IRQn 1 */ +} + +/** + * @brief This function handles DMA1 stream3 global interrupt. + */ +void DMA1_Stream3_IRQHandler(void) +{ + /* USER CODE BEGIN DMA1_Stream3_IRQn 0 */ + + /* USER CODE END DMA1_Stream3_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_spi2_rx); + /* USER CODE BEGIN DMA1_Stream3_IRQn 1 */ + + /* USER CODE END DMA1_Stream3_IRQn 1 */ +} + +/** + * @brief This function handles DMA1 stream4 global interrupt. + */ +void DMA1_Stream4_IRQHandler(void) +{ + /* USER CODE BEGIN DMA1_Stream4_IRQn 0 */ + + /* USER CODE END DMA1_Stream4_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_spi2_tx); + /* USER CODE BEGIN DMA1_Stream4_IRQn 1 */ + + /* USER CODE END DMA1_Stream4_IRQn 1 */ +} + +/** + * @brief This function handles CAN1 RX0 interrupts. + */ +void CAN1_RX0_IRQHandler(void) +{ + /* USER CODE BEGIN CAN1_RX0_IRQn 0 */ + + /* USER CODE END CAN1_RX0_IRQn 0 */ + HAL_CAN_IRQHandler(&hcan1); + /* USER CODE BEGIN CAN1_RX0_IRQn 1 */ + + /* USER CODE END CAN1_RX0_IRQn 1 */ +} + +/** + * @brief This function handles CAN1 RX1 interrupt. + */ +void CAN1_RX1_IRQHandler(void) +{ + /* USER CODE BEGIN CAN1_RX1_IRQn 0 */ + + /* USER CODE END CAN1_RX1_IRQn 0 */ + HAL_CAN_IRQHandler(&hcan1); + /* USER CODE BEGIN CAN1_RX1_IRQn 1 */ + + /* USER CODE END CAN1_RX1_IRQn 1 */ +} + +/** + * @brief This function handles EXTI line[9:5] interrupts. + */ +void EXTI9_5_IRQHandler(void) +{ + /* USER CODE BEGIN EXTI9_5_IRQn 0 */ + + /* USER CODE END EXTI9_5_IRQn 0 */ + HAL_GPIO_EXTI_IRQHandler(INT_GYRO_Pin); + /* USER CODE BEGIN EXTI9_5_IRQn 1 */ + + /* USER CODE END EXTI9_5_IRQn 1 */ +} + +/** + * @brief This function handles I2C2 event interrupt. + */ +void I2C2_EV_IRQHandler(void) +{ + /* USER CODE BEGIN I2C2_EV_IRQn 0 */ + + /* USER CODE END I2C2_EV_IRQn 0 */ + HAL_I2C_EV_IRQHandler(&hi2c2); + /* USER CODE BEGIN I2C2_EV_IRQn 1 */ + + /* USER CODE END I2C2_EV_IRQn 1 */ +} + +/** + * @brief This function handles I2C2 error interrupt. + */ +void I2C2_ER_IRQHandler(void) +{ + /* USER CODE BEGIN I2C2_ER_IRQn 0 */ + + /* USER CODE END I2C2_ER_IRQn 0 */ + HAL_I2C_ER_IRQHandler(&hi2c2); + /* USER CODE BEGIN I2C2_ER_IRQn 1 */ + + /* USER CODE END I2C2_ER_IRQn 1 */ +} + +/** + * @brief This function handles SPI1 global interrupt. + */ +void SPI1_IRQHandler(void) +{ + /* USER CODE BEGIN SPI1_IRQn 0 */ + + /* USER CODE END SPI1_IRQn 0 */ + HAL_SPI_IRQHandler(&hspi1); + /* USER CODE BEGIN SPI1_IRQn 1 */ + + /* USER CODE END SPI1_IRQn 1 */ +} + +/** + * @brief This function handles SPI2 global interrupt. + */ +void SPI2_IRQHandler(void) +{ + /* USER CODE BEGIN SPI2_IRQn 0 */ + + /* USER CODE END SPI2_IRQn 0 */ + HAL_SPI_IRQHandler(&hspi2); + /* USER CODE BEGIN SPI2_IRQn 1 */ + + /* USER CODE END SPI2_IRQn 1 */ +} + +/** + * @brief This function handles USART1 global interrupt. + */ +void USART1_IRQHandler(void) +{ + /* USER CODE BEGIN USART1_IRQn 0 */ + + /* USER CODE END USART1_IRQn 0 */ + HAL_UART_IRQHandler(&huart1); + /* USER CODE BEGIN USART1_IRQn 1 */ + + /* USER CODE END USART1_IRQn 1 */ +} + +/** + * @brief This function handles USART3 global interrupt. + */ +void USART3_IRQHandler(void) +{ + /* USER CODE BEGIN USART3_IRQn 0 */ + + /* USER CODE END USART3_IRQn 0 */ + HAL_UART_IRQHandler(&huart3); + /* USER CODE BEGIN USART3_IRQn 1 */ + + /* USER CODE END USART3_IRQn 1 */ +} + +/** + * @brief This function handles TIM8 trigger and commutation interrupts and TIM14 global interrupt. + */ +void TIM8_TRG_COM_TIM14_IRQHandler(void) +{ + /* USER CODE BEGIN TIM8_TRG_COM_TIM14_IRQn 0 */ + + /* USER CODE END TIM8_TRG_COM_TIM14_IRQn 0 */ + HAL_TIM_IRQHandler(&htim8); + HAL_TIM_IRQHandler(&htim14); + /* USER CODE BEGIN TIM8_TRG_COM_TIM14_IRQn 1 */ + + /* USER CODE END TIM8_TRG_COM_TIM14_IRQn 1 */ +} + +/** + * @brief This function handles DMA1 stream7 global interrupt. + */ +void DMA1_Stream7_IRQHandler(void) +{ + /* USER CODE BEGIN DMA1_Stream7_IRQn 0 */ + + /* USER CODE END DMA1_Stream7_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_i2c2_tx); + /* USER CODE BEGIN DMA1_Stream7_IRQn 1 */ + + /* USER CODE END DMA1_Stream7_IRQn 1 */ +} + +/** + * @brief This function handles DMA2 stream0 global interrupt. + */ +void DMA2_Stream0_IRQHandler(void) +{ + /* USER CODE BEGIN DMA2_Stream0_IRQn 0 */ + + /* USER CODE END DMA2_Stream0_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_spi1_rx); + /* USER CODE BEGIN DMA2_Stream0_IRQn 1 */ + + /* USER CODE END DMA2_Stream0_IRQn 1 */ +} + +/** + * @brief This function handles DMA2 stream2 global interrupt. + */ +void DMA2_Stream2_IRQHandler(void) +{ + /* USER CODE BEGIN DMA2_Stream2_IRQn 0 */ + + /* USER CODE END DMA2_Stream2_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_usart6_rx); + /* USER CODE BEGIN DMA2_Stream2_IRQn 1 */ + + /* USER CODE END DMA2_Stream2_IRQn 1 */ +} + +/** + * @brief This function handles DMA2 stream3 global interrupt. + */ +void DMA2_Stream3_IRQHandler(void) +{ + /* USER CODE BEGIN DMA2_Stream3_IRQn 0 */ + + /* USER CODE END DMA2_Stream3_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_spi1_tx); + /* USER CODE BEGIN DMA2_Stream3_IRQn 1 */ + + /* USER CODE END DMA2_Stream3_IRQn 1 */ +} + +/** + * @brief This function handles DMA2 stream4 global interrupt. + */ +void DMA2_Stream4_IRQHandler(void) +{ + /* USER CODE BEGIN DMA2_Stream4_IRQn 0 */ + + /* USER CODE END DMA2_Stream4_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_adc1); + /* USER CODE BEGIN DMA2_Stream4_IRQn 1 */ + + /* USER CODE END DMA2_Stream4_IRQn 1 */ +} + +/** + * @brief This function handles CAN2 RX0 interrupts. + */ +void CAN2_RX0_IRQHandler(void) +{ + /* USER CODE BEGIN CAN2_RX0_IRQn 0 */ + + /* USER CODE END CAN2_RX0_IRQn 0 */ + HAL_CAN_IRQHandler(&hcan2); + /* USER CODE BEGIN CAN2_RX0_IRQn 1 */ + + /* USER CODE END CAN2_RX0_IRQn 1 */ +} + +/** + * @brief This function handles CAN2 RX1 interrupt. + */ +void CAN2_RX1_IRQHandler(void) +{ + /* USER CODE BEGIN CAN2_RX1_IRQn 0 */ + + /* USER CODE END CAN2_RX1_IRQn 0 */ + HAL_CAN_IRQHandler(&hcan2); + /* USER CODE BEGIN CAN2_RX1_IRQn 1 */ + + /* USER CODE END CAN2_RX1_IRQn 1 */ +} + +/** + * @brief This function handles USB On The Go FS global interrupt. + */ +void OTG_FS_IRQHandler(void) +{ + /* USER CODE BEGIN OTG_FS_IRQn 0 */ + + /* USER CODE END OTG_FS_IRQn 0 */ + HAL_PCD_IRQHandler(&hpcd_USB_OTG_FS); + /* USER CODE BEGIN OTG_FS_IRQn 1 */ + + /* USER CODE END OTG_FS_IRQn 1 */ +} + +/** + * @brief This function handles DMA2 stream5 global interrupt. + */ +void DMA2_Stream5_IRQHandler(void) +{ + /* USER CODE BEGIN DMA2_Stream5_IRQn 0 */ + + /* USER CODE END DMA2_Stream5_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_usart1_rx); + /* USER CODE BEGIN DMA2_Stream5_IRQn 1 */ + + /* USER CODE END DMA2_Stream5_IRQn 1 */ +} + +/** + * @brief This function handles DMA2 stream6 global interrupt. + */ +void DMA2_Stream6_IRQHandler(void) +{ + /* USER CODE BEGIN DMA2_Stream6_IRQn 0 */ + + /* USER CODE END DMA2_Stream6_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_usart6_tx); + /* USER CODE BEGIN DMA2_Stream6_IRQn 1 */ + + /* USER CODE END DMA2_Stream6_IRQn 1 */ +} + +/** + * @brief This function handles DMA2 stream7 global interrupt. + */ +void DMA2_Stream7_IRQHandler(void) +{ + /* USER CODE BEGIN DMA2_Stream7_IRQn 0 */ + + /* USER CODE END DMA2_Stream7_IRQn 0 */ + HAL_DMA_IRQHandler(&hdma_usart1_tx); + /* USER CODE BEGIN DMA2_Stream7_IRQn 1 */ + + /* USER CODE END DMA2_Stream7_IRQn 1 */ +} + +/** + * @brief This function handles USART6 global interrupt. + */ +void USART6_IRQHandler(void) +{ + /* USER CODE BEGIN USART6_IRQn 0 */ + + /* USER CODE END USART6_IRQn 0 */ + HAL_UART_IRQHandler(&huart6); + /* USER CODE BEGIN USART6_IRQn 1 */ + + /* USER CODE END USART6_IRQn 1 */ +} + +/** + * @brief This function handles I2C3 event interrupt. + */ +void I2C3_EV_IRQHandler(void) +{ + /* USER CODE BEGIN I2C3_EV_IRQn 0 */ + + /* USER CODE END I2C3_EV_IRQn 0 */ + HAL_I2C_EV_IRQHandler(&hi2c3); + /* USER CODE BEGIN I2C3_EV_IRQn 1 */ + + /* USER CODE END I2C3_EV_IRQn 1 */ +} + +/** + * @brief This function handles I2C3 error interrupt. + */ +void I2C3_ER_IRQHandler(void) +{ + /* USER CODE BEGIN I2C3_ER_IRQn 0 */ + + /* USER CODE END I2C3_ER_IRQn 0 */ + HAL_I2C_ER_IRQHandler(&hi2c3); + /* USER CODE BEGIN I2C3_ER_IRQn 1 */ + + /* USER CODE END I2C3_ER_IRQn 1 */ +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/system_stm32f4xx.c b/Src/system_stm32f4xx.c new file mode 100644 index 0000000..3bd40f7 --- /dev/null +++ b/Src/system_stm32f4xx.c @@ -0,0 +1,747 @@ +/** + ****************************************************************************** + * @file system_stm32f4xx.c + * @author MCD Application Team + * @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File. + * + * This file provides two functions and one global variable to be called from + * user application: + * - SystemInit(): This function is called at startup just after reset and + * before branch to main program. This call is made inside + * the "startup_stm32f4xx.s" file. + * + * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used + * by the user application to setup the SysTick + * timer or configure other parameters. + * + * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must + * be called whenever the core clock is changed + * during program execution. + * + * + ****************************************************************************** + * @attention + * + * Copyright (c) 2017 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32f4xx_system + * @{ + */ + +/** @addtogroup STM32F4xx_System_Private_Includes + * @{ + */ + + +#include "stm32f4xx.h" + +#if !defined (HSE_VALUE) + #define HSE_VALUE ((uint32_t)25000000) /*!< Default value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (HSI_VALUE) + #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + +/** + * @} + */ + +/** @addtogroup STM32F4xx_System_Private_TypesDefinitions + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32F4xx_System_Private_Defines + * @{ + */ + +/************************* Miscellaneous Configuration ************************/ +/*!< Uncomment the following line if you need to use external SRAM or SDRAM as data memory */ +#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\ + || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ + || defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) +/* #define DATA_IN_ExtSRAM */ +#endif /* STM32F40xxx || STM32F41xxx || STM32F42xxx || STM32F43xxx || STM32F469xx || STM32F479xx ||\ + STM32F412Zx || STM32F412Vx */ + +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ + || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) +/* #define DATA_IN_ExtSDRAM */ +#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ + STM32F479xx */ + +/* Note: Following vector table addresses must be defined in line with linker + configuration. */ +/*!< Uncomment the following line if you need to relocate the vector table + anywhere in Flash or Sram, else the vector table is kept at the automatic + remap of boot address selected */ +/* #define USER_VECT_TAB_ADDRESS */ + +#if defined(USER_VECT_TAB_ADDRESS) +/*!< Uncomment the following line if you need to relocate your vector Table + in Sram else user remap will be done in Flash. */ +/* #define VECT_TAB_SRAM */ +#if defined(VECT_TAB_SRAM) +#define VECT_TAB_BASE_ADDRESS SRAM_BASE /*!< Vector Table base address field. + This value must be a multiple of 0x200. */ +#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field. + This value must be a multiple of 0x200. */ +#else +#define VECT_TAB_BASE_ADDRESS FLASH_BASE /*!< Vector Table base address field. + This value must be a multiple of 0x200. */ +#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field. + This value must be a multiple of 0x200. */ +#endif /* VECT_TAB_SRAM */ +#endif /* USER_VECT_TAB_ADDRESS */ +/******************************************************************************/ + +/** + * @} + */ + +/** @addtogroup STM32F4xx_System_Private_Macros + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32F4xx_System_Private_Variables + * @{ + */ + /* This variable is updated in three ways: + 1) by calling CMSIS function SystemCoreClockUpdate() + 2) by calling HAL API function HAL_RCC_GetHCLKFreq() + 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency + Note: If you use this function to configure the system clock; then there + is no need to call the 2 first functions listed above, since SystemCoreClock + variable is updated automatically. + */ +uint32_t SystemCoreClock = 16000000; +const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; +const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; +/** + * @} + */ + +/** @addtogroup STM32F4xx_System_Private_FunctionPrototypes + * @{ + */ + +#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) + static void SystemInit_ExtMemCtl(void); +#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ + +/** + * @} + */ + +/** @addtogroup STM32F4xx_System_Private_Functions + * @{ + */ + +/** + * @brief Setup the microcontroller system + * Initialize the FPU setting, vector table location and External memory + * configuration. + * @param None + * @retval None + */ +void SystemInit(void) +{ + /* FPU settings ------------------------------------------------------------*/ + #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ + #endif + +#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) + SystemInit_ExtMemCtl(); +#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ + + /* Configure the Vector Table location -------------------------------------*/ +#if defined(USER_VECT_TAB_ADDRESS) + SCB->VTOR = VECT_TAB_BASE_ADDRESS | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ +#endif /* USER_VECT_TAB_ADDRESS */ +} + +/** + * @brief Update SystemCoreClock variable according to Clock Register Values. + * The SystemCoreClock variable contains the core clock (HCLK), it can + * be used by the user application to setup the SysTick timer or configure + * other parameters. + * + * @note Each time the core clock (HCLK) changes, this function must be called + * to update SystemCoreClock variable value. Otherwise, any configuration + * based on this variable will be incorrect. + * + * @note - The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * + * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) + * + * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) + * + * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) + * or HSI_VALUE(*) multiplied/divided by the PLL factors. + * + * (*) HSI_VALUE is a constant defined in stm32f4xx_hal_conf.h file (default value + * 16 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * (**) HSE_VALUE is a constant defined in stm32f4xx_hal_conf.h file (its value + * depends on the application requirements), user has to ensure that HSE_VALUE + * is same as the real frequency of the crystal used. Otherwise, this function + * may have wrong result. + * + * - The result of this function could be not correct when using fractional + * value for HSE crystal. + * + * @param None + * @retval None + */ +void SystemCoreClockUpdate(void) +{ + uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; + + /* Get SYSCLK source -------------------------------------------------------*/ + tmp = RCC->CFGR & RCC_CFGR_SWS; + + switch (tmp) + { + case 0x00: /* HSI used as system clock source */ + SystemCoreClock = HSI_VALUE; + break; + case 0x04: /* HSE used as system clock source */ + SystemCoreClock = HSE_VALUE; + break; + case 0x08: /* PLL used as system clock source */ + + /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N + SYSCLK = PLL_VCO / PLL_P + */ + pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22; + pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; + + if (pllsource != 0) + { + /* HSE used as PLL clock source */ + pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); + } + else + { + /* HSI used as PLL clock source */ + pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); + } + + pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2; + SystemCoreClock = pllvco/pllp; + break; + default: + SystemCoreClock = HSI_VALUE; + break; + } + /* Compute HCLK frequency --------------------------------------------------*/ + /* Get HCLK prescaler */ + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; + /* HCLK frequency */ + SystemCoreClock >>= tmp; +} + +#if defined (DATA_IN_ExtSRAM) && defined (DATA_IN_ExtSDRAM) +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ + || defined(STM32F469xx) || defined(STM32F479xx) +/** + * @brief Setup the external memory controller. + * Called in startup_stm32f4xx.s before jump to main. + * This function configures the external memories (SRAM/SDRAM) + * This SRAM/SDRAM will be used as program data memory (including heap and stack). + * @param None + * @retval None + */ +void SystemInit_ExtMemCtl(void) +{ + __IO uint32_t tmp = 0x00; + + register uint32_t tmpreg = 0, timeout = 0xFFFF; + register __IO uint32_t index; + + /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */ + RCC->AHB1ENR |= 0x000001F8; + + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); + + /* Connect PDx pins to FMC Alternate function */ + GPIOD->AFR[0] = 0x00CCC0CC; + GPIOD->AFR[1] = 0xCCCCCCCC; + /* Configure PDx pins in Alternate function mode */ + GPIOD->MODER = 0xAAAA0A8A; + /* Configure PDx pins speed to 100 MHz */ + GPIOD->OSPEEDR = 0xFFFF0FCF; + /* Configure PDx pins Output type to push-pull */ + GPIOD->OTYPER = 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOD->PUPDR = 0x00000000; + + /* Connect PEx pins to FMC Alternate function */ + GPIOE->AFR[0] = 0xC00CC0CC; + GPIOE->AFR[1] = 0xCCCCCCCC; + /* Configure PEx pins in Alternate function mode */ + GPIOE->MODER = 0xAAAA828A; + /* Configure PEx pins speed to 100 MHz */ + GPIOE->OSPEEDR = 0xFFFFC3CF; + /* Configure PEx pins Output type to push-pull */ + GPIOE->OTYPER = 0x00000000; + /* No pull-up, pull-down for PEx pins */ + GPIOE->PUPDR = 0x00000000; + + /* Connect PFx pins to FMC Alternate function */ + GPIOF->AFR[0] = 0xCCCCCCCC; + GPIOF->AFR[1] = 0xCCCCCCCC; + /* Configure PFx pins in Alternate function mode */ + GPIOF->MODER = 0xAA800AAA; + /* Configure PFx pins speed to 50 MHz */ + GPIOF->OSPEEDR = 0xAA800AAA; + /* Configure PFx pins Output type to push-pull */ + GPIOF->OTYPER = 0x00000000; + /* No pull-up, pull-down for PFx pins */ + GPIOF->PUPDR = 0x00000000; + + /* Connect PGx pins to FMC Alternate function */ + GPIOG->AFR[0] = 0xCCCCCCCC; + GPIOG->AFR[1] = 0xCCCCCCCC; + /* Configure PGx pins in Alternate function mode */ + GPIOG->MODER = 0xAAAAAAAA; + /* Configure PGx pins speed to 50 MHz */ + GPIOG->OSPEEDR = 0xAAAAAAAA; + /* Configure PGx pins Output type to push-pull */ + GPIOG->OTYPER = 0x00000000; + /* No pull-up, pull-down for PGx pins */ + GPIOG->PUPDR = 0x00000000; + + /* Connect PHx pins to FMC Alternate function */ + GPIOH->AFR[0] = 0x00C0CC00; + GPIOH->AFR[1] = 0xCCCCCCCC; + /* Configure PHx pins in Alternate function mode */ + GPIOH->MODER = 0xAAAA08A0; + /* Configure PHx pins speed to 50 MHz */ + GPIOH->OSPEEDR = 0xAAAA08A0; + /* Configure PHx pins Output type to push-pull */ + GPIOH->OTYPER = 0x00000000; + /* No pull-up, pull-down for PHx pins */ + GPIOH->PUPDR = 0x00000000; + + /* Connect PIx pins to FMC Alternate function */ + GPIOI->AFR[0] = 0xCCCCCCCC; + GPIOI->AFR[1] = 0x00000CC0; + /* Configure PIx pins in Alternate function mode */ + GPIOI->MODER = 0x0028AAAA; + /* Configure PIx pins speed to 50 MHz */ + GPIOI->OSPEEDR = 0x0028AAAA; + /* Configure PIx pins Output type to push-pull */ + GPIOI->OTYPER = 0x00000000; + /* No pull-up, pull-down for PIx pins */ + GPIOI->PUPDR = 0x00000000; + +/*-- FMC Configuration -------------------------------------------------------*/ + /* Enable the FMC interface clock */ + RCC->AHB3ENR |= 0x00000001; + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); + + FMC_Bank5_6->SDCR[0] = 0x000019E4; + FMC_Bank5_6->SDTR[0] = 0x01115351; + + /* SDRAM initialization sequence */ + /* Clock enable command */ + FMC_Bank5_6->SDCMR = 0x00000011; + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* Delay */ + for (index = 0; index<1000; index++); + + /* PALL command */ + FMC_Bank5_6->SDCMR = 0x00000012; + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + timeout = 0xFFFF; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* Auto refresh command */ + FMC_Bank5_6->SDCMR = 0x00000073; + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + timeout = 0xFFFF; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* MRD register program */ + FMC_Bank5_6->SDCMR = 0x00046014; + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + timeout = 0xFFFF; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* Set refresh count */ + tmpreg = FMC_Bank5_6->SDRTR; + FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1)); + + /* Disable write protection */ + tmpreg = FMC_Bank5_6->SDCR[0]; + FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); + +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) + /* Configure and enable Bank1_SRAM2 */ + FMC_Bank1->BTCR[2] = 0x00001011; + FMC_Bank1->BTCR[3] = 0x00000201; + FMC_Bank1E->BWTR[2] = 0x0fffffff; +#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ +#if defined(STM32F469xx) || defined(STM32F479xx) + /* Configure and enable Bank1_SRAM2 */ + FMC_Bank1->BTCR[2] = 0x00001091; + FMC_Bank1->BTCR[3] = 0x00110212; + FMC_Bank1E->BWTR[2] = 0x0fffffff; +#endif /* STM32F469xx || STM32F479xx */ + + (void)(tmp); +} +#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ +#elif defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) +/** + * @brief Setup the external memory controller. + * Called in startup_stm32f4xx.s before jump to main. + * This function configures the external memories (SRAM/SDRAM) + * This SRAM/SDRAM will be used as program data memory (including heap and stack). + * @param None + * @retval None + */ +void SystemInit_ExtMemCtl(void) +{ + __IO uint32_t tmp = 0x00; +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ + || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) +#if defined (DATA_IN_ExtSDRAM) + register uint32_t tmpreg = 0, timeout = 0xFFFF; + register __IO uint32_t index; + +#if defined(STM32F446xx) + /* Enable GPIOA, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG interface + clock */ + RCC->AHB1ENR |= 0x0000007D; +#else + /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface + clock */ + RCC->AHB1ENR |= 0x000001F8; +#endif /* STM32F446xx */ + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); + +#if defined(STM32F446xx) + /* Connect PAx pins to FMC Alternate function */ + GPIOA->AFR[0] |= 0xC0000000; + GPIOA->AFR[1] |= 0x00000000; + /* Configure PDx pins in Alternate function mode */ + GPIOA->MODER |= 0x00008000; + /* Configure PDx pins speed to 50 MHz */ + GPIOA->OSPEEDR |= 0x00008000; + /* Configure PDx pins Output type to push-pull */ + GPIOA->OTYPER |= 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOA->PUPDR |= 0x00000000; + + /* Connect PCx pins to FMC Alternate function */ + GPIOC->AFR[0] |= 0x00CC0000; + GPIOC->AFR[1] |= 0x00000000; + /* Configure PDx pins in Alternate function mode */ + GPIOC->MODER |= 0x00000A00; + /* Configure PDx pins speed to 50 MHz */ + GPIOC->OSPEEDR |= 0x00000A00; + /* Configure PDx pins Output type to push-pull */ + GPIOC->OTYPER |= 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOC->PUPDR |= 0x00000000; +#endif /* STM32F446xx */ + + /* Connect PDx pins to FMC Alternate function */ + GPIOD->AFR[0] = 0x000000CC; + GPIOD->AFR[1] = 0xCC000CCC; + /* Configure PDx pins in Alternate function mode */ + GPIOD->MODER = 0xA02A000A; + /* Configure PDx pins speed to 50 MHz */ + GPIOD->OSPEEDR = 0xA02A000A; + /* Configure PDx pins Output type to push-pull */ + GPIOD->OTYPER = 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOD->PUPDR = 0x00000000; + + /* Connect PEx pins to FMC Alternate function */ + GPIOE->AFR[0] = 0xC00000CC; + GPIOE->AFR[1] = 0xCCCCCCCC; + /* Configure PEx pins in Alternate function mode */ + GPIOE->MODER = 0xAAAA800A; + /* Configure PEx pins speed to 50 MHz */ + GPIOE->OSPEEDR = 0xAAAA800A; + /* Configure PEx pins Output type to push-pull */ + GPIOE->OTYPER = 0x00000000; + /* No pull-up, pull-down for PEx pins */ + GPIOE->PUPDR = 0x00000000; + + /* Connect PFx pins to FMC Alternate function */ + GPIOF->AFR[0] = 0xCCCCCCCC; + GPIOF->AFR[1] = 0xCCCCCCCC; + /* Configure PFx pins in Alternate function mode */ + GPIOF->MODER = 0xAA800AAA; + /* Configure PFx pins speed to 50 MHz */ + GPIOF->OSPEEDR = 0xAA800AAA; + /* Configure PFx pins Output type to push-pull */ + GPIOF->OTYPER = 0x00000000; + /* No pull-up, pull-down for PFx pins */ + GPIOF->PUPDR = 0x00000000; + + /* Connect PGx pins to FMC Alternate function */ + GPIOG->AFR[0] = 0xCCCCCCCC; + GPIOG->AFR[1] = 0xCCCCCCCC; + /* Configure PGx pins in Alternate function mode */ + GPIOG->MODER = 0xAAAAAAAA; + /* Configure PGx pins speed to 50 MHz */ + GPIOG->OSPEEDR = 0xAAAAAAAA; + /* Configure PGx pins Output type to push-pull */ + GPIOG->OTYPER = 0x00000000; + /* No pull-up, pull-down for PGx pins */ + GPIOG->PUPDR = 0x00000000; + +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ + || defined(STM32F469xx) || defined(STM32F479xx) + /* Connect PHx pins to FMC Alternate function */ + GPIOH->AFR[0] = 0x00C0CC00; + GPIOH->AFR[1] = 0xCCCCCCCC; + /* Configure PHx pins in Alternate function mode */ + GPIOH->MODER = 0xAAAA08A0; + /* Configure PHx pins speed to 50 MHz */ + GPIOH->OSPEEDR = 0xAAAA08A0; + /* Configure PHx pins Output type to push-pull */ + GPIOH->OTYPER = 0x00000000; + /* No pull-up, pull-down for PHx pins */ + GPIOH->PUPDR = 0x00000000; + + /* Connect PIx pins to FMC Alternate function */ + GPIOI->AFR[0] = 0xCCCCCCCC; + GPIOI->AFR[1] = 0x00000CC0; + /* Configure PIx pins in Alternate function mode */ + GPIOI->MODER = 0x0028AAAA; + /* Configure PIx pins speed to 50 MHz */ + GPIOI->OSPEEDR = 0x0028AAAA; + /* Configure PIx pins Output type to push-pull */ + GPIOI->OTYPER = 0x00000000; + /* No pull-up, pull-down for PIx pins */ + GPIOI->PUPDR = 0x00000000; +#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ + +/*-- FMC Configuration -------------------------------------------------------*/ + /* Enable the FMC interface clock */ + RCC->AHB3ENR |= 0x00000001; + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); + + /* Configure and enable SDRAM bank1 */ +#if defined(STM32F446xx) + FMC_Bank5_6->SDCR[0] = 0x00001954; +#else + FMC_Bank5_6->SDCR[0] = 0x000019E4; +#endif /* STM32F446xx */ + FMC_Bank5_6->SDTR[0] = 0x01115351; + + /* SDRAM initialization sequence */ + /* Clock enable command */ + FMC_Bank5_6->SDCMR = 0x00000011; + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* Delay */ + for (index = 0; index<1000; index++); + + /* PALL command */ + FMC_Bank5_6->SDCMR = 0x00000012; + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + timeout = 0xFFFF; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* Auto refresh command */ +#if defined(STM32F446xx) + FMC_Bank5_6->SDCMR = 0x000000F3; +#else + FMC_Bank5_6->SDCMR = 0x00000073; +#endif /* STM32F446xx */ + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + timeout = 0xFFFF; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* MRD register program */ +#if defined(STM32F446xx) + FMC_Bank5_6->SDCMR = 0x00044014; +#else + FMC_Bank5_6->SDCMR = 0x00046014; +#endif /* STM32F446xx */ + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + timeout = 0xFFFF; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* Set refresh count */ + tmpreg = FMC_Bank5_6->SDRTR; +#if defined(STM32F446xx) + FMC_Bank5_6->SDRTR = (tmpreg | (0x0000050C<<1)); +#else + FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1)); +#endif /* STM32F446xx */ + + /* Disable write protection */ + tmpreg = FMC_Bank5_6->SDCR[0]; + FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); +#endif /* DATA_IN_ExtSDRAM */ +#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ + +#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\ + || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ + || defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) + +#if defined(DATA_IN_ExtSRAM) +/*-- GPIOs Configuration -----------------------------------------------------*/ + /* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */ + RCC->AHB1ENR |= 0x00000078; + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN); + + /* Connect PDx pins to FMC Alternate function */ + GPIOD->AFR[0] = 0x00CCC0CC; + GPIOD->AFR[1] = 0xCCCCCCCC; + /* Configure PDx pins in Alternate function mode */ + GPIOD->MODER = 0xAAAA0A8A; + /* Configure PDx pins speed to 100 MHz */ + GPIOD->OSPEEDR = 0xFFFF0FCF; + /* Configure PDx pins Output type to push-pull */ + GPIOD->OTYPER = 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOD->PUPDR = 0x00000000; + + /* Connect PEx pins to FMC Alternate function */ + GPIOE->AFR[0] = 0xC00CC0CC; + GPIOE->AFR[1] = 0xCCCCCCCC; + /* Configure PEx pins in Alternate function mode */ + GPIOE->MODER = 0xAAAA828A; + /* Configure PEx pins speed to 100 MHz */ + GPIOE->OSPEEDR = 0xFFFFC3CF; + /* Configure PEx pins Output type to push-pull */ + GPIOE->OTYPER = 0x00000000; + /* No pull-up, pull-down for PEx pins */ + GPIOE->PUPDR = 0x00000000; + + /* Connect PFx pins to FMC Alternate function */ + GPIOF->AFR[0] = 0x00CCCCCC; + GPIOF->AFR[1] = 0xCCCC0000; + /* Configure PFx pins in Alternate function mode */ + GPIOF->MODER = 0xAA000AAA; + /* Configure PFx pins speed to 100 MHz */ + GPIOF->OSPEEDR = 0xFF000FFF; + /* Configure PFx pins Output type to push-pull */ + GPIOF->OTYPER = 0x00000000; + /* No pull-up, pull-down for PFx pins */ + GPIOF->PUPDR = 0x00000000; + + /* Connect PGx pins to FMC Alternate function */ + GPIOG->AFR[0] = 0x00CCCCCC; + GPIOG->AFR[1] = 0x000000C0; + /* Configure PGx pins in Alternate function mode */ + GPIOG->MODER = 0x00085AAA; + /* Configure PGx pins speed to 100 MHz */ + GPIOG->OSPEEDR = 0x000CAFFF; + /* Configure PGx pins Output type to push-pull */ + GPIOG->OTYPER = 0x00000000; + /* No pull-up, pull-down for PGx pins */ + GPIOG->PUPDR = 0x00000000; + +/*-- FMC/FSMC Configuration --------------------------------------------------*/ + /* Enable the FMC/FSMC interface clock */ + RCC->AHB3ENR |= 0x00000001; + +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); + /* Configure and enable Bank1_SRAM2 */ + FMC_Bank1->BTCR[2] = 0x00001011; + FMC_Bank1->BTCR[3] = 0x00000201; + FMC_Bank1E->BWTR[2] = 0x0fffffff; +#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ +#if defined(STM32F469xx) || defined(STM32F479xx) + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); + /* Configure and enable Bank1_SRAM2 */ + FMC_Bank1->BTCR[2] = 0x00001091; + FMC_Bank1->BTCR[3] = 0x00110212; + FMC_Bank1E->BWTR[2] = 0x0fffffff; +#endif /* STM32F469xx || STM32F479xx */ +#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx)\ + || defined(STM32F412Zx) || defined(STM32F412Vx) + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN); + /* Configure and enable Bank1_SRAM2 */ + FSMC_Bank1->BTCR[2] = 0x00001011; + FSMC_Bank1->BTCR[3] = 0x00000201; + FSMC_Bank1E->BWTR[2] = 0x0FFFFFFF; +#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F412Zx || STM32F412Vx */ + +#endif /* DATA_IN_ExtSRAM */ +#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ + STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx */ + (void)(tmp); +} +#endif /* DATA_IN_ExtSRAM && DATA_IN_ExtSDRAM */ +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/Src/tim.c b/Src/tim.c new file mode 100644 index 0000000..648464f --- /dev/null +++ b/Src/tim.c @@ -0,0 +1,605 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file tim.c + * @brief This file provides code for the configuration + * of the TIM instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "tim.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +TIM_HandleTypeDef htim1; +TIM_HandleTypeDef htim4; +TIM_HandleTypeDef htim5; +TIM_HandleTypeDef htim8; +TIM_HandleTypeDef htim10; + +/* TIM1 init function */ +void MX_TIM1_Init(void) +{ + + /* USER CODE BEGIN TIM1_Init 0 */ + + /* USER CODE END TIM1_Init 0 */ + + TIM_ClockConfigTypeDef sClockSourceConfig = {0}; + TIM_MasterConfigTypeDef sMasterConfig = {0}; + TIM_OC_InitTypeDef sConfigOC = {0}; + TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0}; + + /* USER CODE BEGIN TIM1_Init 1 */ + + /* USER CODE END TIM1_Init 1 */ + htim1.Instance = TIM1; + htim1.Init.Prescaler = 167; + htim1.Init.CounterMode = TIM_COUNTERMODE_UP; + htim1.Init.Period = 19999; + htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim1.Init.RepetitionCounter = 0; + htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + if (HAL_TIM_Base_Init(&htim1) != HAL_OK) + { + Error_Handler(); + } + sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; + if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_PWM_Init(&htim1) != HAL_OK) + { + Error_Handler(); + } + sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; + sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; + if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK) + { + Error_Handler(); + } + sConfigOC.OCMode = TIM_OCMODE_PWM1; + sConfigOC.Pulse = 0; + sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH; + sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; + sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET; + sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET; + if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_1) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_2) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_3) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_4) != HAL_OK) + { + Error_Handler(); + } + sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE; + sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE; + sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF; + sBreakDeadTimeConfig.DeadTime = 0; + sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE; + sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH; + sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE; + if (HAL_TIMEx_ConfigBreakDeadTime(&htim1, &sBreakDeadTimeConfig) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN TIM1_Init 2 */ + + /* USER CODE END TIM1_Init 2 */ + HAL_TIM_MspPostInit(&htim1); + +} +/* TIM4 init function */ +void MX_TIM4_Init(void) +{ + + /* USER CODE BEGIN TIM4_Init 0 */ + + /* USER CODE END TIM4_Init 0 */ + + TIM_ClockConfigTypeDef sClockSourceConfig = {0}; + TIM_MasterConfigTypeDef sMasterConfig = {0}; + TIM_OC_InitTypeDef sConfigOC = {0}; + + /* USER CODE BEGIN TIM4_Init 1 */ + + /* USER CODE END TIM4_Init 1 */ + htim4.Instance = TIM4; + htim4.Init.Prescaler = 167; + htim4.Init.CounterMode = TIM_COUNTERMODE_UP; + htim4.Init.Period = 65535; + htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + if (HAL_TIM_Base_Init(&htim4) != HAL_OK) + { + Error_Handler(); + } + sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; + if (HAL_TIM_ConfigClockSource(&htim4, &sClockSourceConfig) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_PWM_Init(&htim4) != HAL_OK) + { + Error_Handler(); + } + sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; + sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; + if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK) + { + Error_Handler(); + } + sConfigOC.OCMode = TIM_OCMODE_PWM1; + sConfigOC.Pulse = 0; + sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; + if (HAL_TIM_PWM_ConfigChannel(&htim4, &sConfigOC, TIM_CHANNEL_3) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN TIM4_Init 2 */ + + /* USER CODE END TIM4_Init 2 */ + HAL_TIM_MspPostInit(&htim4); + +} +/* TIM5 init function */ +void MX_TIM5_Init(void) +{ + + /* USER CODE BEGIN TIM5_Init 0 */ + + /* USER CODE END TIM5_Init 0 */ + + TIM_ClockConfigTypeDef sClockSourceConfig = {0}; + TIM_MasterConfigTypeDef sMasterConfig = {0}; + TIM_OC_InitTypeDef sConfigOC = {0}; + + /* USER CODE BEGIN TIM5_Init 1 */ + + /* USER CODE END TIM5_Init 1 */ + htim5.Instance = TIM5; + htim5.Init.Prescaler = 0; + htim5.Init.CounterMode = TIM_COUNTERMODE_UP; + htim5.Init.Period = 65535; + htim5.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim5.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + if (HAL_TIM_Base_Init(&htim5) != HAL_OK) + { + Error_Handler(); + } + sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; + if (HAL_TIM_ConfigClockSource(&htim5, &sClockSourceConfig) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_PWM_Init(&htim5) != HAL_OK) + { + Error_Handler(); + } + sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; + sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; + if (HAL_TIMEx_MasterConfigSynchronization(&htim5, &sMasterConfig) != HAL_OK) + { + Error_Handler(); + } + sConfigOC.OCMode = TIM_OCMODE_PWM1; + sConfigOC.Pulse = 0; + sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; + if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_1) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_2) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_PWM_ConfigChannel(&htim5, &sConfigOC, TIM_CHANNEL_3) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN TIM5_Init 2 */ + + /* USER CODE END TIM5_Init 2 */ + HAL_TIM_MspPostInit(&htim5); + +} +/* TIM8 init function */ +void MX_TIM8_Init(void) +{ + + /* USER CODE BEGIN TIM8_Init 0 */ + + /* USER CODE END TIM8_Init 0 */ + + TIM_ClockConfigTypeDef sClockSourceConfig = {0}; + TIM_MasterConfigTypeDef sMasterConfig = {0}; + TIM_OC_InitTypeDef sConfigOC = {0}; + TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0}; + + /* USER CODE BEGIN TIM8_Init 1 */ + + /* USER CODE END TIM8_Init 1 */ + htim8.Instance = TIM8; + htim8.Init.Prescaler = 167; + htim8.Init.CounterMode = TIM_COUNTERMODE_UP; + htim8.Init.Period = 19999; + htim8.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim8.Init.RepetitionCounter = 0; + htim8.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + if (HAL_TIM_Base_Init(&htim8) != HAL_OK) + { + Error_Handler(); + } + sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL; + if (HAL_TIM_ConfigClockSource(&htim8, &sClockSourceConfig) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_OC_Init(&htim8) != HAL_OK) + { + Error_Handler(); + } + sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; + sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; + if (HAL_TIMEx_MasterConfigSynchronization(&htim8, &sMasterConfig) != HAL_OK) + { + Error_Handler(); + } + sConfigOC.OCMode = TIM_OCMODE_TIMING; + sConfigOC.Pulse = 0; + sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH; + sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; + sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET; + sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET; + if (HAL_TIM_OC_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_1) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_OC_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_2) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_OC_ConfigChannel(&htim8, &sConfigOC, TIM_CHANNEL_3) != HAL_OK) + { + Error_Handler(); + } + sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE; + sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE; + sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF; + sBreakDeadTimeConfig.DeadTime = 0; + sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE; + sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH; + sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE; + if (HAL_TIMEx_ConfigBreakDeadTime(&htim8, &sBreakDeadTimeConfig) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN TIM8_Init 2 */ + + /* USER CODE END TIM8_Init 2 */ + HAL_TIM_MspPostInit(&htim8); + +} +/* TIM10 init function */ +void MX_TIM10_Init(void) +{ + + /* USER CODE BEGIN TIM10_Init 0 */ + + /* USER CODE END TIM10_Init 0 */ + + TIM_OC_InitTypeDef sConfigOC = {0}; + + /* USER CODE BEGIN TIM10_Init 1 */ + + /* USER CODE END TIM10_Init 1 */ + htim10.Instance = TIM10; + htim10.Init.Prescaler = 167; + htim10.Init.CounterMode = TIM_COUNTERMODE_UP; + htim10.Init.Period = 5000-1; + htim10.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + htim10.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + if (HAL_TIM_Base_Init(&htim10) != HAL_OK) + { + Error_Handler(); + } + if (HAL_TIM_PWM_Init(&htim10) != HAL_OK) + { + Error_Handler(); + } + sConfigOC.OCMode = TIM_OCMODE_PWM1; + sConfigOC.Pulse = 0; + sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfigOC.OCFastMode = TIM_OCFAST_DISABLE; + if (HAL_TIM_PWM_ConfigChannel(&htim10, &sConfigOC, TIM_CHANNEL_1) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN TIM10_Init 2 */ + + /* USER CODE END TIM10_Init 2 */ + HAL_TIM_MspPostInit(&htim10); + +} + +void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle) +{ + + if(tim_baseHandle->Instance==TIM1) + { + /* USER CODE BEGIN TIM1_MspInit 0 */ + + /* USER CODE END TIM1_MspInit 0 */ + /* TIM1 clock enable */ + __HAL_RCC_TIM1_CLK_ENABLE(); + /* USER CODE BEGIN TIM1_MspInit 1 */ + + /* USER CODE END TIM1_MspInit 1 */ + } + else if(tim_baseHandle->Instance==TIM4) + { + /* USER CODE BEGIN TIM4_MspInit 0 */ + + /* USER CODE END TIM4_MspInit 0 */ + /* TIM4 clock enable */ + __HAL_RCC_TIM4_CLK_ENABLE(); + /* USER CODE BEGIN TIM4_MspInit 1 */ + + /* USER CODE END TIM4_MspInit 1 */ + } + else if(tim_baseHandle->Instance==TIM5) + { + /* USER CODE BEGIN TIM5_MspInit 0 */ + + /* USER CODE END TIM5_MspInit 0 */ + /* TIM5 clock enable */ + __HAL_RCC_TIM5_CLK_ENABLE(); + /* USER CODE BEGIN TIM5_MspInit 1 */ + + /* USER CODE END TIM5_MspInit 1 */ + } + else if(tim_baseHandle->Instance==TIM8) + { + /* USER CODE BEGIN TIM8_MspInit 0 */ + + /* USER CODE END TIM8_MspInit 0 */ + /* TIM8 clock enable */ + __HAL_RCC_TIM8_CLK_ENABLE(); + + /* TIM8 interrupt Init */ + HAL_NVIC_SetPriority(TIM8_TRG_COM_TIM14_IRQn, 15, 0); + HAL_NVIC_EnableIRQ(TIM8_TRG_COM_TIM14_IRQn); + /* USER CODE BEGIN TIM8_MspInit 1 */ + + /* USER CODE END TIM8_MspInit 1 */ + } + else if(tim_baseHandle->Instance==TIM10) + { + /* USER CODE BEGIN TIM10_MspInit 0 */ + + /* USER CODE END TIM10_MspInit 0 */ + /* TIM10 clock enable */ + __HAL_RCC_TIM10_CLK_ENABLE(); + /* USER CODE BEGIN TIM10_MspInit 1 */ + + /* USER CODE END TIM10_MspInit 1 */ + } +} +void HAL_TIM_MspPostInit(TIM_HandleTypeDef* timHandle) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(timHandle->Instance==TIM1) + { + /* USER CODE BEGIN TIM1_MspPostInit 0 */ + + /* USER CODE END TIM1_MspPostInit 0 */ + __HAL_RCC_GPIOE_CLK_ENABLE(); + /**TIM1 GPIO Configuration + PE13 ------> TIM1_CH3 + PE9 ------> TIM1_CH1 + PE11 ------> TIM1_CH2 + PE14 ------> TIM1_CH4 + */ + GPIO_InitStruct.Pin = GPIO_PIN_13|SERVO_Pin|GPIO_PIN_11|GPIO_PIN_14; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + GPIO_InitStruct.Alternate = GPIO_AF1_TIM1; + HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); + + /* USER CODE BEGIN TIM1_MspPostInit 1 */ + + /* USER CODE END TIM1_MspPostInit 1 */ + } + else if(timHandle->Instance==TIM4) + { + /* USER CODE BEGIN TIM4_MspPostInit 0 */ + + /* USER CODE END TIM4_MspPostInit 0 */ + + __HAL_RCC_GPIOD_CLK_ENABLE(); + /**TIM4 GPIO Configuration + PD14 ------> TIM4_CH3 + */ + GPIO_InitStruct.Pin = BUZZER_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF2_TIM4; + HAL_GPIO_Init(BUZZER_GPIO_Port, &GPIO_InitStruct); + + /* USER CODE BEGIN TIM4_MspPostInit 1 */ + + /* USER CODE END TIM4_MspPostInit 1 */ + } + else if(timHandle->Instance==TIM5) + { + /* USER CODE BEGIN TIM5_MspPostInit 0 */ + + /* USER CODE END TIM5_MspPostInit 0 */ + + __HAL_RCC_GPIOH_CLK_ENABLE(); + /**TIM5 GPIO Configuration + PH12 ------> TIM5_CH3 + PH11 ------> TIM5_CH2 + PH10 ------> TIM5_CH1 + */ + GPIO_InitStruct.Pin = LED_R_Pin|LED_G_Pin|LED_B_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF2_TIM5; + HAL_GPIO_Init(GPIOH, &GPIO_InitStruct); + + /* USER CODE BEGIN TIM5_MspPostInit 1 */ + + /* USER CODE END TIM5_MspPostInit 1 */ + } + else if(timHandle->Instance==TIM8) + { + /* USER CODE BEGIN TIM8_MspPostInit 0 */ + + /* USER CODE END TIM8_MspPostInit 0 */ + + __HAL_RCC_GPIOI_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + /**TIM8 GPIO Configuration + PI7 ------> TIM8_CH3 + PI6 ------> TIM8_CH2 + PC6 ------> TIM8_CH1 + */ + GPIO_InitStruct.Pin = GPIO_PIN_7|GPIO_PIN_6; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + GPIO_InitStruct.Alternate = GPIO_AF3_TIM8; + HAL_GPIO_Init(GPIOI, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = GPIO_PIN_6; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + GPIO_InitStruct.Alternate = GPIO_AF3_TIM8; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /* USER CODE BEGIN TIM8_MspPostInit 1 */ + + /* USER CODE END TIM8_MspPostInit 1 */ + } + else if(timHandle->Instance==TIM10) + { + /* USER CODE BEGIN TIM10_MspPostInit 0 */ + + /* USER CODE END TIM10_MspPostInit 0 */ + + __HAL_RCC_GPIOF_CLK_ENABLE(); + /**TIM10 GPIO Configuration + PF6 ------> TIM10_CH1 + */ + GPIO_InitStruct.Pin = IMU_TEMP_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF3_TIM10; + HAL_GPIO_Init(IMU_TEMP_GPIO_Port, &GPIO_InitStruct); + + /* USER CODE BEGIN TIM10_MspPostInit 1 */ + + /* USER CODE END TIM10_MspPostInit 1 */ + } + +} + +void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* tim_baseHandle) +{ + + if(tim_baseHandle->Instance==TIM1) + { + /* USER CODE BEGIN TIM1_MspDeInit 0 */ + + /* USER CODE END TIM1_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_TIM1_CLK_DISABLE(); + /* USER CODE BEGIN TIM1_MspDeInit 1 */ + + /* USER CODE END TIM1_MspDeInit 1 */ + } + else if(tim_baseHandle->Instance==TIM4) + { + /* USER CODE BEGIN TIM4_MspDeInit 0 */ + + /* USER CODE END TIM4_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_TIM4_CLK_DISABLE(); + /* USER CODE BEGIN TIM4_MspDeInit 1 */ + + /* USER CODE END TIM4_MspDeInit 1 */ + } + else if(tim_baseHandle->Instance==TIM5) + { + /* USER CODE BEGIN TIM5_MspDeInit 0 */ + + /* USER CODE END TIM5_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_TIM5_CLK_DISABLE(); + /* USER CODE BEGIN TIM5_MspDeInit 1 */ + + /* USER CODE END TIM5_MspDeInit 1 */ + } + else if(tim_baseHandle->Instance==TIM8) + { + /* USER CODE BEGIN TIM8_MspDeInit 0 */ + + /* USER CODE END TIM8_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_TIM8_CLK_DISABLE(); + + /* TIM8 interrupt Deinit */ + HAL_NVIC_DisableIRQ(TIM8_TRG_COM_TIM14_IRQn); + /* USER CODE BEGIN TIM8_MspDeInit 1 */ + + /* USER CODE END TIM8_MspDeInit 1 */ + } + else if(tim_baseHandle->Instance==TIM10) + { + /* USER CODE BEGIN TIM10_MspDeInit 0 */ + + /* USER CODE END TIM10_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_TIM10_CLK_DISABLE(); + /* USER CODE BEGIN TIM10_MspDeInit 1 */ + + /* USER CODE END TIM10_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/usart.c b/Src/usart.c new file mode 100644 index 0000000..7cc1d9c --- /dev/null +++ b/Src/usart.c @@ -0,0 +1,398 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file usart.c + * @brief This file provides code for the configuration + * of the USART instances. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "usart.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +UART_HandleTypeDef huart1; +UART_HandleTypeDef huart3; +UART_HandleTypeDef huart6; +DMA_HandleTypeDef hdma_usart1_tx; +DMA_HandleTypeDef hdma_usart1_rx; +DMA_HandleTypeDef hdma_usart3_rx; +DMA_HandleTypeDef hdma_usart6_rx; +DMA_HandleTypeDef hdma_usart6_tx; + +/* USART1 init function */ + +void MX_USART1_UART_Init(void) +{ + + /* USER CODE BEGIN USART1_Init 0 */ + + /* USER CODE END USART1_Init 0 */ + + /* USER CODE BEGIN USART1_Init 1 */ + + /* USER CODE END USART1_Init 1 */ + huart1.Instance = USART1; + huart1.Init.BaudRate = 921600; + huart1.Init.WordLength = UART_WORDLENGTH_8B; + huart1.Init.StopBits = UART_STOPBITS_1; + huart1.Init.Parity = UART_PARITY_NONE; + huart1.Init.Mode = UART_MODE_TX_RX; + huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE; + huart1.Init.OverSampling = UART_OVERSAMPLING_16; + if (HAL_UART_Init(&huart1) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN USART1_Init 2 */ + + /* USER CODE END USART1_Init 2 */ + +} +/* USART3 init function */ + +void MX_USART3_UART_Init(void) +{ + + /* USER CODE BEGIN USART3_Init 0 */ + + /* USER CODE END USART3_Init 0 */ + + /* USER CODE BEGIN USART3_Init 1 */ + + /* USER CODE END USART3_Init 1 */ + huart3.Instance = USART3; + huart3.Init.BaudRate = 100000; + huart3.Init.WordLength = UART_WORDLENGTH_9B; + huart3.Init.StopBits = UART_STOPBITS_1; + huart3.Init.Parity = UART_PARITY_EVEN; + huart3.Init.Mode = UART_MODE_TX_RX; + huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE; + huart3.Init.OverSampling = UART_OVERSAMPLING_16; + if (HAL_UART_Init(&huart3) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN USART3_Init 2 */ + + /* USER CODE END USART3_Init 2 */ + +} +/* USART6 init function */ + +void MX_USART6_UART_Init(void) +{ + + /* USER CODE BEGIN USART6_Init 0 */ + + /* USER CODE END USART6_Init 0 */ + + /* USER CODE BEGIN USART6_Init 1 */ + + /* USER CODE END USART6_Init 1 */ + huart6.Instance = USART6; + huart6.Init.BaudRate = 115200; + huart6.Init.WordLength = UART_WORDLENGTH_8B; + huart6.Init.StopBits = UART_STOPBITS_1; + huart6.Init.Parity = UART_PARITY_NONE; + huart6.Init.Mode = UART_MODE_TX_RX; + huart6.Init.HwFlowCtl = UART_HWCONTROL_NONE; + huart6.Init.OverSampling = UART_OVERSAMPLING_16; + if (HAL_UART_Init(&huart6) != HAL_OK) + { + Error_Handler(); + } + /* USER CODE BEGIN USART6_Init 2 */ + + /* USER CODE END USART6_Init 2 */ + +} + +void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(uartHandle->Instance==USART1) + { + /* USER CODE BEGIN USART1_MspInit 0 */ + + /* USER CODE END USART1_MspInit 0 */ + /* USART1 clock enable */ + __HAL_RCC_USART1_CLK_ENABLE(); + + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOA_CLK_ENABLE(); + /**USART1 GPIO Configuration + PB7 ------> USART1_RX + PA9 ------> USART1_TX + */ + GPIO_InitStruct.Pin = GPIO_PIN_7; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF7_USART1; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + GPIO_InitStruct.Pin = GPIO_PIN_9; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF7_USART1; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* USART1 DMA Init */ + /* USART1_TX Init */ + hdma_usart1_tx.Instance = DMA2_Stream7; + hdma_usart1_tx.Init.Channel = DMA_CHANNEL_4; + hdma_usart1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_usart1_tx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_usart1_tx.Init.MemInc = DMA_MINC_ENABLE; + hdma_usart1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_usart1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_usart1_tx.Init.Mode = DMA_NORMAL; + hdma_usart1_tx.Init.Priority = DMA_PRIORITY_VERY_HIGH; + hdma_usart1_tx.Init.FIFOMode = DMA_FIFOMODE_DISABLE; + if (HAL_DMA_Init(&hdma_usart1_tx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart1_tx); + + /* USART1_RX Init */ + hdma_usart1_rx.Instance = DMA2_Stream5; + hdma_usart1_rx.Init.Channel = DMA_CHANNEL_4; + hdma_usart1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_usart1_rx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_usart1_rx.Init.MemInc = DMA_MINC_ENABLE; + hdma_usart1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_usart1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_usart1_rx.Init.Mode = DMA_NORMAL; + hdma_usart1_rx.Init.Priority = DMA_PRIORITY_VERY_HIGH; + hdma_usart1_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE; + if (HAL_DMA_Init(&hdma_usart1_rx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart1_rx); + + /* USART1 interrupt Init */ + HAL_NVIC_SetPriority(USART1_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(USART1_IRQn); + /* USER CODE BEGIN USART1_MspInit 1 */ + + /* USER CODE END USART1_MspInit 1 */ + } + else if(uartHandle->Instance==USART3) + { + /* USER CODE BEGIN USART3_MspInit 0 */ + + /* USER CODE END USART3_MspInit 0 */ + /* USART3 clock enable */ + __HAL_RCC_USART3_CLK_ENABLE(); + + __HAL_RCC_GPIOC_CLK_ENABLE(); + /**USART3 GPIO Configuration + PC11 ------> USART3_RX + PC10 ------> USART3_TX + */ + GPIO_InitStruct.Pin = GPIO_PIN_11|GPIO_PIN_10; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF7_USART3; + HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); + + /* USART3 DMA Init */ + /* USART3_RX Init */ + hdma_usart3_rx.Instance = DMA1_Stream1; + hdma_usart3_rx.Init.Channel = DMA_CHANNEL_4; + hdma_usart3_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_usart3_rx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_usart3_rx.Init.MemInc = DMA_MINC_ENABLE; + hdma_usart3_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_usart3_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_usart3_rx.Init.Mode = DMA_NORMAL; + hdma_usart3_rx.Init.Priority = DMA_PRIORITY_LOW; + hdma_usart3_rx.Init.FIFOMode = DMA_FIFOMODE_DISABLE; + if (HAL_DMA_Init(&hdma_usart3_rx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart3_rx); + + /* USART3 interrupt Init */ + HAL_NVIC_SetPriority(USART3_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(USART3_IRQn); + /* USER CODE BEGIN USART3_MspInit 1 */ + + /* USER CODE END USART3_MspInit 1 */ + } + else if(uartHandle->Instance==USART6) + { + /* USER CODE BEGIN USART6_MspInit 0 */ + + /* USER CODE END USART6_MspInit 0 */ + /* USART6 clock enable */ + __HAL_RCC_USART6_CLK_ENABLE(); + + __HAL_RCC_GPIOG_CLK_ENABLE(); + /**USART6 GPIO Configuration + PG14 ------> USART6_TX + PG9 ------> USART6_RX + */ + GPIO_InitStruct.Pin = GPIO_PIN_14|GPIO_PIN_9; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF8_USART6; + HAL_GPIO_Init(GPIOG, &GPIO_InitStruct); + + /* USART6 DMA Init */ + /* USART6_RX Init */ + hdma_usart6_rx.Instance = DMA2_Stream2; + hdma_usart6_rx.Init.Channel = DMA_CHANNEL_5; + hdma_usart6_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_usart6_rx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_usart6_rx.Init.MemInc = DMA_MINC_ENABLE; + hdma_usart6_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_usart6_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_usart6_rx.Init.Mode = DMA_NORMAL; + hdma_usart6_rx.Init.Priority = DMA_PRIORITY_HIGH; + hdma_usart6_rx.Init.FIFOMode = DMA_FIFOMODE_ENABLE; + hdma_usart6_rx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL; + hdma_usart6_rx.Init.MemBurst = DMA_MBURST_SINGLE; + hdma_usart6_rx.Init.PeriphBurst = DMA_PBURST_SINGLE; + if (HAL_DMA_Init(&hdma_usart6_rx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(uartHandle,hdmarx,hdma_usart6_rx); + + /* USART6_TX Init */ + hdma_usart6_tx.Instance = DMA2_Stream6; + hdma_usart6_tx.Init.Channel = DMA_CHANNEL_5; + hdma_usart6_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_usart6_tx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_usart6_tx.Init.MemInc = DMA_MINC_ENABLE; + hdma_usart6_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_usart6_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_usart6_tx.Init.Mode = DMA_NORMAL; + hdma_usart6_tx.Init.Priority = DMA_PRIORITY_HIGH; + hdma_usart6_tx.Init.FIFOMode = DMA_FIFOMODE_ENABLE; + hdma_usart6_tx.Init.FIFOThreshold = DMA_FIFO_THRESHOLD_FULL; + hdma_usart6_tx.Init.MemBurst = DMA_MBURST_SINGLE; + hdma_usart6_tx.Init.PeriphBurst = DMA_PBURST_SINGLE; + if (HAL_DMA_Init(&hdma_usart6_tx) != HAL_OK) + { + Error_Handler(); + } + + __HAL_LINKDMA(uartHandle,hdmatx,hdma_usart6_tx); + + /* USART6 interrupt Init */ + HAL_NVIC_SetPriority(USART6_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(USART6_IRQn); + /* USER CODE BEGIN USART6_MspInit 1 */ + + /* USER CODE END USART6_MspInit 1 */ + } +} + +void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle) +{ + + if(uartHandle->Instance==USART1) + { + /* USER CODE BEGIN USART1_MspDeInit 0 */ + + /* USER CODE END USART1_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_USART1_CLK_DISABLE(); + + /**USART1 GPIO Configuration + PB7 ------> USART1_RX + PA9 ------> USART1_TX + */ + HAL_GPIO_DeInit(GPIOB, GPIO_PIN_7); + + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9); + + /* USART1 DMA DeInit */ + HAL_DMA_DeInit(uartHandle->hdmatx); + HAL_DMA_DeInit(uartHandle->hdmarx); + + /* USART1 interrupt Deinit */ + HAL_NVIC_DisableIRQ(USART1_IRQn); + /* USER CODE BEGIN USART1_MspDeInit 1 */ + + /* USER CODE END USART1_MspDeInit 1 */ + } + else if(uartHandle->Instance==USART3) + { + /* USER CODE BEGIN USART3_MspDeInit 0 */ + + /* USER CODE END USART3_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_USART3_CLK_DISABLE(); + + /**USART3 GPIO Configuration + PC11 ------> USART3_RX + PC10 ------> USART3_TX + */ + HAL_GPIO_DeInit(GPIOC, GPIO_PIN_11|GPIO_PIN_10); + + /* USART3 DMA DeInit */ + HAL_DMA_DeInit(uartHandle->hdmarx); + + /* USART3 interrupt Deinit */ + HAL_NVIC_DisableIRQ(USART3_IRQn); + /* USER CODE BEGIN USART3_MspDeInit 1 */ + + /* USER CODE END USART3_MspDeInit 1 */ + } + else if(uartHandle->Instance==USART6) + { + /* USER CODE BEGIN USART6_MspDeInit 0 */ + + /* USER CODE END USART6_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_USART6_CLK_DISABLE(); + + /**USART6 GPIO Configuration + PG14 ------> USART6_TX + PG9 ------> USART6_RX + */ + HAL_GPIO_DeInit(GPIOG, GPIO_PIN_14|GPIO_PIN_9); + + /* USART6 DMA DeInit */ + HAL_DMA_DeInit(uartHandle->hdmarx); + HAL_DMA_DeInit(uartHandle->hdmatx); + + /* USART6 interrupt Deinit */ + HAL_NVIC_DisableIRQ(USART6_IRQn); + /* USER CODE BEGIN USART6_MspDeInit 1 */ + + /* USER CODE END USART6_MspDeInit 1 */ + } +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ diff --git a/Src/usb_device.c b/Src/usb_device.c new file mode 100644 index 0000000..1c91d19 --- /dev/null +++ b/Src/usb_device.c @@ -0,0 +1,100 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file : usb_device.c + * @version : v1.0_Cube + * @brief : This file implements the USB Device + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ + +#include "usb_device.h" +#include "usbd_core.h" +#include "usbd_desc.h" +#include "usbd_cdc.h" +#include "usbd_cdc_if.h" + +/* USER CODE BEGIN Includes */ + +/* USER CODE END Includes */ + +/* USER CODE BEGIN PV */ +/* Private variables ---------------------------------------------------------*/ + +/* USER CODE END PV */ + +/* USER CODE BEGIN PFP */ +/* Private function prototypes -----------------------------------------------*/ + +/* USER CODE END PFP */ + +/* USB Device Core handle declaration. */ +USBD_HandleTypeDef hUsbDeviceFS; + +/* + * -- Insert your variables declaration here -- + */ +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/* + * -- Insert your external function declaration here -- + */ +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/** + * Init USB device Library, add supported class and start the library + * @retval None + */ +void MX_USB_DEVICE_Init(void) +{ + /* USER CODE BEGIN USB_DEVICE_Init_PreTreatment */ + + /* USER CODE END USB_DEVICE_Init_PreTreatment */ + + /* Init Device Library, add supported class and start the library. */ + if (USBD_Init(&hUsbDeviceFS, &FS_Desc, DEVICE_FS) != USBD_OK) + { + Error_Handler(); + } + if (USBD_RegisterClass(&hUsbDeviceFS, &USBD_CDC) != USBD_OK) + { + Error_Handler(); + } + if (USBD_CDC_RegisterInterface(&hUsbDeviceFS, &USBD_Interface_fops_FS) != USBD_OK) + { + Error_Handler(); + } + if (USBD_Start(&hUsbDeviceFS) != USBD_OK) + { + Error_Handler(); + } + + /* USER CODE BEGIN USB_DEVICE_Init_PostTreatment */ + + /* USER CODE END USB_DEVICE_Init_PostTreatment */ +} + +/** + * @} + */ + +/** + * @} + */ + diff --git a/Src/usbd_cdc_if.c b/Src/usbd_cdc_if.c new file mode 100644 index 0000000..7905498 --- /dev/null +++ b/Src/usbd_cdc_if.c @@ -0,0 +1,340 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file : usbd_cdc_if.c + * @version : v1.0_Cube + * @brief : Usb device for Virtual Com Port. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_cdc_if.h" + +/* USER CODE BEGIN INCLUDE */ + +/* USER CODE END INCLUDE */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ + +/* USER CODE BEGIN PV */ +/* Private variables ---------------------------------------------------------*/ +static USBCallback tx_cbk = NULL; +static USBCallback rx_cbk = NULL; +/* USER CODE END PV */ + +/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY + * @brief Usb device library. + * @{ + */ + +/** @addtogroup USBD_CDC_IF + * @{ + */ + +/** @defgroup USBD_CDC_IF_Private_TypesDefinitions USBD_CDC_IF_Private_TypesDefinitions + * @brief Private types. + * @{ + */ + +/* USER CODE BEGIN PRIVATE_TYPES */ + +/* USER CODE END PRIVATE_TYPES */ + +/** + * @} + */ + +/** @defgroup USBD_CDC_IF_Private_Defines USBD_CDC_IF_Private_Defines + * @brief Private defines. + * @{ + */ + +/* USER CODE BEGIN PRIVATE_DEFINES */ +/* USER CODE END PRIVATE_DEFINES */ + +/** + * @} + */ + +/** @defgroup USBD_CDC_IF_Private_Macros USBD_CDC_IF_Private_Macros + * @brief Private macros. + * @{ + */ + +/* USER CODE BEGIN PRIVATE_MACRO */ + +/* USER CODE END PRIVATE_MACRO */ + +/** + * @} + */ + +/** @defgroup USBD_CDC_IF_Private_Variables USBD_CDC_IF_Private_Variables + * @brief Private variables. + * @{ + */ +/* Create buffer for reception and transmission */ +/* It's up to user to redefine and/or remove those define */ +/** Received data over USB are stored in this buffer */ +uint8_t UserRxBufferFS[APP_RX_DATA_SIZE]; + +/** Data to send over USB CDC are stored in this buffer */ +uint8_t UserTxBufferFS[APP_TX_DATA_SIZE]; + +/* USER CODE BEGIN PRIVATE_VARIABLES */ + +/* USER CODE END PRIVATE_VARIABLES */ + +/** + * @} + */ + +/** @defgroup USBD_CDC_IF_Exported_Variables USBD_CDC_IF_Exported_Variables + * @brief Public variables. + * @{ + */ + +extern USBD_HandleTypeDef hUsbDeviceFS; + +/* USER CODE BEGIN EXPORTED_VARIABLES */ + +/* USER CODE END EXPORTED_VARIABLES */ + +/** + * @} + */ + +/** @defgroup USBD_CDC_IF_Private_FunctionPrototypes USBD_CDC_IF_Private_FunctionPrototypes + * @brief Private functions declaration. + * @{ + */ + +static int8_t CDC_Init_FS(void); +static int8_t CDC_DeInit_FS(void); +static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length); +static int8_t CDC_Receive_FS(uint8_t* pbuf, uint32_t *Len); +static int8_t CDC_TransmitCplt_FS(uint8_t *pbuf, uint32_t *Len, uint8_t epnum); + +/* USER CODE BEGIN PRIVATE_FUNCTIONS_DECLARATION */ + +/* USER CODE END PRIVATE_FUNCTIONS_DECLARATION */ + +/** + * @} + */ + +USBD_CDC_ItfTypeDef USBD_Interface_fops_FS = +{ + CDC_Init_FS, + CDC_DeInit_FS, + CDC_Control_FS, + CDC_Receive_FS, + CDC_TransmitCplt_FS +}; + +/* Private functions ---------------------------------------------------------*/ +/** + * @brief Initializes the CDC media low layer over the FS USB IP + * @retval USBD_OK if all operations are OK else USBD_FAIL + */ +static int8_t CDC_Init_FS(void) +{ + /* USER CODE BEGIN 3 */ + /* Set Application Buffers */ + USBD_CDC_SetTxBuffer(&hUsbDeviceFS, UserTxBufferFS, 0); + USBD_CDC_SetRxBuffer(&hUsbDeviceFS, UserRxBufferFS); + return (USBD_OK); + /* USER CODE END 3 */ +} + +/** + * @brief DeInitializes the CDC media low layer + * @retval USBD_OK if all operations are OK else USBD_FAIL + */ +static int8_t CDC_DeInit_FS(void) +{ + /* USER CODE BEGIN 4 */ + return (USBD_OK); + /* USER CODE END 4 */ +} + +/** + * @brief Manage the CDC class requests + * @param cmd: Command code + * @param pbuf: Buffer containing command data (request parameters) + * @param length: Number of data to be sent (in bytes) + * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL + */ +static int8_t CDC_Control_FS(uint8_t cmd, uint8_t* pbuf, uint16_t length) +{ + /* USER CODE BEGIN 5 */ + switch(cmd) + { + case CDC_SEND_ENCAPSULATED_COMMAND: + + break; + + case CDC_GET_ENCAPSULATED_RESPONSE: + + break; + + case CDC_SET_COMM_FEATURE: + + break; + + case CDC_GET_COMM_FEATURE: + + break; + + case CDC_CLEAR_COMM_FEATURE: + + break; + + /*******************************************************************************/ + /* Line Coding Structure */ + /*-----------------------------------------------------------------------------*/ + /* Offset | Field | Size | Value | Description */ + /* 0 | dwDTERate | 4 | Number |Data terminal rate, in bits per second*/ + /* 4 | bCharFormat | 1 | Number | Stop bits */ + /* 0 - 1 Stop bit */ + /* 1 - 1.5 Stop bits */ + /* 2 - 2 Stop bits */ + /* 5 | bParityType | 1 | Number | Parity */ + /* 0 - None */ + /* 1 - Odd */ + /* 2 - Even */ + /* 3 - Mark */ + /* 4 - Space */ + /* 6 | bDataBits | 1 | Number Data bits (5, 6, 7, 8 or 16). */ + /*******************************************************************************/ + case CDC_SET_LINE_CODING: + + break; + + case CDC_GET_LINE_CODING: + + break; + + case CDC_SET_CONTROL_LINE_STATE: + + break; + + case CDC_SEND_BREAK: + + break; + + default: + break; + } + + return (USBD_OK); + /* USER CODE END 5 */ +} + +/** + * @brief Data received over USB OUT endpoint are sent over CDC interface + * through this function. + * + * @note + * This function will issue a NAK packet on any OUT packet received on + * USB endpoint until exiting this function. If you exit this function + * before transfer is complete on CDC interface (ie. using DMA controller) + * it will result in receiving more data while previous ones are still + * not sent. + * + * @param Buf: Buffer of data to be received + * @param Len: Number of data received (in bytes) + * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL + */ +static int8_t CDC_Receive_FS(uint8_t* Buf, uint32_t *Len) +{ + /* USER CODE BEGIN 6 */ + USBD_CDC_SetRxBuffer(&hUsbDeviceFS, &Buf[0]); + USBD_CDC_ReceivePacket(&hUsbDeviceFS); + + if(rx_cbk) + rx_cbk(*Len); + + return (USBD_OK); + /* USER CODE END 6 */ +} + +/** + * @brief CDC_Transmit_FS + * Data to send over USB IN endpoint are sent over CDC interface + * through this function. + * @note + * + * + * @param Buf: Buffer of data to be sent + * @param Len: Number of data to be sent (in bytes) + * @retval USBD_OK if all operations are OK else USBD_FAIL or USBD_BUSY + */ +uint8_t CDC_Transmit_FS(uint8_t* Buf, uint16_t Len) +{ + uint8_t result = USBD_OK; + /* USER CODE BEGIN 7 */ + USBD_CDC_HandleTypeDef *hcdc = (USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData; + if (hcdc->TxState != 0){ + return USBD_BUSY; + } + USBD_CDC_SetTxBuffer(&hUsbDeviceFS, Buf, Len); + result = USBD_CDC_TransmitPacket(&hUsbDeviceFS); + /* USER CODE END 7 */ + return result; +} + +/** + * @brief CDC_TransmitCplt_FS + * Data transmitted callback + * + * @note + * This function is IN transfer complete callback used to inform user that + * the submitted Data is successfully sent over USB. + * + * @param Buf: Buffer of data to be received + * @param Len: Number of data received (in bytes) + * @retval Result of the operation: USBD_OK if all operations are OK else USBD_FAIL + */ +static int8_t CDC_TransmitCplt_FS(uint8_t *Buf, uint32_t *Len, uint8_t epnum) +{ + uint8_t result = USBD_OK; + /* USER CODE BEGIN 13 */ + UNUSED(Buf); + UNUSED(Len); + UNUSED(epnum); + if(tx_cbk) + tx_cbk(*Len); + /* USER CODE END 13 */ + return result; +} + +/* USER CODE BEGIN PRIVATE_FUNCTIONS_IMPLEMENTATION */ +uint8_t* CDCInitRxbufferNcallback(USBCallback transmit_cbk,USBCallback recv_cbk) +{ + tx_cbk = transmit_cbk; + rx_cbk = recv_cbk; + return UserRxBufferFS; +} +/* USER CODE END PRIVATE_FUNCTIONS_IMPLEMENTATION */ + +/** + * @} + */ + +/** + * @} + */ diff --git a/Src/usbd_conf.c b/Src/usbd_conf.c new file mode 100644 index 0000000..4d67d2a --- /dev/null +++ b/Src/usbd_conf.c @@ -0,0 +1,685 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file : usbd_conf.c + * @version : v1.0_Cube + * @brief : This file implements the board support package for the USB device library + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f4xx.h" +#include "stm32f4xx_hal.h" +#include "usbd_def.h" +#include "usbd_core.h" + +#include "usbd_cdc.h" + +/* USER CODE BEGIN Includes */ +#include "bsp_dwt.h" +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ + +/* USER CODE BEGIN PV */ +/* Private variables ---------------------------------------------------------*/ + +/* USER CODE END PV */ + +PCD_HandleTypeDef hpcd_USB_OTG_FS; +void Error_Handler(void); + +/* External functions --------------------------------------------------------*/ +void SystemClock_Config(void); + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/* USER CODE BEGIN PFP */ +/* Private function prototypes -----------------------------------------------*/ +USBD_StatusTypeDef USBD_Get_USB_Status(HAL_StatusTypeDef hal_status); + +/* USER CODE END PFP */ + +/* Private functions ---------------------------------------------------------*/ + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/******************************************************************************* + LL Driver Callbacks (PCD -> USB Device Library) +*******************************************************************************/ +/* MSP Init */ + +void HAL_PCD_MspInit(PCD_HandleTypeDef* pcdHandle) +{ + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(pcdHandle->Instance==USB_OTG_FS) + { + /* USER CODE BEGIN USB_OTG_FS_MspInit 0 */ + + /* USER CODE END USB_OTG_FS_MspInit 0 */ + + __HAL_RCC_GPIOA_CLK_ENABLE(); + /**USB_OTG_FS GPIO Configuration + PA12 ------> USB_OTG_FS_DP + PA11 ------> USB_OTG_FS_DM + PA10 ------> USB_OTG_FS_ID + */ + GPIO_InitStruct.Pin = GPIO_PIN_12|GPIO_PIN_11|GPIO_PIN_10; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* Peripheral clock enable */ + __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + + /* Peripheral interrupt init */ + HAL_NVIC_SetPriority(OTG_FS_IRQn, 5, 0); + HAL_NVIC_EnableIRQ(OTG_FS_IRQn); + /* USER CODE BEGIN USB_OTG_FS_MspInit 1 */ + // 上电后重新枚举usb设备 + HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, GPIO_PIN_RESET); + DWT_Delay(100); + HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, GPIO_PIN_RESET); + DWT_Delay(100); + /* USER CODE END USB_OTG_FS_MspInit 1 */ + } +} + +void HAL_PCD_MspDeInit(PCD_HandleTypeDef* pcdHandle) +{ + if(pcdHandle->Instance==USB_OTG_FS) + { + /* USER CODE BEGIN USB_OTG_FS_MspDeInit 0 */ + + /* USER CODE END USB_OTG_FS_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_USB_OTG_FS_CLK_DISABLE(); + + /**USB_OTG_FS GPIO Configuration + PA12 ------> USB_OTG_FS_DP + PA11 ------> USB_OTG_FS_DM + PA10 ------> USB_OTG_FS_ID + */ + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_12|GPIO_PIN_11|GPIO_PIN_10); + + /* Peripheral interrupt Deinit*/ + HAL_NVIC_DisableIRQ(OTG_FS_IRQn); + + /* USER CODE BEGIN USB_OTG_FS_MspDeInit 1 */ + + /* USER CODE END USB_OTG_FS_MspDeInit 1 */ + } +} + +/** + * @brief Setup stage callback + * @param hpcd: PCD handle + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) +#else +void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + USBD_LL_SetupStage((USBD_HandleTypeDef*)hpcd->pData, (uint8_t *)hpcd->Setup); +} + +/** + * @brief Data Out stage callback. + * @param hpcd: PCD handle + * @param epnum: Endpoint number + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +#else +void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + USBD_LL_DataOutStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->OUT_ep[epnum].xfer_buff); +} + +/** + * @brief Data In stage callback. + * @param hpcd: PCD handle + * @param epnum: Endpoint number + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +#else +void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + USBD_LL_DataInStage((USBD_HandleTypeDef*)hpcd->pData, epnum, hpcd->IN_ep[epnum].xfer_buff); +} + +/** + * @brief SOF callback. + * @param hpcd: PCD handle + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_SOFCallback(PCD_HandleTypeDef *hpcd) +#else +void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + USBD_LL_SOF((USBD_HandleTypeDef*)hpcd->pData); +} + +/** + * @brief Reset callback. + * @param hpcd: PCD handle + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_ResetCallback(PCD_HandleTypeDef *hpcd) +#else +void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + USBD_SpeedTypeDef speed = USBD_SPEED_FULL; + + if ( hpcd->Init.speed == PCD_SPEED_HIGH) + { + speed = USBD_SPEED_HIGH; + } + else if ( hpcd->Init.speed == PCD_SPEED_FULL) + { + speed = USBD_SPEED_FULL; + } + else + { + Error_Handler(); + } + /* Set Speed. */ + USBD_LL_SetSpeed((USBD_HandleTypeDef*)hpcd->pData, speed); + + /* Reset Device. */ + USBD_LL_Reset((USBD_HandleTypeDef*)hpcd->pData); +} + +/** + * @brief Suspend callback. + * When Low power mode is enabled the debug cannot be used (IAR, Keil doesn't support it) + * @param hpcd: PCD handle + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) +#else +void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + /* Inform USB library that core enters in suspend Mode. */ + USBD_LL_Suspend((USBD_HandleTypeDef*)hpcd->pData); + __HAL_PCD_GATE_PHYCLOCK(hpcd); + /* Enter in STOP mode. */ + /* USER CODE BEGIN 2 */ + if (hpcd->Init.low_power_enable) + { + /* Set SLEEPDEEP bit and SleepOnExit of Cortex System Control Register. */ + SCB->SCR |= (uint32_t)((uint32_t)(SCB_SCR_SLEEPDEEP_Msk | SCB_SCR_SLEEPONEXIT_Msk)); + } + /* USER CODE END 2 */ +} + +/** + * @brief Resume callback. + * When Low power mode is enabled the debug cannot be used (IAR, Keil doesn't support it) + * @param hpcd: PCD handle + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) +#else +void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + /* USER CODE BEGIN 3 */ + + /* USER CODE END 3 */ + USBD_LL_Resume((USBD_HandleTypeDef*)hpcd->pData); +} + +/** + * @brief ISOOUTIncomplete callback. + * @param hpcd: PCD handle + * @param epnum: Endpoint number + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +#else +void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + USBD_LL_IsoOUTIncomplete((USBD_HandleTypeDef*)hpcd->pData, epnum); +} + +/** + * @brief ISOINIncomplete callback. + * @param hpcd: PCD handle + * @param epnum: Endpoint number + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +#else +void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + USBD_LL_IsoINIncomplete((USBD_HandleTypeDef*)hpcd->pData, epnum); +} + +/** + * @brief Connect callback. + * @param hpcd: PCD handle + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) +#else +void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + USBD_LL_DevConnected((USBD_HandleTypeDef*)hpcd->pData); +} + +/** + * @brief Disconnect callback. + * @param hpcd: PCD handle + * @retval None + */ +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) +static void PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) +#else +void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ +{ + USBD_LL_DevDisconnected((USBD_HandleTypeDef*)hpcd->pData); +} + +/******************************************************************************* + LL Driver Interface (USB Device Library --> PCD) +*******************************************************************************/ + +/** + * @brief Initializes the low level portion of the device driver. + * @param pdev: Device handle + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_Init(USBD_HandleTypeDef *pdev) +{ + /* Init USB Ip. */ + if (pdev->id == DEVICE_FS) { + /* Link the driver to the stack. */ + hpcd_USB_OTG_FS.pData = pdev; + pdev->pData = &hpcd_USB_OTG_FS; + + hpcd_USB_OTG_FS.Instance = USB_OTG_FS; + hpcd_USB_OTG_FS.Init.dev_endpoints = 4; + hpcd_USB_OTG_FS.Init.speed = PCD_SPEED_FULL; + hpcd_USB_OTG_FS.Init.dma_enable = DISABLE; + hpcd_USB_OTG_FS.Init.phy_itface = PCD_PHY_EMBEDDED; + hpcd_USB_OTG_FS.Init.Sof_enable = DISABLE; + hpcd_USB_OTG_FS.Init.low_power_enable = DISABLE; + hpcd_USB_OTG_FS.Init.lpm_enable = DISABLE; + hpcd_USB_OTG_FS.Init.vbus_sensing_enable = DISABLE; + hpcd_USB_OTG_FS.Init.use_dedicated_ep1 = DISABLE; + if (HAL_PCD_Init(&hpcd_USB_OTG_FS) != HAL_OK) + { + Error_Handler( ); + } + +#if (USE_HAL_PCD_REGISTER_CALLBACKS == 1U) + /* Register USB PCD CallBacks */ + HAL_PCD_RegisterCallback(&hpcd_USB_OTG_FS, HAL_PCD_SOF_CB_ID, PCD_SOFCallback); + HAL_PCD_RegisterCallback(&hpcd_USB_OTG_FS, HAL_PCD_SETUPSTAGE_CB_ID, PCD_SetupStageCallback); + HAL_PCD_RegisterCallback(&hpcd_USB_OTG_FS, HAL_PCD_RESET_CB_ID, PCD_ResetCallback); + HAL_PCD_RegisterCallback(&hpcd_USB_OTG_FS, HAL_PCD_SUSPEND_CB_ID, PCD_SuspendCallback); + HAL_PCD_RegisterCallback(&hpcd_USB_OTG_FS, HAL_PCD_RESUME_CB_ID, PCD_ResumeCallback); + HAL_PCD_RegisterCallback(&hpcd_USB_OTG_FS, HAL_PCD_CONNECT_CB_ID, PCD_ConnectCallback); + HAL_PCD_RegisterCallback(&hpcd_USB_OTG_FS, HAL_PCD_DISCONNECT_CB_ID, PCD_DisconnectCallback); + + HAL_PCD_RegisterDataOutStageCallback(&hpcd_USB_OTG_FS, PCD_DataOutStageCallback); + HAL_PCD_RegisterDataInStageCallback(&hpcd_USB_OTG_FS, PCD_DataInStageCallback); + HAL_PCD_RegisterIsoOutIncpltCallback(&hpcd_USB_OTG_FS, PCD_ISOOUTIncompleteCallback); + HAL_PCD_RegisterIsoInIncpltCallback(&hpcd_USB_OTG_FS, PCD_ISOINIncompleteCallback); +#endif /* USE_HAL_PCD_REGISTER_CALLBACKS */ + HAL_PCDEx_SetRxFiFo(&hpcd_USB_OTG_FS, 0x80); + HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 0, 0x40); + HAL_PCDEx_SetTxFiFo(&hpcd_USB_OTG_FS, 1, 0x80); + } + return USBD_OK; +} + +/** + * @brief De-Initializes the low level portion of the device driver. + * @param pdev: Device handle + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_DeInit(USBD_HandleTypeDef *pdev) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_DeInit(pdev->pData); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Starts the low level portion of the device driver. + * @param pdev: Device handle + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_Start(USBD_HandleTypeDef *pdev) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_Start(pdev->pData); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Stops the low level portion of the device driver. + * @param pdev: Device handle + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_Stop(USBD_HandleTypeDef *pdev) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_Stop(pdev->pData); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Opens an endpoint of the low level driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint number + * @param ep_type: Endpoint type + * @param ep_mps: Endpoint max packet size + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_OpenEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t ep_type, uint16_t ep_mps) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Open(pdev->pData, ep_addr, ep_mps, ep_type); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Closes an endpoint of the low level driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint number + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_CloseEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Close(pdev->pData, ep_addr); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Flushes an endpoint of the Low Level Driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint number + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_FlushEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Flush(pdev->pData, ep_addr); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Sets a Stall condition on an endpoint of the Low Level Driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint number + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_StallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_SetStall(pdev->pData, ep_addr); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Clears a Stall condition on an endpoint of the Low Level Driver. + * @param pdev: Device handle + * @param ep_addr: Endpoint number + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_ClearStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_ClrStall(pdev->pData, ep_addr); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Returns Stall condition. + * @param pdev: Device handle + * @param ep_addr: Endpoint number + * @retval Stall (1: Yes, 0: No) + */ +uint8_t USBD_LL_IsStallEP(USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + PCD_HandleTypeDef *hpcd = (PCD_HandleTypeDef*) pdev->pData; + + if((ep_addr & 0x80) == 0x80) + { + return hpcd->IN_ep[ep_addr & 0x7F].is_stall; + } + else + { + return hpcd->OUT_ep[ep_addr & 0x7F].is_stall; + } +} + +/** + * @brief Assigns a USB address to the device. + * @param pdev: Device handle + * @param dev_addr: Device address + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_SetUSBAddress(USBD_HandleTypeDef *pdev, uint8_t dev_addr) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_SetAddress(pdev->pData, dev_addr); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Transmits data over an endpoint. + * @param pdev: Device handle + * @param ep_addr: Endpoint number + * @param pbuf: Pointer to data to be sent + * @param size: Data size + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_Transmit(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t *pbuf, uint32_t size) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Transmit(pdev->pData, ep_addr, pbuf, size); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Prepares an endpoint for reception. + * @param pdev: Device handle + * @param ep_addr: Endpoint number + * @param pbuf: Pointer to data to be received + * @param size: Data size + * @retval USBD status + */ +USBD_StatusTypeDef USBD_LL_PrepareReceive(USBD_HandleTypeDef *pdev, uint8_t ep_addr, uint8_t *pbuf, uint32_t size) +{ + HAL_StatusTypeDef hal_status = HAL_OK; + USBD_StatusTypeDef usb_status = USBD_OK; + + hal_status = HAL_PCD_EP_Receive(pdev->pData, ep_addr, pbuf, size); + + usb_status = USBD_Get_USB_Status(hal_status); + + return usb_status; +} + +/** + * @brief Returns the last transferred packet size. + * @param pdev: Device handle + * @param ep_addr: Endpoint number + * @retval Received Data Size + */ +uint32_t USBD_LL_GetRxDataSize(USBD_HandleTypeDef *pdev, uint8_t ep_addr) +{ + return HAL_PCD_EP_GetRxCount((PCD_HandleTypeDef*) pdev->pData, ep_addr); +} + +#ifdef USBD_HS_TESTMODE_ENABLE +/** + * @brief Set High speed Test mode. + * @param pdev: Device handle + * @param testmode: test mode + * @retval USBD Status + */ +USBD_StatusTypeDef USBD_LL_SetTestMode(USBD_HandleTypeDef *pdev, uint8_t testmode) +{ + UNUSED(pdev); + UNUSED(testmode); + + return USBD_OK; +} +#endif /* USBD_HS_TESTMODE_ENABLE */ + +/** + * @brief Static single allocation. + * @param size: Size of allocated memory + * @retval None + */ +void *USBD_static_malloc(uint32_t size) +{ + static uint32_t mem[(sizeof(USBD_CDC_HandleTypeDef)/4)+1];/* On 32-bit boundary */ + return mem; +} + +/** + * @brief Dummy memory free + * @param p: Pointer to allocated memory address + * @retval None + */ +void USBD_static_free(void *p) +{ + +} + +/** + * @brief Delays routine for the USB Device Library. + * @param Delay: Delay in ms + * @retval None + */ +void USBD_LL_Delay(uint32_t Delay) +{ + HAL_Delay(Delay); +} + +/** + * @brief Returns the USB status depending on the HAL status: + * @param hal_status: HAL status + * @retval USB status + */ +USBD_StatusTypeDef USBD_Get_USB_Status(HAL_StatusTypeDef hal_status) +{ + USBD_StatusTypeDef usb_status = USBD_OK; + + switch (hal_status) + { + case HAL_OK : + usb_status = USBD_OK; + break; + case HAL_ERROR : + usb_status = USBD_FAIL; + break; + case HAL_BUSY : + usb_status = USBD_BUSY; + break; + case HAL_TIMEOUT : + usb_status = USBD_FAIL; + break; + default : + usb_status = USBD_FAIL; + break; + } + return usb_status; +} diff --git a/Src/usbd_desc.c b/Src/usbd_desc.c new file mode 100644 index 0000000..41fbf69 --- /dev/null +++ b/Src/usbd_desc.c @@ -0,0 +1,445 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file : usbd_desc.c + * @version : v1.0_Cube + * @brief : This file implements the USB device descriptors. + ****************************************************************************** + * @attention + * + * Copyright (c) 2023 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "usbd_core.h" +#include "usbd_desc.h" +#include "usbd_conf.h" + +/* USER CODE BEGIN INCLUDE */ + +/* USER CODE END INCLUDE */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ + +/* USER CODE BEGIN PV */ +/* Private variables ---------------------------------------------------------*/ + +/* USER CODE END PV */ + +/** @addtogroup STM32_USB_OTG_DEVICE_LIBRARY + * @{ + */ + +/** @addtogroup USBD_DESC + * @{ + */ + +/** @defgroup USBD_DESC_Private_TypesDefinitions USBD_DESC_Private_TypesDefinitions + * @brief Private types. + * @{ + */ + +/* USER CODE BEGIN PRIVATE_TYPES */ + +/* USER CODE END PRIVATE_TYPES */ + +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_Defines USBD_DESC_Private_Defines + * @brief Private defines. + * @{ + */ + +#define USBD_VID 1155 +#define USBD_LANGID_STRING 1033 +#define USBD_MANUFACTURER_STRING "YueLuEmbedded" +#define USBD_PID_FS 202 +#define USBD_PRODUCT_STRING_FS "Vision Comm port" +#define USBD_CONFIGURATION_STRING_FS "CDC Config" +#define USBD_INTERFACE_STRING_FS "CDC Interface" + +#define USB_SIZ_BOS_DESC 0x0C + +/* USER CODE BEGIN PRIVATE_DEFINES */ + +/* USER CODE END PRIVATE_DEFINES */ + +/** + * @} + */ + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/** @defgroup USBD_DESC_Private_Macros USBD_DESC_Private_Macros + * @brief Private macros. + * @{ + */ + +/* USER CODE BEGIN PRIVATE_MACRO */ + +/* USER CODE END PRIVATE_MACRO */ + +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_FunctionPrototypes USBD_DESC_Private_FunctionPrototypes + * @brief Private functions declaration. + * @{ + */ + +static void Get_SerialNum(void); +static void IntToUnicode(uint32_t value, uint8_t * pbuf, uint8_t len); + +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_FunctionPrototypes USBD_DESC_Private_FunctionPrototypes + * @brief Private functions declaration for FS. + * @{ + */ + +uint8_t * USBD_FS_DeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); +uint8_t * USBD_FS_LangIDStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); +uint8_t * USBD_FS_ManufacturerStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); +uint8_t * USBD_FS_ProductStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); +uint8_t * USBD_FS_SerialStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); +uint8_t * USBD_FS_ConfigStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); +uint8_t * USBD_FS_InterfaceStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); +#if (USBD_LPM_ENABLED == 1) +uint8_t * USBD_FS_USR_BOSDescriptor(USBD_SpeedTypeDef speed, uint16_t *length); +#endif /* (USBD_LPM_ENABLED == 1) */ + +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_Variables USBD_DESC_Private_Variables + * @brief Private variables. + * @{ + */ + +USBD_DescriptorsTypeDef FS_Desc = +{ + USBD_FS_DeviceDescriptor +, USBD_FS_LangIDStrDescriptor +, USBD_FS_ManufacturerStrDescriptor +, USBD_FS_ProductStrDescriptor +, USBD_FS_SerialStrDescriptor +, USBD_FS_ConfigStrDescriptor +, USBD_FS_InterfaceStrDescriptor +#if (USBD_LPM_ENABLED == 1) +, USBD_FS_USR_BOSDescriptor +#endif /* (USBD_LPM_ENABLED == 1) */ +}; + +#if defined ( __ICCARM__ ) /* IAR Compiler */ + #pragma data_alignment=4 +#endif /* defined ( __ICCARM__ ) */ +/** USB standard device descriptor. */ +__ALIGN_BEGIN uint8_t USBD_FS_DeviceDesc[USB_LEN_DEV_DESC] __ALIGN_END = +{ + 0x12, /*bLength */ + USB_DESC_TYPE_DEVICE, /*bDescriptorType*/ +#if (USBD_LPM_ENABLED == 1) + 0x01, /*bcdUSB */ /* changed to USB version 2.01 + in order to support LPM L1 suspend + resume test of USBCV3.0*/ +#else + 0x00, /*bcdUSB */ +#endif /* (USBD_LPM_ENABLED == 1) */ + 0x02, + 0x02, /*bDeviceClass*/ + 0x02, /*bDeviceSubClass*/ + 0x00, /*bDeviceProtocol*/ + USB_MAX_EP0_SIZE, /*bMaxPacketSize*/ + LOBYTE(USBD_VID), /*idVendor*/ + HIBYTE(USBD_VID), /*idVendor*/ + LOBYTE(USBD_PID_FS), /*idProduct*/ + HIBYTE(USBD_PID_FS), /*idProduct*/ + 0x00, /*bcdDevice rel. 2.00*/ + 0x02, + USBD_IDX_MFC_STR, /*Index of manufacturer string*/ + USBD_IDX_PRODUCT_STR, /*Index of product string*/ + USBD_IDX_SERIAL_STR, /*Index of serial number string*/ + USBD_MAX_NUM_CONFIGURATION /*bNumConfigurations*/ +}; + +/* USB_DeviceDescriptor */ +/** BOS descriptor. */ +#if (USBD_LPM_ENABLED == 1) +#if defined ( __ICCARM__ ) /* IAR Compiler */ + #pragma data_alignment=4 +#endif /* defined ( __ICCARM__ ) */ +__ALIGN_BEGIN uint8_t USBD_FS_BOSDesc[USB_SIZ_BOS_DESC] __ALIGN_END = +{ + 0x5, + USB_DESC_TYPE_BOS, + 0xC, + 0x0, + 0x1, /* 1 device capability*/ + /* device capability*/ + 0x7, + USB_DEVICE_CAPABITY_TYPE, + 0x2, + 0x2, /* LPM capability bit set*/ + 0x0, + 0x0, + 0x0 +}; +#endif /* (USBD_LPM_ENABLED == 1) */ + +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_Variables USBD_DESC_Private_Variables + * @brief Private variables. + * @{ + */ + +#if defined ( __ICCARM__ ) /* IAR Compiler */ + #pragma data_alignment=4 +#endif /* defined ( __ICCARM__ ) */ + +/** USB lang identifier descriptor. */ +__ALIGN_BEGIN uint8_t USBD_LangIDDesc[USB_LEN_LANGID_STR_DESC] __ALIGN_END = +{ + USB_LEN_LANGID_STR_DESC, + USB_DESC_TYPE_STRING, + LOBYTE(USBD_LANGID_STRING), + HIBYTE(USBD_LANGID_STRING) +}; + +#if defined ( __ICCARM__ ) /* IAR Compiler */ + #pragma data_alignment=4 +#endif /* defined ( __ICCARM__ ) */ +/* Internal string descriptor. */ +__ALIGN_BEGIN uint8_t USBD_StrDesc[USBD_MAX_STR_DESC_SIZ] __ALIGN_END; + +#if defined ( __ICCARM__ ) /*!< IAR Compiler */ + #pragma data_alignment=4 +#endif +__ALIGN_BEGIN uint8_t USBD_StringSerial[USB_SIZ_STRING_SERIAL] __ALIGN_END = { + USB_SIZ_STRING_SERIAL, + USB_DESC_TYPE_STRING, +}; + +/** + * @} + */ + +/** @defgroup USBD_DESC_Private_Functions USBD_DESC_Private_Functions + * @brief Private functions. + * @{ + */ + +/** + * @brief Return the device descriptor + * @param speed : Current device speed + * @param length : Pointer to data length variable + * @retval Pointer to descriptor buffer + */ +uint8_t * USBD_FS_DeviceDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) +{ + UNUSED(speed); + *length = sizeof(USBD_FS_DeviceDesc); + return USBD_FS_DeviceDesc; +} + +/** + * @brief Return the LangID string descriptor + * @param speed : Current device speed + * @param length : Pointer to data length variable + * @retval Pointer to descriptor buffer + */ +uint8_t * USBD_FS_LangIDStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) +{ + UNUSED(speed); + *length = sizeof(USBD_LangIDDesc); + return USBD_LangIDDesc; +} + +/** + * @brief Return the product string descriptor + * @param speed : Current device speed + * @param length : Pointer to data length variable + * @retval Pointer to descriptor buffer + */ +uint8_t * USBD_FS_ProductStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) +{ + if(speed == 0) + { + USBD_GetString((uint8_t *)USBD_PRODUCT_STRING_FS, USBD_StrDesc, length); + } + else + { + USBD_GetString((uint8_t *)USBD_PRODUCT_STRING_FS, USBD_StrDesc, length); + } + return USBD_StrDesc; +} + +/** + * @brief Return the manufacturer string descriptor + * @param speed : Current device speed + * @param length : Pointer to data length variable + * @retval Pointer to descriptor buffer + */ +uint8_t * USBD_FS_ManufacturerStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) +{ + UNUSED(speed); + USBD_GetString((uint8_t *)USBD_MANUFACTURER_STRING, USBD_StrDesc, length); + return USBD_StrDesc; +} + +/** + * @brief Return the serial number string descriptor + * @param speed : Current device speed + * @param length : Pointer to data length variable + * @retval Pointer to descriptor buffer + */ +uint8_t * USBD_FS_SerialStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) +{ + UNUSED(speed); + *length = USB_SIZ_STRING_SERIAL; + + /* Update the serial number string descriptor with the data from the unique + * ID */ + Get_SerialNum(); + /* USER CODE BEGIN USBD_FS_SerialStrDescriptor */ + + /* USER CODE END USBD_FS_SerialStrDescriptor */ + return (uint8_t *) USBD_StringSerial; +} + +/** + * @brief Return the configuration string descriptor + * @param speed : Current device speed + * @param length : Pointer to data length variable + * @retval Pointer to descriptor buffer + */ +uint8_t * USBD_FS_ConfigStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) +{ + if(speed == USBD_SPEED_HIGH) + { + USBD_GetString((uint8_t *)USBD_CONFIGURATION_STRING_FS, USBD_StrDesc, length); + } + else + { + USBD_GetString((uint8_t *)USBD_CONFIGURATION_STRING_FS, USBD_StrDesc, length); + } + return USBD_StrDesc; +} + +/** + * @brief Return the interface string descriptor + * @param speed : Current device speed + * @param length : Pointer to data length variable + * @retval Pointer to descriptor buffer + */ +uint8_t * USBD_FS_InterfaceStrDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) +{ + if(speed == 0) + { + USBD_GetString((uint8_t *)USBD_INTERFACE_STRING_FS, USBD_StrDesc, length); + } + else + { + USBD_GetString((uint8_t *)USBD_INTERFACE_STRING_FS, USBD_StrDesc, length); + } + return USBD_StrDesc; +} + +#if (USBD_LPM_ENABLED == 1) +/** + * @brief Return the BOS descriptor + * @param speed : Current device speed + * @param length : Pointer to data length variable + * @retval Pointer to descriptor buffer + */ +uint8_t * USBD_FS_USR_BOSDescriptor(USBD_SpeedTypeDef speed, uint16_t *length) +{ + UNUSED(speed); + *length = sizeof(USBD_FS_BOSDesc); + return (uint8_t*)USBD_FS_BOSDesc; +} +#endif /* (USBD_LPM_ENABLED == 1) */ + +/** + * @brief Create the serial number string descriptor + * @param None + * @retval None + */ +static void Get_SerialNum(void) +{ + uint32_t deviceserial0; + uint32_t deviceserial1; + uint32_t deviceserial2; + + deviceserial0 = *(uint32_t *) DEVICE_ID1; + deviceserial1 = *(uint32_t *) DEVICE_ID2; + deviceserial2 = *(uint32_t *) DEVICE_ID3; + + deviceserial0 += deviceserial2; + + if (deviceserial0 != 0) + { + IntToUnicode(deviceserial0, &USBD_StringSerial[2], 8); + IntToUnicode(deviceserial1, &USBD_StringSerial[18], 4); + } +} + +/** + * @brief Convert Hex 32Bits value into char + * @param value: value to convert + * @param pbuf: pointer to the buffer + * @param len: buffer length + * @retval None + */ +static void IntToUnicode(uint32_t value, uint8_t * pbuf, uint8_t len) +{ + uint8_t idx = 0; + + for (idx = 0; idx < len; idx++) + { + if (((value >> 28)) < 0xA) + { + pbuf[2 * idx] = (value >> 28) + '0'; + } + else + { + pbuf[2 * idx] = (value >> 28) + 'A' - 10; + } + + value = value << 4; + + pbuf[2 * idx + 1] = 0; + } +} +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + diff --git a/application/APP层应用编写指引.md b/application/APP层应用编写指引.md new file mode 100644 index 0000000..4158dd7 --- /dev/null +++ b/application/APP层应用编写指引.md @@ -0,0 +1,70 @@ +# APP层应用编写指引 + +
© COPYRIGHT(c) 2019 STMicroelectronics neozng1@hnu.edu.cn
+ +## 通信机制 + +**应用之间不应该有任何包含关系,它们必须是平行工作的。**而这通过pub-sub的机制实现。module层提供了`message_center`模块,支持发布订阅者的消息订阅机制。以传统的框架为例,负责整车控制的应用和其他应用(或任务)是从属的树状结构,或不同的任务和应用之间通过全局变量传递消息(**请不要使用全局变量!**),而此框架下的不同应用是并行的关系。 + +如果一个应用希望获取另一个应用的数据,那么他应该**订阅**由此此应用发布的话题。一个应用要把自己希望共享的数据,注册到消息中心,即**发布**。为了区别不同的消息来源(你希望订阅谁的消息?哪一个消息?),可以通过**话题名**进行订阅。也就是说,消息中心作为第三方,管理所有的消息发布者和订阅者,它像报刊亭一样对消息进行中转,使得不同的应用之间不需要包含彼此,更不用全局变量也能共享消息。 + +> 更多关于发布-订阅的实现,请参考`modules/message_center`下的文档。 + + +## robot_def.h + +这是机器人的参数配置文件,必须要针对每个机器人进行修改。包括机器人的尺寸参数和性能参数等。你还需要在这里设定软硬件配置:云台板/底盘板/单板等。这里定义的宏会作为条件编译的决断。 + +app层共用的状态变量和结构体等也应该定义在这里(例如用于应用之间通信的数据)。记得用于通信的变量要用: +```c +#pragma pack(1) +typedef struct +{ + // your struct + +} your_struct; +#pragma pack() +``` +包裹起来,取消字节对齐以防止出现访问8-bit地址而出现错误。 + +如果你需要其他的通信数据类型或修改模块间通信数据的格式,直接在此处更改即可。 + +## robot_cmd + +机器人命令模块是对整个机器人的抽象,对于单板控制整车的情况,该应用应该包含接收控制指令的模块,例如遥控器、视觉通信模块。该模块会处理接收到的控制数据,并将其转化为**具体的、定量的**控制信息,发送给其他模块。同时,cmd应用会处理模块和应用离线的情况,出现紧急状况时停止所有执行机构的运行。 + +如从遥控器获知当前右侧摇杆拨向上方,则将遥控器发来的数值转化为底盘前进的速度值,然后发送给其他应用。同时,robot_cmd还要从其他应用获取反馈信息,做出其他决策。可以将其视为整个机器人的**大脑**。 + +robot_cmd工作起来就像一个遥控数据的兼容层,不论数据的来源是视觉上位机/遥控器/键鼠/图传通信链路/ps手柄,最后都会被转化成真实参考输入提供给其他的app。它的任务是将其他来源的数据映射到控制输入上。 + + + +## gimbal + +以步兵为例,云台应用应当包含两个电机,分别用于驱动yaw和pitch轴(除非你是一个三轴的云台),还有一个imu(开发板一般放在云台上)。gimbal模块会接收robot_cmd发来的控制信息(云台的角度、转速等),并通过电机提供的接口完成电机的参考值设定。gimbal还要把imu的数据反馈给cmd,用于和视觉的通信以及云台状态的判断。 + + + +## shoot + +还是以步兵为例,发射应用应当包括摩擦轮电机、拨盘电机和弹舱盖。根据cmd应用发来的控制信息,决定当前的发射模式(单发、双发、连发),弹舱盖的开合,以及射速(15?18?30?)等。 + + + +## chassis + +以步兵为例,底盘应该包括4个电机。根据cmd应用发来的控制信息,进行麦克纳姆轮的运动学解算,从而获知四个电机需要的设定值,然后调用电机提供的接口进行设定。chassis还要根据电机的反馈数据以及imu信息(如果有imu的话,即双板的情况,云台一个底盘一个),计算底盘的实际运动状态,反馈给robot_cmd应用。 + + + +## lift + +以工程机器人为例,抬升机构应该包含用于抬升的执行单元(可能是气缸、电磁阀、电机、点推杆等),根据cmd发来的数据控制执行单元运行到特定的高度,并进行必要的反馈。 + + + +## 双板兼容 + +此框架对单开发板/双开发板/多开发板的情况都提供了支持(多板一般只在工程机器人上出现,需要自己在robot_cmd和robot_def增加相应的条件编译选项,robot.c中也不要忘记增加初始化和任务运行函数),目前通过条件编译实现了对单双板的切换。使用双板时,主控板在云台上,连接遥控器和上位机;副板在底盘上,负责底盘的运动控制和与裁判系统的通信。 + +当然,你可以为每台不同的机器人进行特化,因为本框架是针对步兵/英雄定制的。 diff --git a/application/application.md b/application/application.md new file mode 100644 index 0000000..9e9636b --- /dev/null +++ b/application/application.md @@ -0,0 +1,52 @@ +# application + +neozng1@hnu.edu.cn
+ +这是application层的说明。 + +> todo: 是否有必要将所有电机等模块的初始化参数放到一个头文件? + +## 使用说明 + +在main函数中包含`robot.h`头文件,这是对整车的抽象。将`INStask`,`motortask`,`ledtask`,`monitortask`这四个task加入`freertos.c`中,创建对应的任务,设置合适的任务运行间隔;然后将`robottask`放入freertos.c中,同样以一定的频率运行。 在初始化实时系统之前,在`main()`中调用`RobotInit()`进行整车的初始化。 + +**关于运行的任务**,INStask的运行频率必须为1kHz,motortask推荐的运行频率为200Hz\~1000Hz(详情见module/motor/motor_task.c),在MotorTask内部,对于高实时性要求的电机可以提升到1kHz,不过要注意CAN总线的负载。monitortask的运行频率为100Hz;robottask的运行频率推荐为150Hz以上,应当高于视觉发送的频率,若后续使用插帧,同样应该保证不低过motortask太多。 + +若使用双板,则在`robot_def.h`中给对应的开发板设定宏定义,如底盘板使用`#define CHASSIS_BOARD`,云台板使用`#define GIMBAL_BOARD`;单个开发板控制整车,则定义`#define ONE_BOARD`。在每个应用中,都已经使用编译预处理指令完成条件编译,会自动根据设定的宏切换功能。使用双板的时候,目前板间通信通过CAN完成,因此两个开发板会挂载在一条总线上,在两个开发板对这条总线的其他使用CAN的设备进行配置时注意**不要发生ID冲突**,还要注意**防止负载过大**。 + +**同样,在该文件中你需要修改一些关于机器人的参数**。比如底盘和云台对齐时yaw电机编码器的值,拨盘的单圈载弹量、底盘的轴距等等。 + + + +## 封装总览 + +Robot.c是整个机器人的抽象,其下有4个应用:robot_cmd,gimbal,chassis,shoot。此框架当前是针对步兵/英雄/哨兵设计的,其他机器人只需要根据各自的特殊机构进行修改即可。robot_cmd是整个机器人的核心应用,其负责接受遥控器/上位机发来的指令,并将指令转化为实际的运动控制目标,发送给其他三个应用。后者会根据robot_cmd发来的命令,设定电机和其他执行单元的参考值等。 + +为了进一步解耦应用之间的关系,app层并没有module和bsp之间的那种层级结构(或设计模式中所谓的**结构类型模式**,即robot_cmd包含其他三个模块),而采用了应用并列的**发布-订阅**机制,四个应用之间没有任何相互包含关系,他们之间的通信通过module层提供的`message_center`实现。每个应用会通过该模块向一些话题(事件)发布一些消息,同时从一些话题订阅消息。如robot_cmd应用会发布其他三个模块的控制信息,同时订阅其他三个模块的反馈信息。其他三个模块会订阅robot_cmd发布的控制信息,同时发布反馈给robot_cmd的信息,他们不需要知道彼此的存在,只是从`message_center`处获取其他应用发布的消息或向自己发布的话题推送消息。 + +application在初始化module的时候,初始化参数会包含部分bsp的内容,但仅仅是外设和引脚的选择以及id设置(用于通信的外设需要id设置)。实际上当前框架的app层和cubemx初始化部分耦合,在配置的时候就必须确定每个外设的作用和归属权,一旦cubemx完成设置app层必须按照对应参数设置引脚和并分配module的外设。后续考虑将cubemx和bsp耦合,去除顶层代码和底层的关系 + + + +## 整车程序流程 + +```mermaid +graph TD +main调用RobotInit进行初始化 --> RobotInit调用基础bsp初始化以及各个app的初始化 --> 各个app进行消息订阅初始化和自有模块的初始化 --> 启动实时系统 --> 各任务开始运行 + +``` + +任务开始之后,每个app之间的交互关系如下: + +```mermaid +graph TD +robot_cmd获取遥控器/上位机指令以及各个应用发布的回传信息 --> 将指令转化为具体的控制信息 --> 发布指令到对应话题 +``` + +gimbal/chassis/shoot则根据订阅的robot_cmd发布的消息,将具体的控制信息根据当前模式转化为执行单元的目标值,通过自己拥有的模块完成这些指令,然后把回传的信息发布到对应话题。 + +每个应用的具体流程和实现,参见它们各自的说明文档。 + +## 开发要点 + +各个应用之间务必通过`message_center`以发布-订阅的方式进行消息交换,不要出现包含关系,这可以大大减小耦合度并提高合作开发的效率。 diff --git a/application/chassis/chassis.c b/application/chassis/chassis.c new file mode 100644 index 0000000..41b6e10 --- /dev/null +++ b/application/chassis/chassis.c @@ -0,0 +1,442 @@ +/** + * @file chassis.c + * @author NeoZeng neozng1@hnu.edu.cn + * @brief 底盘应用,负责接收robot_cmd的控制命令并根据命令进行运动学解算,得到输出 + * 注意底盘采取右手系,对于平面视图,底盘纵向运动的正前方为x正方向;横向运动的右侧为y正方向 + * + * @version 0.1 + * @date 2022-12-04 + * + * @copyright Copyright (c) 2022 + * + */ + +#include "chassis.h" +#include "robot_def.h" +#include "dji_motor.h" +#include "LKMotor.h" +#include "super_cap.h" +#include "message_center.h" +#include "referee_task.h" +#include "user_lib.h" + +#include "general_def.h" +#include "bsp_dwt.h" +#include "referee_UI.h" +#include "arm_math.h" + +/* 根据robot_def.h中的macro自动计算的参数 */ +#define HALF_WHEEL_BASE (WHEEL_BASE / 2.0f) // 半轴距 +#define HALF_TRACK_WIDTH (TRACK_WIDTH / 2.0f) // 半轮距 +#define PERIMETER_WHEEL (RADIUS_WHEEL * 2 * PI) // 轮子周长 +#if defined(CHASSIS_MCNAMEE_WHEEL) +#define CHASSIS_WHEEL_OFFSET 1.0f // 机器人底盘轮子修正偏移量 +#elif defined(CHASSIS_STEERING_WHEEL) +#define CHASSIS_WHEEL_OFFSET 30.0f // 机器人底盘轮子修正偏移量 +#define SQRT2 1.41421356f // 根号2 +#elif defined(CHASSIS_OMNI_WHEEL) +#define CHASSIS_WHEEL_OFFSET 0.7071f // 机器人底盘轮子修正偏移量,根号2/2,即45度,用于修正全向轮的安装位置 +#endif // CHASSIS_OMNI_WHEEL + +/* 底盘应用包含的模块和信息存储,底盘是单例模式,因此不需要为底盘建立单独的结构体 */ +#ifdef CHASSIS_BOARD // 如果是底盘板,使用板载IMU获取底盘转动角速度 +#include "can_comm.h" +#include "ins_task.h" +static CANCommInstance *chasiss_can_comm; // 双板通信CAN comm +attitude_t *Chassis_IMU_data; +#endif // CHASSIS_BOARD +#ifdef ONE_BOARD +static Publisher_t *chassis_pub; // 用于发布底盘的数据 +static Subscriber_t *chassis_sub; // 用于订阅底盘的控制命令 +#endif // !ONE_BOARD +static Chassis_Ctrl_Cmd_s chassis_cmd_recv; // 底盘接收到的控制命令 +static Chassis_Upload_Data_s chassis_feedback_data; // 底盘回传的反馈数据 + +static referee_info_t* referee_data; // 用于获取裁判系统的数据 +static Referee_Interactive_info_t ui_data; // UI数据,将底盘中的数据传入此结构体的对应变量中,UI会自动检测是否变化,对应显示UI + +static SuperCapInstance *cap; // 超级电容 +static LKMotorInstance *motor_lf,*motor_rb; // 轮电机9015 +static DJIMotorInstance *motor_steering_lf,*motor_steering_rb; // 舵电机6020 +/* 用于自旋变速策略的时间变量 */ +// static float t; + +/* 私有函数计算的中介变量,设为静态避免参数传递的开销 */ +static float chassis_vx, chassis_vy; // 将云台系的速度投影到底盘 +static float vt_lf, vt_rb; // 底盘速度解算后的临时输出,待进行限幅 +static float at_lf, at_rb; // 底盘的角度解算后的临时输出,待进行限幅 +static PIDInstance chassis_follow_pid; // 底盘跟随云台的PID + +void ChassisInit() +{ + // 轮电机9015初始化 + Motor_Init_Config_s chassis_motor_config = { + .can_init_config.can_handle = &hcan1, + .controller_param_init_config = { + .speed_PID = { + .Kp = 95, // 4.5 + .Ki = 0, // 0 + .Kd = 0, // 0 + .IntegralLimit = 8000, + .Improve = PID_Trapezoid_Intergral | PID_Integral_Limit | PID_Derivative_On_Measurement, + .MaxOut = 12000, + }, + .current_PID = { + .Kp = 1, // 0.4 + .Ki = 0, // 0 + .Kd = 0, + .IntegralLimit = 10500, + .Improve = PID_Trapezoid_Intergral | PID_Integral_Limit | PID_Derivative_On_Measurement, + .MaxOut = 20000, + }, + }, + .controller_setting_init_config = { + .angle_feedback_source = MOTOR_FEED, + .speed_feedback_source = MOTOR_FEED, + .outer_loop_type = SPEED_LOOP, + .close_loop_type = SPEED_LOOP | CURRENT_LOOP, + }, + .motor_type = LK9015, + }; + // @todo: 当前还没有设置电机的正反转,仍然需要手动添加reference的正负号,需要电机module的支持,待修改. + + chassis_motor_config.can_init_config.tx_id = 1; + // chassis_motor_config.controller_setting_init_config.motor_reverse_flag = MOTOR_DIRECTION_REVERSE; + motor_rb = LKMotorInit(&chassis_motor_config); + + chassis_motor_config.can_init_config.tx_id = 2; + // chassis_motor_config.controller_setting_init_config.motor_reverse_flag = MOTOR_DIRECTION_REVERSE; + motor_lf = LKMotorInit(&chassis_motor_config); + + // 舵电机6020初始化 + Motor_Init_Config_s chassis_motor_steering_config = { + .can_init_config.can_handle = &hcan1, + .controller_param_init_config = { + .angle_PID = { + .Kp = 12, + .Ki = 0.2, + .Kd = 0, + .CoefA = 3, + .CoefB = 0.1, + .Improve = PID_Trapezoid_Intergral | PID_Integral_Limit | PID_Derivative_On_Measurement | PID_DerivativeFilter | PID_ChangingIntegrationRate, + .IntegralLimit = 1000, + .MaxOut = 5000, + .Derivative_LPF_RC = 0.001, + .DeadBand = 0.5, + }, + .speed_PID = { + .Kp = 40, + .Ki = 3, + .Kd = 0, + .Improve = PID_Integral_Limit | PID_Derivative_On_Measurement | PID_ChangingIntegrationRate | PID_OutputFilter, + .IntegralLimit = 4000, + .MaxOut = 20000, + .Output_LPF_RC = 0.03, + }, + }, + .controller_setting_init_config = { + .angle_feedback_source = MOTOR_FEED, + .speed_feedback_source = MOTOR_FEED, + .outer_loop_type = ANGLE_LOOP, + .close_loop_type = ANGLE_LOOP | SPEED_LOOP, + .motor_reverse_flag = MOTOR_DIRECTION_NORMAL, + }, + .motor_type = GM6020, + }; + + chassis_motor_steering_config.can_init_config.tx_id = 1; + motor_steering_rb = DJIMotorInit(&chassis_motor_steering_config); + + chassis_motor_steering_config.can_init_config.tx_id = 2; + motor_steering_lf = DJIMotorInit(&chassis_motor_steering_config); + + PID_Init_Config_s chassis_follow_pid_conf = { + .Kp = 20, // 6 + .Ki = 0, + .Kd = 3, // 0.5 + .DeadBand = 0.5f, + //.CoefA = 0.2, + //.CoefB = 0.3, + //.Improve = PID_Trapezoid_Intergral | PID_DerivativeFilter | PID_DerivativeFilter | PID_Derivative_On_Measurement | PID_Integral_Limit | PID_Derivative_On_Measurement, + //.IntegralLimit = 50, // 200 + .MaxOut = 45, + //.Derivative_LPF_RC = 0.01, // 0.01 + }; + PIDInit(&chassis_follow_pid, &chassis_follow_pid_conf); + + // 裁判系统初始化 + + referee_data = UITaskInit(&huart6,&ui_data); // 裁判系统初始化,会同时初始化UI + + SuperCap_Init_Config_s cap_conf = { + .can_config = { + .can_handle = &hcan2, + .tx_id = 0x302, // 超级电容默认接收id + .rx_id = 0x301, // 超级电容默认发送id,注意tx和rx在其他人看来是反的 + }}; + cap = SuperCapInit(&cap_conf); // 超级电容初始化 + + // 发布订阅初始化,如果为双板,则需要can comm来传递消息 +#ifdef CHASSIS_BOARD + Chassis_IMU_data = INS_Init(); // 底盘IMU初始化 + + CANComm_Init_Config_s comm_conf = { + .can_config = { + .can_handle = &hcan2, + .tx_id = 0x311, + .rx_id = 0x312, + }, + .recv_data_len = sizeof(Chassis_Ctrl_Cmd_s), + .send_data_len = sizeof(Chassis_Upload_Data_s), + }; + chasiss_can_comm = CANCommInit(&comm_conf); // can comm初始化 +#endif // CHASSIS_BOARD + +#ifdef ONE_BOARD // 单板控制整车,则通过pubsub来传递消息 + chassis_sub = SubRegister("chassis_cmd", sizeof(Chassis_Ctrl_Cmd_s)); + chassis_pub = PubRegister("chassis_feed", sizeof(Chassis_Upload_Data_s)); +#endif // ONE_BOARD +} + +// #define LF_CENTER ((HALF_TRACK_WIDTH + CENTER_GIMBAL_OFFSET_X + HALF_WHEEL_BASE - CENTER_GIMBAL_OFFSET_Y) * DEGREE_2_RAD) +// #define RF_CENTER ((HALF_TRACK_WIDTH - CENTER_GIMBAL_OFFSET_X + HALF_WHEEL_BASE - CENTER_GIMBAL_OFFSET_Y) * DEGREE_2_RAD) +// #define LB_CENTER ((HALF_TRACK_WIDTH + CENTER_GIMBAL_OFFSET_X + HALF_WHEEL_BASE + CENTER_GIMBAL_OFFSET_Y) * DEGREE_2_RAD) +// #define RB_CENTER ((HALF_TRACK_WIDTH - CENTER_GIMBAL_OFFSET_X + HALF_WHEEL_BASE + CENTER_GIMBAL_OFFSET_Y) * DEGREE_2_RAD) + +// static void SteeringWheelRotateHandle() +// { +// if (fabsf(chassis_cmd_recv.vx) > 0 || fabsf(chassis_cmd_recv.vy) > 0) { +// chassis_cmd_recv.wz = 0; +// } +// } + +/** + * @brief 使舵电机角度最小旋转,取优弧,防止电机旋转不必要的行程 + * 例如:上次角度为0,目标角度为135度, + * 电机会选择逆时针旋转至-45度,而不是顺时针旋转至135度, + * 两个角度都会让轮电机处于同一平行线上 + * + * @param angle 目标角度 + * @param last_angle 上次角度 + * + */ +static void MinmizeRotation(float *angle, const float *last_angle, float *speed) +{ + float target_angle = *angle; + float actual_angle = *last_angle; + float rotation = target_angle - actual_angle; + float norm_rotation = rotation; + while (norm_rotation > 180.0f) { + norm_rotation -= 360.0f; + } + while (norm_rotation < -180.0f) { + norm_rotation += 360.0f; + } + float threshold = 90.0f; + float target_single=fmodf(target_angle,360.0f); + if(target_single<0.0f) target_single+=360.0f; + + float current_single=fmodf(actual_angle,360.0f); + if(current_single<0.0f) current_single+=360.0f; + + + if (fabsf(norm_rotation) > threshold) { + int32_t round_diff = (int32_t)(target_angle / 360.0f) - (int32_t)(actual_angle / 360.0f); + *angle = actual_angle + norm_rotation-180.0f+round_diff*360.0f; + *speed = -(*speed); + }else if(norm_rotation<-threshold){ + int32_t round_diff = (int32_t)(target_angle / 360.0f) - (int32_t)(actual_angle / 360.0f); + *angle = actual_angle + norm_rotation+180.0f+round_diff*360.0f; + *speed = -(*speed); + } + ANGLE_LIMIT_360_TO_180_ABS(*angle); + // float rotation = *angle - *last_angle; + // ANGLE_LIMIT_360_TO_180_ABS(rotation); + // if (rotation > 90) { + // *angle -= 180; + // *speed = -(*speed); + // } else if (rotation < -90) { + // *angle += 180; + // *speed = -(*speed); + // } + // ANGLE_LIMIT_360_TO_180_ABS(*angle); +} + +/** + * @brief 舵轮电机角度解算 + * + */ +static void SteeringWheelCalculate() +{ + float offset_lf, offset_rb; // 用于计算舵轮的角度 + float at_lf_last, at_rb_last; // 上次的角度 + at_lf_last = motor_steering_lf->measure.total_angle; + at_rb_last = motor_steering_rb->measure.total_angle; + if (chassis_vx == 0 && chassis_vy == 0 && chassis_cmd_recv.wz == 0) { + // at_lf = at_lf_last; + // at_rf = at_rf_last; + // at_lb = at_lb_last; + // at_rb = at_rb_last; + vt_lf = 0, vt_rb = 0; + } else { + // 生成预计算变量,减少计算量,空间换时间 + float w = chassis_cmd_recv.wz * CHASSIS_WHEEL_OFFSET * SQRT2; + float temp_x = chassis_vx - w, temp_y = chassis_vy - w; + arm_sqrt_f32(temp_x * temp_x + temp_y * temp_y, &vt_lf); // lf:y- , x- + temp_y = chassis_vy + w; // 重复利用变量,temp_x = chassis_vy - w;与上次相同因此注释 + // arm_sqrt_f32(temp_x * temp_x + temp_y * temp_y, &vt_lb); // lb: y+ , x- + // temp_x = chassis_vx + w; // temp_y = chassis_vx + w;与上次相同因此注释 + arm_sqrt_f32(temp_x * temp_x + temp_y * temp_y, &vt_rb); // rb: y+ , x+ + temp_y = chassis_vy - w; // temp_x = chassis_vy + w;与上次相同因此注释 + // arm_sqrt_f32(temp_x * temp_x + temp_y * temp_y, &vt_rf); // rf: y- , x+ + + // 计算角度偏移 + offset_lf = atan2f(chassis_vx - w, chassis_vy - w) * RAD_2_DEGREE; // lf: y- , x- + offset_rb = atan2f(chassis_vx + w, chassis_vy + w) * RAD_2_DEGREE; // rb: y+ , x+ + + at_lf = STEERING_CHASSIS_ALIGN_ANGLE_LF + offset_lf; // 此处似乎不需要加上真实角度,因为我们需要的是绝对角度而不是相对角度 + at_rb = STEERING_CHASSIS_ALIGN_ANGLE_RB + offset_rb; + + ANGLE_LIMIT_360_TO_180_ABS(at_lf); + ANGLE_LIMIT_360_TO_180_ABS(at_rb); + + MinmizeRotation(&at_lf, &at_lf_last, &vt_lf); + MinmizeRotation(&at_rb, &at_rb_last, &vt_rb); + } + + DJIMotorSetRef(motor_steering_lf, at_lf); + DJIMotorSetRef(motor_steering_rb, at_rb); +} + +/** + * @brief 计算每个轮毂电机的输出,正运动学解算 + * 用宏进行预替换减小开销,运动解算具体过程参考教程 + */ +// static void MecanumCalculate() +// { +// vt_lf = -chassis_vx - chassis_vy - chassis_cmd_recv.wz * LF_CENTER; +// vt_rf = -chassis_vx + chassis_vy - chassis_cmd_recv.wz * RF_CENTER; +// vt_lb = chassis_vx - chassis_vy - chassis_cmd_recv.wz * LB_CENTER; +// vt_rb = chassis_vx + chassis_vy - chassis_cmd_recv.wz * RB_CENTER; +// } + +/** + * @brief 根据裁判系统和电容剩余容量对输出进行限制并设置电机参考值 + * + */ +static void LimitChassisOutput() +{ + // 功率限制待添加 + // referee_data->PowerHeatData.chassis_power; + // referee_data->PowerHeatData.chassis_power_buffer; + + // 完成功率限制后进行电机参考输入设定 + + // LKMotorSetRef( motor_lf , vt_lf ); + // LKMotorSetRef( motor_rb , vt_rb ); + + LKMotorSetRef( motor_lf , vt_lf ); + LKMotorSetRef( motor_rb , vt_rb ); +} + +/** + * @brief 根据每个轮子的速度反馈,计算底盘的实际运动速度,逆运动解算 + * 对于双板的情况,考虑增加来自底盘板IMU的数据 + * + */ +static void EstimateSpeed() +{ + // 根据电机速度和陀螺仪的角速度进行解算,还可以利用加速度计判断是否打滑(如果有) + // chassis_feedback_data.vx vy wz = + // ... +} + +/* 机器人底盘控制核心任务 */ +void ChassisTask() +{ + // 后续增加没收到消息的处理(双板的情况) + // 获取新的控制信息 +#ifdef ONE_BOARD + SubGetMessage(chassis_sub, &chassis_cmd_recv); +#endif +#ifdef CHASSIS_BOARD + chassis_cmd_recv = *(Chassis_Ctrl_Cmd_s *)CANCommGet(chasiss_can_comm); +#endif // CHASSIS_BOARD + + if (chassis_cmd_recv.chassis_mode == CHASSIS_ZERO_FORCE) + { // 如果出现重要模块离线或遥控器设置为急停,让电机停止 + LKMotorStop(motor_lf); + LKMotorStop(motor_rb); + DJIMotorStop(motor_steering_lf); + DJIMotorStop(motor_steering_rb); + } + else + { + // 正常工作 + LKMotorEnable(motor_lf); + LKMotorEnable(motor_rb); + DJIMotorEnable(motor_steering_lf); + DJIMotorEnable(motor_steering_rb); + } + + // 根据控制模式设定旋转速度 + switch (chassis_cmd_recv.chassis_mode) + { + case CHASSIS_NO_FOLLOW: // 底盘不旋转,但维持全向机动,一般用于调整云台姿态 + chassis_cmd_recv.wz = 0; + break; + case CHASSIS_FOLLOW_GIMBAL_YAW: // 跟随云台,不单独设置pid,以误差角度平方为速度输出 + float single_round_offset = chassis_cmd_recv.offset_angle; + // float single_round_offset = fmodf(chassis_cmd_recv.offset_angle, 360.0f); + if(single_round_offset > 180.0f) + { + single_round_offset -= 360.0f; + } + else if(single_round_offset < -180.0f) + { + single_round_offset += 360.0f; + + } + chassis_cmd_recv.wz = PIDCalculate(&chassis_follow_pid, single_round_offset, 0)/100; + // chassis_cmd_recv.wz = PIDCalculate(&chassis_follow_pid, chassis_cmd_recv.offset_angle, 0)/100; + break; + case CHASSIS_ROTATE: // 自旋,同时保持全向机动;当前wz维持定值,后续增加不规则的变速策略 + chassis_cmd_recv.wz = 0.5; + break; + default: + break; + } + + // 根据云台和底盘的角度offset将控制量映射到底盘坐标系上 + // 底盘逆时针旋转为角度正方向;云台命令的方向以云台指向的方向为x,采用右手系(x指向正北时y在正东) + static float sin_theta, cos_theta; + cos_theta = arm_cos_f32(chassis_cmd_recv.offset_angle * DEGREE_2_RAD); + sin_theta = arm_sin_f32(chassis_cmd_recv.offset_angle * DEGREE_2_RAD); + chassis_vx = chassis_cmd_recv.vx * cos_theta - chassis_cmd_recv.vy * sin_theta; + chassis_vy = chassis_cmd_recv.vx * sin_theta + chassis_cmd_recv.vy * cos_theta; + + // 根据控制模式进行正运动学解算,计算底盘输出 + SteeringWheelCalculate(); + // MecanumCalculate(); + + // 根据裁判系统的反馈数据和电容数据对输出限幅并设定闭环参考值 + LimitChassisOutput(); + + // 根据电机的反馈速度和IMU(如果有)计算真实速度 + EstimateSpeed(); + + // // 获取裁判系统数据 建议将裁判系统与底盘分离,所以此处数据应使用消息中心发送 + // // 我方颜色id小于7是红色,大于7是蓝色,注意这里发送的是对方的颜色, 0:blue , 1:red + // chassis_feedback_data.enemy_color = referee_data->GameRobotState.robot_id > 7 ? 1 : 0; + // // 当前只做了17mm热量的数据获取,后续根据robot_def中的宏切换双枪管和英雄42mm的情况 + // chassis_feedback_data.bullet_speed = referee_data->GameRobotState.shooter_id1_17mm_speed_limit; + // chassis_feedback_data.rest_heat = referee_data->PowerHeatData.shooter_heat0; + + // 推送反馈消息 +#ifdef ONE_BOARD + PubPushMessage(chassis_pub, (void *)&chassis_feedback_data); +#endif +#ifdef CHASSIS_BOARD + CANCommSend(chasiss_can_comm, (void *)&chassis_feedback_data); +#endif // CHASSIS_BOARD +} diff --git a/application/chassis/chassis.h b/application/chassis/chassis.h new file mode 100644 index 0000000..ea7c0b4 --- /dev/null +++ b/application/chassis/chassis.h @@ -0,0 +1,16 @@ +#ifndef CHASSIS_H +#define CHASSIS_H + +/** + * @brief 底盘应用初始化,请在开启rtos之前调用(目前会被RobotInit()调用) + * + */ +void ChassisInit(); + +/** + * @brief 底盘应用任务,放入实时系统以一定频率运行 + * + */ +void ChassisTask(); + +#endif // CHASSIS_H \ No newline at end of file diff --git a/application/chassis/chassis.md b/application/chassis/chassis.md new file mode 100644 index 0000000..6f04688 --- /dev/null +++ b/application/chassis/chassis.md @@ -0,0 +1,24 @@ +# chassis + + + +## 工作流程 + +首先进行初始化,`ChasissInit()`会被`RobotInit()`调用,进行裁判系统、底盘电机的初始化。如果为双板模式,则还会初始化IMU,并且将消息订阅者和发布者的初始化改为`CANComm`的初始化。 + +操作系统启动后,工作顺序为: + +1. 从cmd模块获取数据(如果双板则从CANComm获取) +2. 判断当前控制数据的模式,如果为停止则停止所有电机 +3. 根据控制数据,计算底盘的旋转速度 +4. 根据控制数据中yaw电机的编码器值`angle_offset`,将控制数据映射到底盘坐标系下 +5. 进行麦克纳姆轮的运动学解算,得到每个电机的设定值 +6. 获取裁判系统的数据,并根据底盘功率限制对输出进行限幅 +7. 由电机的反馈数据和IMU(如果有),计算底盘当前的真实运动速度 +8. 设置底盘反馈数据,包括运动速度和裁判系统数据 +9. 将反馈数据推送到消息中心(如果双板则通过CANComm发送) + + +### 后续支持平衡底盘 + +新增一个app balance_chassis \ No newline at end of file diff --git a/application/cmd/robot_cmd.c b/application/cmd/robot_cmd.c new file mode 100644 index 0000000..ac24c6f --- /dev/null +++ b/application/cmd/robot_cmd.c @@ -0,0 +1,351 @@ +// app +#include "robot_def.h" +#include "robot_cmd.h" +// module +#include "remote_control.h" +#include "ins_task.h" +#include "master_process.h" +#include "message_center.h" +#include "general_def.h" +#include "dji_motor.h" +// bsp +#include "bsp_dwt.h" +#include "bsp_log.h" +#include "main.h" +// 私有宏,自动将编码器转换成角度值 +#define YAW_ALIGN_ANGLE (YAW_CHASSIS_ALIGN_ECD * ECD_ANGLE_COEF_DJI) // 对齐时的角度,0-360 +#define PTICH_HORIZON_ANGLE (PITCH_HORIZON_ECD * ECD_ANGLE_COEF_DJI) // pitch水平时电机的角度,0-360 + +/* cmd应用包含的模块实例指针和交互信息存储*/ +#ifdef GIMBAL_BOARD // 对双板的兼容,条件编译 +#include "can_comm.h" +static CANCommInstance *cmd_can_comm; // 双板通信 +#endif +#ifdef ONE_BOARD +static Publisher_t *chassis_cmd_pub; // 底盘控制消息发布者 +static Subscriber_t *chassis_feed_sub; // 底盘反馈信息订阅者 +#endif // ONE_BOARD + +static Chassis_Ctrl_Cmd_s chassis_cmd_send; // 发送给底盘应用的信息,包括控制信息和UI绘制相关 +static Chassis_Upload_Data_s chassis_fetch_data; // 从底盘应用接收的反馈信息信息,底盘功率枪口热量与底盘运动状态等 + +static RC_ctrl_t *rc_data; // 遥控器数据,初始化时返回 +static Vision_Recv_s *vision_recv_data; // 视觉接收数据指针,初始化时返回 +static Vision_Send_s vision_send_data; // 视觉发送数据 + +static Publisher_t *gimbal_cmd_pub; // 云台控制消息发布者 +static Subscriber_t *gimbal_feed_sub; // 云台反馈信息订阅者 +static Gimbal_Ctrl_Cmd_s gimbal_cmd_send; // 传递给云台的控制信息 +static Gimbal_Upload_Data_s gimbal_fetch_data; // 从云台获取的反馈信息 + +static Publisher_t *shoot_cmd_pub; // 发射控制消息发布者 +static Subscriber_t *shoot_feed_sub; // 发射反馈信息订阅者 +static Shoot_Ctrl_Cmd_s shoot_cmd_send; // 传递给发射的控制信息 +static Shoot_Upload_Data_s shoot_fetch_data; // 从发射获取的反馈信息 + +static Robot_Status_e robot_state; // 机器人整体工作状态 + +void RobotCMDInit() +{ + rc_data = RemoteControlInit(&huart3); // 修改为对应串口,注意如果是自研板dbus协议串口需选用添加了反相器的那个 + vision_recv_data = VisionInit(&huart1); // 视觉通信串口 + + gimbal_cmd_pub = PubRegister("gimbal_cmd", sizeof(Gimbal_Ctrl_Cmd_s)); + gimbal_feed_sub = SubRegister("gimbal_feed", sizeof(Gimbal_Upload_Data_s)); + shoot_cmd_pub = PubRegister("shoot_cmd", sizeof(Shoot_Ctrl_Cmd_s)); + shoot_feed_sub = SubRegister("shoot_feed", sizeof(Shoot_Upload_Data_s)); + +#ifdef ONE_BOARD // 双板兼容 + chassis_cmd_pub = PubRegister("chassis_cmd", sizeof(Chassis_Ctrl_Cmd_s)); + chassis_feed_sub = SubRegister("chassis_feed", sizeof(Chassis_Upload_Data_s)); +#endif // ONE_BOARD +#ifdef GIMBAL_BOARD + CANComm_Init_Config_s comm_conf = { + .can_config = { + .can_handle = &hcan1, + .tx_id = 0x312, + .rx_id = 0x311, + }, + .recv_data_len = sizeof(Chassis_Upload_Data_s), + .send_data_len = sizeof(Chassis_Ctrl_Cmd_s), + }; + cmd_can_comm = CANCommInit(&comm_conf); +#endif // GIMBAL_BOARD + gimbal_cmd_send.pitch = 0; + + robot_state = ROBOT_READY; // 启动时机器人进入工作模式,后续加入所有应用初始化完成之后再进入 +} + +/** + * @brief 根据gimbal app传回的当前电机角度计算和零位的误差 + * 单圈绝对角度的范围是0~360,说明文档中有图示 + * + */ +static void CalcOffsetAngle() +{ + static float last_offset_angle = 0; + const float smooth_factor = 0.3f; // 平滑因子,0~1之间,值越大平滑效果越明显 + float new_offset = gimbal_fetch_data.yaw_motor_total_angle - YAW_ALIGN_ANGLE; +#if YAW_CHASSIS_REVERSE + new_offset = -new_offset; +#endif + float angle_diff = new_offset - last_offset_angle; + if (angle_diff > 180.0f) + new_offset -= 360.0f; + else if (angle_diff < -180.0f) + new_offset += 360.0f; + chassis_cmd_send .offset_angle = last_offset_angle *(1.0f - smooth_factor) + new_offset * smooth_factor; + last_offset_angle = chassis_cmd_send.offset_angle; + // static float angle; + // static float last_diff = 0.0f; // 用于在±180°附近保持上次符号,避免来回跳变 + // /* 使用 yaw 电机的单圈角度与 `YAW_ALIGN_ANGLE` 对齐(保持原实现的参考系) + // 并归一化到 (-180,180],加小死区防抖。 + // */ + // angle = gimbal_fetch_data.yaw_motor_single_round_angle; // 单圈绝对角度(0-360) + // float diff = angle - YAW_ALIGN_ANGLE; + // while (diff > 180.0f) + // diff -= 360.0f; + // while (diff <= -180.0f) + // diff += 360.0f; + // if (fabsf(diff) < 0.5f) + // diff = 0.0f; + // /* 处理在恰好为 180° 或接近 180° 时的二义性(噪声导致 180/-180 翻转) + // 如果差值接近 180°,则保持上一次的符号以避免抖动。可根据需要调整 eps180。 + // */ + // const float eps180 = 1.0f; + // if (fabsf(fabsf(diff) - 180.0f) < eps180) + // { + // diff = (last_diff >= 0.0f) ? 180.0f : -180.0f; + // } + // else + // { + // last_diff = diff; + // } + // chassis_cmd_send.offset_angle = diff; + //别名angle提高可读性,不然太长了不好看,虽然基本不会动这个函数 +// static float angle; +// angle = gimbal_fetch_data.yaw_motor_single_round_angle; // 从云台获取的当前yaw电机角度 +// #if YAW_ECD_GREATER_THAN_4096 // 如果大于180度 +// if (angle > YAW_ALIGN_ANGLE && angle <= 180.0f + YAW_ALIGN_ANGLE) +// chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE; +// else if (angle > 180.0f + YAW_ALIGN_ANGLE) +// chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE - 360.0f; +// else +// chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE; +// #else // 小于180度 +// if (angle > YAW_ALIGN_ANGLE) +// chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE; +// else if (angle <= YAW_ALIGN_ANGLE && angle >= YAW_ALIGN_ANGLE - 180.0f) +// chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE; +// else +// chassis_cmd_send.offset_angle = angle - YAW_ALIGN_ANGLE + 360.0f; +// #endif +} + +/** + * @brief 控制输入为遥控器(调试时)的模式和控制量设置 + * + */ +static void RemoteControlSet() +{ + // 控制底盘和云台运行模式,云台待添加,云台是否始终使用IMU数据? + if (switch_is_up(rc_data[TEMP].rc.switch_right)) // 右侧开关状态[下],底盘跟随云台 + { + chassis_cmd_send.chassis_mode = CHASSIS_ROTATE; + gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE; + } + else if (switch_is_mid(rc_data[TEMP].rc.switch_right)) // 右侧开关状态[中],底盘和云台分离,底盘保持不转动 + { + chassis_cmd_send.chassis_mode = CHASSIS_FOLLOW_GIMBAL_YAW; + gimbal_cmd_send.gimbal_mode = GIMBAL_GYRO_MODE; + } + + // 云台参数,确定云台控制数据 + if (switch_is_mid(rc_data[TEMP].rc.switch_left)) // 左侧开关状态为[中],视觉模式 + { + // 待添加,视觉会发来和目标的误差,同样将其转化为total angle的增量进行控制 + // ... + } + // 左侧开关状态为[下],或视觉未识别到目标,纯遥控器拨杆控制 + if (switch_is_down(rc_data[TEMP].rc.switch_left) || vision_recv_data->target_state == NO_TARGET) + { // 按照摇杆的输出大小进行角度增量,增益系数需调整 + gimbal_cmd_send.yaw += 0.005f * (float)rc_data[TEMP].rc.rocker_l_; + gimbal_cmd_send.pitch += 0.001f * (float)rc_data[TEMP].rc.rocker_l1; + } + // 云台软件限位 + + // 底盘参数,目前没有加入小陀螺(调试似乎暂时没有必要),系数需要调整 + chassis_cmd_send.vy = -0.15f * (float)rc_data[TEMP].rc.rocker_r_; // _水平方向 + chassis_cmd_send.vx = 0.15f * (float)rc_data[TEMP].rc.rocker_r1; // 1数值方向 + + // // 发射参数 + // if (switch_is_up(rc_data[TEMP].rc.switch_right)) // 右侧开关状态[上],弹舱打开 + // ; // 弹舱舵机控制,待添加servo_motor模块,开启 + // else + // ; // 弹舱舵机控制,待添加servo_motor模块,关闭 + + // 摩擦轮控制,拨轮向上打为负,向下为正 + if (rc_data[TEMP].rc.dial < -100) // 向上超过100,打开摩擦轮 + shoot_cmd_send.friction_mode = FRICTION_ON; + else + shoot_cmd_send.friction_mode = FRICTION_OFF; + // 拨弹控制,遥控器固定为一种拨弹模式,可自行选择 + if (rc_data[TEMP].rc.dial < -500) + shoot_cmd_send.load_mode = LOAD_BURSTFIRE; + else + shoot_cmd_send.load_mode = LOAD_STOP; + // 射频控制,固定每秒1发,后续可以根据左侧拨轮的值大小切换射频, + shoot_cmd_send.shoot_rate = 8; +} + +/** + * @brief 输入为键鼠时模式和控制量设置 + * + */ +static void MouseKeySet() +{ + chassis_cmd_send.vx = rc_data[TEMP].key[KEY_PRESS].w * 300 - rc_data[TEMP].key[KEY_PRESS].s * 300; // 系数待测 + chassis_cmd_send.vy = rc_data[TEMP].key[KEY_PRESS].s * 300 - rc_data[TEMP].key[KEY_PRESS].d * 300; + + gimbal_cmd_send.yaw += (float)rc_data[TEMP].mouse.x / 660 * 10; // 系数待测 + gimbal_cmd_send.pitch += (float)rc_data[TEMP].mouse.y / 660 * 10; + + switch (rc_data[TEMP].key_count[KEY_PRESS][Key_Z] % 3) // Z键设置弹速 + { + case 0: + shoot_cmd_send.bullet_speed = 15; + break; + case 1: + shoot_cmd_send.bullet_speed = 18; + break; + default: + shoot_cmd_send.bullet_speed = 30; + break; + } + switch (rc_data[TEMP].key_count[KEY_PRESS][Key_E] % 4) // E键设置发射模式 + { + case 0: + shoot_cmd_send.load_mode = LOAD_STOP; + break; + case 1: + shoot_cmd_send.load_mode = LOAD_1_BULLET; + break; + case 2: + shoot_cmd_send.load_mode = LOAD_3_BULLET; + break; + default: + shoot_cmd_send.load_mode = LOAD_BURSTFIRE; + break; + } + switch (rc_data[TEMP].key_count[KEY_PRESS][Key_R] % 2) // R键开关弹舱 + { + case 0: + shoot_cmd_send.lid_mode = LID_OPEN; + break; + default: + shoot_cmd_send.lid_mode = LID_CLOSE; + break; + } + switch (rc_data[TEMP].key_count[KEY_PRESS][Key_F] % 2) // F键开关摩擦轮 + { + case 0: + shoot_cmd_send.friction_mode = FRICTION_OFF; + break; + default: + shoot_cmd_send.friction_mode = FRICTION_ON; + break; + } + switch (rc_data[TEMP].key_count[KEY_PRESS][Key_C] % 4) // C键设置底盘速度 + { + case 0: + chassis_cmd_send.chassis_speed_buff = 40; + break; + case 1: + chassis_cmd_send.chassis_speed_buff = 60; + break; + case 2: + chassis_cmd_send.chassis_speed_buff = 80; + break; + default: + chassis_cmd_send.chassis_speed_buff = 100; + break; + } + switch (rc_data[TEMP].key[KEY_PRESS].shift) // 待添加 按shift允许超功率 消耗缓冲能量 + { + case 1: + + break; + + default: + + break; + } +} + +/** + * @brief 紧急停止,包括遥控器左上侧拨轮打满/重要模块离线/双板通信失效等 + * 停止的阈值'300'待修改成合适的值,或改为开关控制. + * + * @todo 后续修改为遥控器离线则电机停止(关闭遥控器急停),通过给遥控器模块添加daemon实现 + * + */ +static void EmergencyHandler() +{ + // 右摇杆最下急停 + if (switch_is_down(rc_data[TEMP].rc.switch_right) || robot_state == ROBOT_STOP) // 还需添加重要应用和模块离线的判断 + { + robot_state = ROBOT_STOP; + gimbal_cmd_send.gimbal_mode = GIMBAL_ZERO_FORCE; + chassis_cmd_send.chassis_mode = CHASSIS_ZERO_FORCE; + shoot_cmd_send.shoot_mode = SHOOT_OFF; + shoot_cmd_send.friction_mode = FRICTION_OFF; + shoot_cmd_send.load_mode = LOAD_STOP; + LOGERROR("[CMD] emergency stop!"); + } + // 遥控器右侧开关为[上],恢复正常运行 + if (switch_is_mid(rc_data[TEMP].rc.switch_right) || switch_is_up(rc_data[TEMP].rc.switch_right)) + { + robot_state = ROBOT_READY; + // shoot_cmd_send.shoot_mode = SHOOT_ON;//开摩擦轮? + LOGINFO("[CMD] reinstate, robot ready"); + } +} + +/* 机器人核心控制任务,200Hz频率运行(必须高于视觉发送频率) */ +void RobotCMDTask() +{ + // 从其他应用获取回传数据 +#ifdef ONE_BOARD + SubGetMessage(chassis_feed_sub, (void *)&chassis_fetch_data); +#endif // ONE_BOARD +#ifdef GIMBAL_BOARD + chassis_fetch_data = *(Chassis_Upload_Data_s *)CANCommGet(cmd_can_comm); +#endif // GIMBAL_BOARD + SubGetMessage(shoot_feed_sub, &shoot_fetch_data); + SubGetMessage(gimbal_feed_sub, &gimbal_fetch_data); + + // 根据gimbal的反馈值计算云台和底盘正方向的夹角,不需要传参,通过static私有变量完成 + CalcOffsetAngle(); + // 根据遥控器左侧开关,确定当前使用的控制模式为遥控器调试还是键鼠 + if (switch_is_down(rc_data[TEMP].rc.switch_left)) // 遥控器左侧开关状态为[下],遥控器控制 + RemoteControlSet(); + else if (switch_is_up(rc_data[TEMP].rc.switch_left)) // 遥控器左侧开关状态为[上],键盘控制 + MouseKeySet(); + + EmergencyHandler(); // 处理模块离线和遥控器急停等紧急情况 + + // 设置视觉发送数据,还需增加加速度和角速度数据 + // VisionSetFlag(chassis_fetch_data.enemy_color,,chassis_fetch_data.bullet_speed) + + // 推送消息,双板通信,视觉通信等 + // 其他应用所需的控制数据在remotecontrolsetmode和mousekeysetmode中完成设置 +#ifdef ONE_BOARD + PubPushMessage(chassis_cmd_pub, (void *)&chassis_cmd_send); +#endif // ONE_BOARD +#ifdef GIMBAL_BOARD + CANCommSend(cmd_can_comm, (void *)&chassis_cmd_send); +#endif // GIMBAL_BOARD + PubPushMessage(shoot_cmd_pub, (void *)&shoot_cmd_send); + PubPushMessage(gimbal_cmd_pub, (void *)&gimbal_cmd_send); + VisionSend(&vision_send_data); +} diff --git a/application/cmd/robot_cmd.h b/application/cmd/robot_cmd.h new file mode 100644 index 0000000..f42e9ce --- /dev/null +++ b/application/cmd/robot_cmd.h @@ -0,0 +1,17 @@ +#ifndef ROBOT_CMD_H +#define ROBOT_CMD_H + + +/** + * @brief 机器人核心控制任务初始化,会被RobotInit()调用 + * + */ +void RobotCMDInit(); + +/** + * @brief 机器人核心控制任务,200Hz频率运行(必须高于视觉发送频率) + * + */ +void RobotCMDTask(); + +#endif // !ROBOT_CMD_H \ No newline at end of file diff --git a/application/cmd/robot_cmd.md b/application/cmd/robot_cmd.md new file mode 100644 index 0000000..c8c9d16 --- /dev/null +++ b/application/cmd/robot_cmd.md @@ -0,0 +1,50 @@ +# robot_cmd + +neozng1@hnu.edu.cn
+ +## 运行流程 + +运行流程可以很直观的从`RobotCMDTask()`中看出。 + +1. 首先通过消息订阅机制,获取其他应用的反馈信息 +2. 使用`CalcOffsetAngle()`计算底盘和云台的offset angle(使得底盘始终获知当前的正方向) +3. 接着根据当前是通过键鼠or遥控器控制,调用对应的函数,将控制指令量化为具体的控制信息 +4. 得到控制信息之后,先不急着发布,而是检测重要的模块和应用是否掉线或出现异常,以及遥控器是否进入紧急停止模式,如果以上情况发生,那么将所有的控制信息都置零,即让电机和其他执行单元保持静止。 +5. 最后通过pubsub机制,把具体的控制信息发布到对应话题,让其他应用获取。若为双板,则将原本要推送给底盘的信息通过CANComm进行发送。 + + + +### 遥控器控制模式: + +拨轮向下打到底进入紧急停止模式(后续改为关闭遥控器停止,利用daemon);拨轮向上打开启摩擦轮,超过一半开始发射(速度环,连发) + +左侧开关: +- 上:键鼠控制 +- 中:视觉控制(没有识别到目标的时候仍然可以使用遥控器控制云台) +- 下:遥控器控制 + +右侧开关: +- 上:弹舱开 +- 中:底盘云台分离(底盘不旋转,全向移动) +- 下:底盘跟随云台 + +### 键鼠控制模式: + +遥控器左侧开关拨到最上方,进入键鼠控制模式,此时不会响应遥控器遥感和拨轮的输入. + +前后左右:WSAD + +开关弹舱盖:R + +小陀螺:Q + +发射:鼠标左键 + +自瞄:鼠标右键 + + + + + + + diff --git a/application/gimbal/gimbal.c b/application/gimbal/gimbal.c new file mode 100644 index 0000000..6dde34a --- /dev/null +++ b/application/gimbal/gimbal.c @@ -0,0 +1,158 @@ +#include "gimbal.h" +#include "robot_def.h" +#include "dji_motor.h" +#include "ins_task.h" +#include "message_center.h" +#include "general_def.h" + +#include "bmi088.h" + +static attitude_t *gimba_IMU_data; // 云台IMU数据 +static DJIMotorInstance *yaw_motor, *pitch_motor; + +static Publisher_t *gimbal_pub; // 云台应用消息发布者(云台反馈给cmd) +static Subscriber_t *gimbal_sub; // cmd控制消息订阅者 +static Gimbal_Upload_Data_s gimbal_feedback_data; // 回传给cmd的云台状态信息 +static Gimbal_Ctrl_Cmd_s gimbal_cmd_recv; // 来自cmd的控制信息 + +void GimbalInit() +{ + gimba_IMU_data = INS_Init(); // IMU先初始化,获取姿态数据指针赋给yaw电机的其他数据来源 + // YAW + Motor_Init_Config_s yaw_config = { + .can_init_config = { + .can_handle = &hcan1, + .tx_id = 5, + }, + .controller_param_init_config = { + .angle_PID = { + .Kp = 0.685, // 8 + .Ki = 0.315, + .Kd = 0.022, + //.DeadBand = 0.1, + .Improve = PID_Trapezoid_Intergral | PID_Integral_Limit | PID_Derivative_On_Measurement | PID_DerivativeFilter | PID_ChangingIntegrationRate, + .IntegralLimit = 1060, + .CoefA = 20, + .CoefB = 0.2, + .MaxOut = 4000, + .Derivative_LPF_RC = 0.001 + }, + .speed_PID = { + .Kp = 8000, // 50 + .Ki = 5000, // 200 + .Kd = 0, + .CoefB = 1, + .CoefA = 10, + .Improve = PID_Trapezoid_Intergral | PID_Integral_Limit | PID_Derivative_On_Measurement | PID_ChangingIntegrationRate, + .IntegralLimit = 7000, + .MaxOut = 25000, + }, + .other_angle_feedback_ptr = &gimba_IMU_data->YawTotalAngle, + // 还需要增加角速度额外反馈指针,注意方向,ins_task.md中有c板的bodyframe坐标系说明 + .other_speed_feedback_ptr = &gimba_IMU_data->Gyro[2], + }, + .controller_setting_init_config = { + .angle_feedback_source = OTHER_FEED, + .speed_feedback_source = OTHER_FEED, + .outer_loop_type = ANGLE_LOOP, + .close_loop_type = ANGLE_LOOP | SPEED_LOOP, + .motor_reverse_flag = MOTOR_DIRECTION_NORMAL, + }, + .motor_type = GM6020}; + // PITCH + Motor_Init_Config_s pitch_config = { + .can_init_config = { + .can_handle = &hcan2, + .tx_id = 4, + }, + .controller_param_init_config = { + .angle_PID = { + .Kp = 10, // 10 + .Ki = 0, + .Kd = 0, + .Improve = PID_Trapezoid_Intergral | PID_Integral_Limit | PID_Derivative_On_Measurement, + .IntegralLimit = 100, + .MaxOut = 500, + }, + .speed_PID = { + .Kp = 50, // 50 + .Ki = 350, // 350 + .Kd = 0, // 0 + .Improve = PID_Trapezoid_Intergral | PID_Integral_Limit | PID_Derivative_On_Measurement, + .IntegralLimit = 2500, + .MaxOut = 20000, + }, + .other_angle_feedback_ptr = &gimba_IMU_data->Pitch, + // 还需要增加角速度额外反馈指针,注意方向,ins_task.md中有c板的bodyframe坐标系说明 + .other_speed_feedback_ptr = (&gimba_IMU_data->Gyro[0]), + }, + .controller_setting_init_config = { + .angle_feedback_source = OTHER_FEED, + .speed_feedback_source = OTHER_FEED, + .outer_loop_type = ANGLE_LOOP, + .close_loop_type = SPEED_LOOP | ANGLE_LOOP, + .motor_reverse_flag = MOTOR_DIRECTION_NORMAL, + }, + .motor_type = GM6020, + }; + // 电机对total_angle闭环,上电时为零,会保持静止,收到遥控器数据再动 + yaw_motor = DJIMotorInit(&yaw_config); + pitch_motor = DJIMotorInit(&pitch_config); + + gimbal_pub = PubRegister("gimbal_feed", sizeof(Gimbal_Upload_Data_s)); + gimbal_sub = SubRegister("gimbal_cmd", sizeof(Gimbal_Ctrl_Cmd_s)); +} + +/* 机器人云台控制核心任务,后续考虑只保留IMU控制,不再需要电机的反馈 */ +void GimbalTask() +{ + // 获取云台控制数据 + // 后续增加未收到数据的处理 + SubGetMessage(gimbal_sub, &gimbal_cmd_recv); + + // @todo:现在已不再需要电机反馈,实际上可以始终使用IMU的姿态数据来作为云台的反馈,yaw电机的offset只是用来跟随底盘 + // 根据控制模式进行电机反馈切换和过渡,视觉模式在robot_cmd模块就已经设置好,gimbal只看yaw_ref和pitch_ref + switch (gimbal_cmd_recv.gimbal_mode) + { + // 停止 + case GIMBAL_ZERO_FORCE: + DJIMotorStop(yaw_motor); + DJIMotorStop(pitch_motor); + break; + // 使用陀螺仪的反馈,底盘根据yaw电机的offset跟随云台或视觉模式采用 + case GIMBAL_GYRO_MODE: // 后续只保留此模式 + DJIMotorEnable(yaw_motor); + DJIMotorEnable(pitch_motor); + DJIMotorChangeFeed(yaw_motor, ANGLE_LOOP, OTHER_FEED); + DJIMotorChangeFeed(yaw_motor, SPEED_LOOP, OTHER_FEED); + DJIMotorChangeFeed(pitch_motor, ANGLE_LOOP, OTHER_FEED); + DJIMotorChangeFeed(pitch_motor, SPEED_LOOP, OTHER_FEED); + DJIMotorSetRef(yaw_motor, gimbal_cmd_recv.yaw); // yaw和pitch会在robot_cmd中处理好多圈和单圈 + DJIMotorSetRef(pitch_motor, gimbal_cmd_recv.pitch); + break; + // 云台自由模式,使用编码器反馈,底盘和云台分离,仅云台旋转,一般用于调整云台姿态(英雄吊射等)/能量机关 + case GIMBAL_FREE_MODE: // 后续删除,或加入云台追地盘的跟随模式(响应速度更快) + DJIMotorEnable(yaw_motor); + DJIMotorEnable(pitch_motor); + DJIMotorChangeFeed(yaw_motor, ANGLE_LOOP, OTHER_FEED); + DJIMotorChangeFeed(yaw_motor, SPEED_LOOP, OTHER_FEED); + DJIMotorChangeFeed(pitch_motor, ANGLE_LOOP, OTHER_FEED); + DJIMotorChangeFeed(pitch_motor, SPEED_LOOP, OTHER_FEED); + DJIMotorSetRef(yaw_motor, gimbal_cmd_recv.yaw); // yaw和pitch会在robot_cmd中处理好多圈和单圈 + DJIMotorSetRef(pitch_motor, gimbal_cmd_recv.pitch); + break; + default: + break; + } + + // 在合适的地方添加pitch重力补偿前馈力矩 + // 根据IMU姿态/pitch电机角度反馈计算出当前配重下的重力矩 + // ... + + // 设置反馈数据,主要是imu和yaw的ecd + gimbal_feedback_data.gimbal_imu_data = *gimba_IMU_data; + // gimbal_feedback_data.yaw_motor_single_round_angle = yaw_motor->measure.angle_single_round; + gimbal_feedback_data.yaw_motor_single_round_angle = yaw_motor->measure.total_angle; + // 推送消息 + PubPushMessage(gimbal_pub, (void *)&gimbal_feedback_data); +} \ No newline at end of file diff --git a/application/gimbal/gimbal.h b/application/gimbal/gimbal.h new file mode 100644 index 0000000..0bcc37e --- /dev/null +++ b/application/gimbal/gimbal.h @@ -0,0 +1,16 @@ +#ifndef GIMBAL_H +#define GIMBAL_H + +/** + * @brief 初始化云台,会被RobotInit()调用 + * + */ +void GimbalInit(); + +/** + * @brief 云台任务 + * + */ +void GimbalTask(); + +#endif // GIMBAL_H \ No newline at end of file diff --git a/application/gimbal/gimbal.md b/application/gimbal/gimbal.md new file mode 100644 index 0000000..d83ca3c --- /dev/null +++ b/application/gimbal/gimbal.md @@ -0,0 +1,13 @@ +# gimbal + + + +## 工作流程 + +初始化pitch和yaw电机以及一个imu。订阅gimbal_cmd消息(来自robot_cmd)并发布gimbal_feed话题。 + +1. 从消息中心获取gimbal_cmd话题的消息 +2. 根据消息中的控制模式进行模式切换,如果急停则关闭所有电机 +3. 由设定的模式,进行电机反馈数据来源的切换,修改反馈数据指针,设置前馈控制数据指针等。 +4. 设置反馈数据,包括yaw电机的绝对角度和imu数据 +5. 推送反馈数据到gimbal_feed话题下 \ No newline at end of file diff --git a/application/robot.c b/application/robot.c new file mode 100644 index 0000000..3102179 --- /dev/null +++ b/application/robot.c @@ -0,0 +1,60 @@ +#include "bsp_init.h" +#include "robot.h" +#include "robot_def.h" +#include "robot_task.h" + +// 编译warning,提醒开发者修改机器人参数 +#ifndef ROBOT_DEF_PARAM_WARNING +#define ROBOT_DEF_PARAM_WARNING +#pragma message "check if you have configured the parameters in robot_def.h, IF NOT, please refer to the comments AND DO IT, otherwise the robot will have FATAL ERRORS!!!" +#endif // !ROBOT_DEF_PARAM_WARNING + +#if defined(ONE_BOARD) || defined(CHASSIS_BOARD) +#include "chassis.h" +#endif + +#if defined(ONE_BOARD) || defined(GIMBAL_BOARD) +#include "gimbal.h" +#include "shoot.h" +#include "robot_cmd.h" +#endif + + +void RobotInit() +{ + // 关闭中断,防止在初始化过程中发生中断 + // 请不要在初始化过程中使用中断和延时函数! + // 若必须,则只允许使用DWT_Delay() + __disable_irq(); + + BSPInit(); + +#if defined(ONE_BOARD) || defined(GIMBAL_BOARD) + RobotCMDInit(); + GimbalInit(); + ShootInit(); +#endif + +#if defined(ONE_BOARD) || defined(CHASSIS_BOARD) + ChassisInit(); +#endif + + OSTaskInit(); // 创建基础任务 + + // 初始化完成,开启中断 + __enable_irq(); +} + +void RobotTask() +{ +#if defined(ONE_BOARD) || defined(GIMBAL_BOARD) + RobotCMDTask(); + GimbalTask(); + ShootTask(); +#endif + +#if defined(ONE_BOARD) || defined(CHASSIS_BOARD) + ChassisTask(); +#endif + +} \ No newline at end of file diff --git a/application/robot.h b/application/robot.h new file mode 100644 index 0000000..36f9809 --- /dev/null +++ b/application/robot.h @@ -0,0 +1,18 @@ +#ifndef ROBOT_H +#define ROBOT_H + +/* Robot利用robot_def.h中的宏对不同的机器人进行了大量的兼容,同时兼容了两个开发板(云台板和底盘板)的配置 */ + +/** + * @brief 机器人初始化,请在开启rtos之前调用.这也是唯一需要放入main函数的函数 + * + */ +void RobotInit(); + +/** + * @brief 机器人任务,放入实时系统以一定频率运行,内部会调用各个应用的任务 + * + */ +void RobotTask(); + +#endif \ No newline at end of file diff --git a/application/robot_def.h b/application/robot_def.h new file mode 100644 index 0000000..ef05828 --- /dev/null +++ b/application/robot_def.h @@ -0,0 +1,221 @@ +/** + * @file robot_def.h + * @author NeoZeng neozng1@hnu.edu.cn + * @author Even + * @version 0.1 + * @date 2022-12-02 + * + * @copyright Copyright (c) HNU YueLu EC 2022 all rights reserved + * + */ +#pragma once // 可以用#pragma once代替#ifndef ROBOT_DEF_H(header guard) +#ifndef ROBOT_DEF_H +#define ROBOT_DEF_H + +#include "ins_task.h" +#include "master_process.h" +#include "stdint.h" + +/* 开发板类型定义,烧录时注意不要弄错对应功能;修改定义后需要重新编译,只能存在一个定义! */ +#define ONE_BOARD // 单板控制整车 +// #define CHASSIS_BOARD //底盘板 +// #define GIMBAL_BOARD //云台板 + +#define VISION_USE_VCP // 使用虚拟串口发送视觉数据 +// #define VISION_USE_UART // 使用串口发送视觉数据 + +/* 机器人重要参数定义,注意根据不同机器人进行修改,浮点数需要以.0或f结尾,无符号以u结尾 */ +// 云台参数 +#define YAW_CHASSIS_ALIGN_ECD 8015 // 云台和底盘对齐指向相同方向时的电机编码器值,若对云台有机械改动需要修改 +#define YAW_ECD_GREATER_THAN_4096 0 // ALIGN_ECD值是否大于4096,是为1,否为0;用于计算云台偏转角度 +#define PITCH_HORIZON_ECD 3412 // 云台处于水平位置时编码器值,若对云台有机械改动需要修改 +#define PITCH_MAX_ANGLE 0 // 云台竖直方向最大角度 (注意反馈如果是陀螺仪,则填写陀螺仪的角度) +#define PITCH_MIN_ANGLE 0 // 云台竖直方向最小角度 (注意反馈如果是陀螺仪,则填写陀螺仪的角度) +// 底盘参数 +// #define CHASSIS_OMNI_WHEEL // 是否为全向轮底盘 +// #define CHASSIS_MCNAMEE_WHEEL // 是否为麦克纳姆轮底盘 +#define CHASSIS_STEERING_WHEEL // 是否为舵轮 +#define STEERING_CHASSIS_ALIGN_ECD_LF 1221 // 舵电机 A 编码器值,若有机械改动需要修改 +#define STEERING_CHASSIS_ALIGN_ECD_RB 7294 // 舵电机 D 编码器值,若有机械改动需要修改 + +#define STEERING_CHASSIS_ALIGN_ANGLE_LF STEERING_CHASSIS_ALIGN_ECD_LF / 8192.f * 360.f // 舵轮 A 对齐角度 +#define STEERING_CHASSIS_ALIGN_ANGLE_RB STEERING_CHASSIS_ALIGN_ECD_RB / 8192.f * 360.f // 舵轮 D 对齐角度 +// 发射参数 +#define ONE_BULLET_DELTA_ANGLE 36 // 发射一发弹丸拨盘转动的距离,由机械设计图纸给出 +#define REDUCTION_RATIO_LOADER 49.0f // 拨盘电机的减速比,英雄需要修改为3508的19.0f +#define NUM_PER_CIRCLE 10 // 拨盘一圈的装载量 +// 机器人底盘修改的参数,单位为mm(毫米) +#define WHEEL_BASE 350 // 纵向轴距(前进后退方向) +#define TRACK_WIDTH 300 // 横向轮距(左右平移方向) +#define CENTER_GIMBAL_OFFSET_X 0 // 云台旋转中心距底盘几何中心的距离,前后方向,云台位于正中心时默认设为0 +#define CENTER_GIMBAL_OFFSET_Y 0 // 云台旋转中心距底盘几何中心的距离,左右方向,云台位于正中心时默认设为0 +#define RADIUS_WHEEL 60 // 轮子半径 +#define REDUCTION_RATIO_WHEEL 19.0f // 电机减速比,因为编码器量测的是转子的速度而不是输出轴的速度故需进行转换 + +#define GYRO2GIMBAL_DIR_YAW 1 // 陀螺仪数据相较于云台的yaw的方向,1为相同,-1为相反 +#define GYRO2GIMBAL_DIR_PITCH 1 // 陀螺仪数据相较于云台的pitch的方向,1为相同,-1为相反 +#define GYRO2GIMBAL_DIR_ROLL 1 // 陀螺仪数据相较于云台的roll的方向,1为相同,-1为相反 + +// 检查是否出现主控板定义冲突,只允许一个开发板定义存在,否则编译会自动报错 +#if (defined(ONE_BOARD) && defined(CHASSIS_BOARD)) || \ + (defined(ONE_BOARD) && defined(GIMBAL_BOARD)) || \ + (defined(CHASSIS_BOARD) && defined(GIMBAL_BOARD)) +#error Conflict board definition! You can only define one board type. +#endif + +#pragma pack(1) // 压缩结构体,取消字节对齐,下面的数据都可能被传输 +/* -------------------------基本控制模式和数据类型定义-------------------------*/ +/** + * @brief 这些枚举类型和结构体会作为CMD控制数据和各应用的反馈数据的一部分 + * + */ +// 机器人状态 +typedef enum +{ + ROBOT_STOP = 0, + ROBOT_READY, +} Robot_Status_e; + +// 应用状态 +typedef enum +{ + APP_OFFLINE = 0, + APP_ONLINE, + APP_ERROR, +} App_Status_e; + +// 底盘模式设置 +/** + * @brief 后续考虑修改为云台跟随底盘,而不是让底盘去追云台,云台的惯量比底盘小. + * + */ +typedef enum +{ + CHASSIS_ZERO_FORCE = 0, // 电流零输入 + CHASSIS_ROTATE, // 小陀螺模式 + CHASSIS_NO_FOLLOW, // 不跟随,允许全向平移 + CHASSIS_FOLLOW_GIMBAL_YAW, // 跟随模式,底盘叠加角度环控制 +} chassis_mode_e; + +// 云台模式设置 +typedef enum +{ + GIMBAL_ZERO_FORCE = 0, // 电流零输入 + GIMBAL_FREE_MODE, // 云台自由运动模式,即与底盘分离(底盘此时应为NO_FOLLOW)反馈值为电机total_angle;似乎可以改为全部用IMU数据? + GIMBAL_GYRO_MODE, // 云台陀螺仪反馈模式,反馈值为陀螺仪pitch,total_yaw_angle,底盘可以为小陀螺和跟随模式 +} gimbal_mode_e; + +// 发射模式设置 +typedef enum +{ + SHOOT_OFF = 0, + SHOOT_ON, +} shoot_mode_e; +typedef enum +{ + FRICTION_OFF = 0, // 摩擦轮关闭 + FRICTION_ON, // 摩擦轮开启 +} friction_mode_e; + +typedef enum +{ + LID_OPEN = 0, // 弹舱盖打开 + LID_CLOSE, // 弹舱盖关闭 +} lid_mode_e; + +typedef enum +{ + LOAD_STOP = 0, // 停止发射 + LOAD_REVERSE, // 反转 + LOAD_1_BULLET, // 单发 + LOAD_3_BULLET, // 三发 + LOAD_BURSTFIRE, // 连发 +} loader_mode_e; + +// 功率限制,从裁判系统获取,是否有必要保留? +typedef struct +{ // 功率控制 + float chassis_power_mx; +} Chassis_Power_Data_s; + +/* ----------------CMD应用发布的控制数据,应当由gimbal/chassis/shoot订阅---------------- */ +/** + * @brief 对于双板情况,遥控器和pc在云台,裁判系统在底盘 + * + */ +// cmd发布的底盘控制数据,由chassis订阅 +typedef struct +{ + // 控制部分 + float vx; // 前进方向速度 + float vy; // 横移方向速度 + float wz; // 旋转速度 + float offset_angle; // 底盘和归中位置的夹角 + chassis_mode_e chassis_mode; + int chassis_speed_buff; + // UI部分 + // ... + +} Chassis_Ctrl_Cmd_s; + +// cmd发布的云台控制数据,由gimbal订阅 +typedef struct +{ // 云台角度控制 + float yaw; + float pitch; + float chassis_rotate_wz; + + gimbal_mode_e gimbal_mode; +} Gimbal_Ctrl_Cmd_s; + +// cmd发布的发射控制数据,由shoot订阅 +typedef struct +{ + shoot_mode_e shoot_mode; + loader_mode_e load_mode; + lid_mode_e lid_mode; + friction_mode_e friction_mode; + Bullet_Speed_e bullet_speed; // 弹速枚举 + uint8_t rest_heat; + float shoot_rate; // 连续发射的射频,unit per s,发/秒 +} Shoot_Ctrl_Cmd_s; + +/* ----------------gimbal/shoot/chassis发布的反馈数据----------------*/ +/** + * @brief 由cmd订阅,其他应用也可以根据需要获取. + * + */ + +typedef struct +{ +#if defined(CHASSIS_BOARD) || defined(GIMBAL_BOARD) // 非单板的时候底盘还将imu数据回传(若有必要) + // attitude_t chassis_imu_data; +#endif + // 后续增加底盘的真实速度 + // float real_vx; + // float real_vy; + // float real_wz; + + uint8_t rest_heat; // 剩余枪口热量 + Bullet_Speed_e bullet_speed; // 弹速限制 + Enemy_Color_e enemy_color; // 0 for blue, 1 for red + +} Chassis_Upload_Data_s; + + +typedef struct +{ + attitude_t gimbal_imu_data; + uint16_t yaw_motor_single_round_angle; + float yaw_motor_total_angle; +} Gimbal_Upload_Data_s; + +typedef struct +{ + // code to go here + // ... +} Shoot_Upload_Data_s; + +#pragma pack() // 开启字节对齐,结束前面的#pragma pack(1) + +#endif // !ROBOT_DEF_H \ No newline at end of file diff --git a/application/robot_task.h b/application/robot_task.h new file mode 100644 index 0000000..a65d83e --- /dev/null +++ b/application/robot_task.h @@ -0,0 +1,139 @@ +/* 注意该文件应只用于任务初始化,只能被robot.c包含*/ +#pragma once + +#include "FreeRTOS.h" +#include "task.h" +#include "main.h" +#include "cmsis_os.h" + +#include "robot.h" +#include "ins_task.h" +#include "motor_task.h" +#include "referee_task.h" +#include "master_process.h" +#include "daemon.h" +#include "HT04.h" +#include "buzzer.h" + +#include "bsp_log.h" + +osThreadId insTaskHandle; +osThreadId robotTaskHandle; +osThreadId motorTaskHandle; +osThreadId daemonTaskHandle; +osThreadId uiTaskHandle; + +void StartINSTASK(void const *argument); +void StartMOTORTASK(void const *argument); +void StartDAEMONTASK(void const *argument); +void StartROBOTTASK(void const *argument); +void StartUITASK(void const *argument); + +/** + * @brief 初始化机器人任务,所有持续运行的任务都在这里初始化 + * + */ +void OSTaskInit() +{ + osThreadDef(instask, StartINSTASK, osPriorityAboveNormal, 0, 1024); + insTaskHandle = osThreadCreate(osThread(instask), NULL); // 由于是阻塞读取传感器,为姿态解算设置较高优先级,确保以1khz的频率执行 + // 后续修改为读取传感器数据准备好的中断处理, + + osThreadDef(motortask, StartMOTORTASK, osPriorityNormal, 0, 256); + motorTaskHandle = osThreadCreate(osThread(motortask), NULL); + + osThreadDef(daemontask, StartDAEMONTASK, osPriorityNormal, 0, 128); + daemonTaskHandle = osThreadCreate(osThread(daemontask), NULL); + + osThreadDef(robottask, StartROBOTTASK, osPriorityNormal, 0, 1024); + robotTaskHandle = osThreadCreate(osThread(robottask), NULL); + + osThreadDef(uitask, StartUITASK, osPriorityNormal, 0, 512); + uiTaskHandle = osThreadCreate(osThread(uitask), NULL); + + HTMotorControlInit(); // 没有注册HT电机则不会执行 +} + +__attribute__((noreturn)) void StartINSTASK(void const *argument) +{ + static float ins_start; + static float ins_dt; + INS_Init(); // 确保BMI088被正确初始化. + LOGINFO("[freeRTOS] INS Task Start"); + for (;;) + { + // 1kHz + ins_start = DWT_GetTimeline_ms(); + INS_Task(); + ins_dt = DWT_GetTimeline_ms() - ins_start; + if (ins_dt > 1) + LOGERROR("[freeRTOS] INS Task is being DELAY! dt = [%f]", &ins_dt); + VisionSend(); // 解算完成后发送视觉数据,但是当前的实现不太优雅,后续若添加硬件触发需要重新考虑结构的组织 + osDelay(1); + } +} + +__attribute__((noreturn)) void StartMOTORTASK(void const *argument)//500hz +{ + static float motor_dt; + static float motor_start; + LOGINFO("[freeRTOS] MOTOR Task Start"); + for (;;) + { + motor_start = DWT_GetTimeline_ms(); + MotorControlTask(); + motor_dt = DWT_GetTimeline_ms() - motor_start; + if (motor_dt > 2) + LOGERROR("[freeRTOS] MOTOR Task is being DELAY! dt = [%f]", &motor_dt); + osDelay(2); + } +} + +__attribute__((noreturn)) void StartDAEMONTASK(void const *argument) +{ + static float daemon_dt; + static float daemon_start; + BuzzerInit(); + LOGINFO("[freeRTOS] Daemon Task Start"); + for (;;) + { + // 100Hz + daemon_start = DWT_GetTimeline_ms(); + DaemonTask(); + BuzzerTask(); + daemon_dt = DWT_GetTimeline_ms() - daemon_start; + if (daemon_dt > 10) + LOGERROR("[freeRTOS] Daemon Task is being DELAY! dt = [%f]", &daemon_dt); + osDelay(10); + } +} + +__attribute__((noreturn)) void StartROBOTTASK(void const *argument) +{ + static float robot_dt; + static float robot_start; + LOGINFO("[freeRTOS] ROBOT core Task Start"); + // 200Hz-500Hz,若有额外的控制任务如平衡步兵可能需要提升至1kHz + for (;;) + { + robot_start = DWT_GetTimeline_ms(); + RobotTask(); + robot_dt = DWT_GetTimeline_ms() - robot_start; + if (robot_dt > 5) + LOGERROR("[freeRTOS] ROBOT core Task is being DELAY! dt = [%f]", &robot_dt); + osDelay(5); + } +} + +__attribute__((noreturn)) void StartUITASK(void const *argument) +{ + LOGINFO("[freeRTOS] UI Task Start"); + MyUIInit(); + LOGINFO("[freeRTOS] UI Init Done, communication with ref has established"); + for (;;) + { + // 每给裁判系统发送一包数据会挂起一次,详见UITask函数的refereeSend() + UITask(); + osDelay(2); // 即使没有任何UI需要刷新,也挂起一次,防止卡在UITask中无法切换 + } +} diff --git a/application/shoot/shoot.c b/application/shoot/shoot.c new file mode 100644 index 0000000..514ea36 --- /dev/null +++ b/application/shoot/shoot.c @@ -0,0 +1,213 @@ +#include "shoot.h" +#include "robot_def.h" + +#include "dji_motor.h" +#include "message_center.h" +#include "bsp_dwt.h" +#include "general_def.h" + +/* 对于双发射机构的机器人,将下面的数据封装成结构体即可,生成两份shoot应用实例 */ +static DJIMotorInstance *friction_l, *friction_r, *loader; // 拨盘电机 +// static servo_instance *lid; 需要增加弹舱盖 + +static Publisher_t *shoot_pub; +static Shoot_Ctrl_Cmd_s shoot_cmd_recv; // 来自cmd的发射控制信息 +static Subscriber_t *shoot_sub; +static Shoot_Upload_Data_s shoot_feedback_data; // 来自cmd的发射控制信息 + +// dwt定时,计算冷却用 +static float hibernate_time = 0, dead_time = 0; + +void ShootInit() +{ + // 左摩擦轮 + Motor_Init_Config_s friction_config = { + .can_init_config = { + .can_handle = &hcan2, + }, + .controller_param_init_config = { + .speed_PID = { + .Kp = 0, // 20 + .Ki = 0, // 1 + .Kd = 0, + .Improve = PID_Integral_Limit, + .IntegralLimit = 10000, + .MaxOut = 15000, + }, + .current_PID = { + .Kp = 0, // 0.7 + .Ki = 0, // 0.1 + .Kd = 0, + .Improve = PID_Integral_Limit, + .IntegralLimit = 10000, + .MaxOut = 15000, + }, + }, + .controller_setting_init_config = { + .angle_feedback_source = MOTOR_FEED, + .speed_feedback_source = MOTOR_FEED, + + .outer_loop_type = SPEED_LOOP, + .close_loop_type = SPEED_LOOP | CURRENT_LOOP, + .motor_reverse_flag = MOTOR_DIRECTION_NORMAL, + }, + .motor_type = M3508}; + friction_config.can_init_config.tx_id = 1, + friction_l = DJIMotorInit(&friction_config); + + friction_config.can_init_config.tx_id = 2; // 右摩擦轮,改txid和方向就行 + friction_config.controller_setting_init_config.motor_reverse_flag = MOTOR_DIRECTION_REVERSE; + friction_r = DJIMotorInit(&friction_config); + + // 拨盘电机 + Motor_Init_Config_s loader_config = { + .can_init_config = { + .can_handle = &hcan2, + .tx_id = 5, + }, + .controller_param_init_config = { + .angle_PID = { + // 如果启用位置环来控制发弹,需要较大的I值保证输出力矩的线性度否则出现接近拨出的力矩大幅下降 + .Kp = 0, // 10 + .Ki = 0, + .Kd = 0, + .MaxOut = 200, + }, + .speed_PID = { + .Kp = 0, // 10 + .Ki = 0, // 1 + .Kd = 0, + .Improve = PID_Integral_Limit, + .IntegralLimit = 5000, + .MaxOut = 5000, + }, + .current_PID = { + .Kp = 0, // 0.7 + .Ki = 0, // 0.1 + .Kd = 0, + .Improve = PID_Integral_Limit, + .IntegralLimit = 5000, + .MaxOut = 5000, + }, + }, + .controller_setting_init_config = { + .angle_feedback_source = MOTOR_FEED, .speed_feedback_source = MOTOR_FEED, + .outer_loop_type = SPEED_LOOP, // 初始化成SPEED_LOOP,让拨盘停在原地,防止拨盘上电时乱转 + .close_loop_type = CURRENT_LOOP | SPEED_LOOP, + .motor_reverse_flag = MOTOR_DIRECTION_NORMAL, // 注意方向设置为拨盘的拨出的击发方向 + }, + .motor_type = M2006 // 英雄使用m3508 + }; + loader = DJIMotorInit(&loader_config); + + shoot_pub = PubRegister("shoot_feed", sizeof(Shoot_Upload_Data_s)); + shoot_sub = SubRegister("shoot_cmd", sizeof(Shoot_Ctrl_Cmd_s)); +} + +/* 机器人发射机构控制核心任务 */ +void ShootTask() +{ + // 从cmd获取控制数据 + SubGetMessage(shoot_sub, &shoot_cmd_recv); + + // 对shoot mode等于SHOOT_STOP的情况特殊处理,直接停止所有电机(紧急停止) + if (shoot_cmd_recv.shoot_mode == SHOOT_OFF) + { + DJIMotorStop(friction_l); + DJIMotorStop(friction_r); + DJIMotorStop(loader); + } + else // 恢复运行 + { + DJIMotorEnable(friction_l); + DJIMotorEnable(friction_r); + DJIMotorEnable(loader); + } + + // 如果上一次触发单发或3发指令的时间加上不应期仍然大于当前时间(尚未休眠完毕),直接返回即可 + // 单发模式主要提供给能量机关激活使用(以及英雄的射击大部分处于单发) + // if (hibernate_time + dead_time > DWT_GetTimeline_ms()) + // return; + + // 若不在休眠状态,根据robotCMD传来的控制模式进行拨盘电机参考值设定和模式切换 + switch (shoot_cmd_recv.load_mode) + { + // 停止拨盘 + case LOAD_STOP: + DJIMotorOuterLoop(loader, SPEED_LOOP); // 切换到速度环 + DJIMotorSetRef(loader, 0); // 同时设定参考值为0,这样停止的速度最快 + break; + // 单发模式,根据鼠标按下的时间,触发一次之后需要进入不响应输入的状态(否则按下的时间内可能多次进入,导致多次发射) + case LOAD_1_BULLET: // 激活能量机关/干扰对方用,英雄用. + DJIMotorOuterLoop(loader, ANGLE_LOOP); // 切换到角度环 + DJIMotorSetRef(loader, loader->measure.total_angle + ONE_BULLET_DELTA_ANGLE); // 控制量增加一发弹丸的角度 + hibernate_time = DWT_GetTimeline_ms(); // 记录触发指令的时间 + dead_time = 150; // 完成1发弹丸发射的时间 + break; + // 三连发,如果不需要后续可能删除 + case LOAD_3_BULLET: + DJIMotorOuterLoop(loader, ANGLE_LOOP); // 切换到速度环 + DJIMotorSetRef(loader, loader->measure.total_angle + 3 * ONE_BULLET_DELTA_ANGLE); // 增加3发 + hibernate_time = DWT_GetTimeline_ms(); // 记录触发指令的时间 + dead_time = 300; // 完成3发弹丸发射的时间 + break; + // 连发模式,对速度闭环,射频后续修改为可变,目前固定为1Hz + case LOAD_BURSTFIRE: + DJIMotorOuterLoop(loader, SPEED_LOOP); + DJIMotorSetRef(loader, shoot_cmd_recv.shoot_rate * 360 * REDUCTION_RATIO_LOADER / 8); + // x颗/秒换算成速度: 已知一圈的载弹量,由此计算出1s需要转的角度,注意换算角速度(DJIMotor的速度单位是angle per second) + break; + // 拨盘反转,对速度闭环,后续增加卡弹检测(通过裁判系统剩余热量反馈和电机电流) + // 也有可能需要从switch-case中独立出来 + case LOAD_REVERSE: + DJIMotorOuterLoop(loader, SPEED_LOOP); + // ... + break; + default: + while (1) + ; // 未知模式,停止运行,检查指针越界,内存溢出等问题 + } + + // 确定是否开启摩擦轮,后续可能修改为键鼠模式下始终开启摩擦轮(上场时建议一直开启) + if (shoot_cmd_recv.friction_mode == FRICTION_ON) + { + // 根据收到的弹速设置设定摩擦轮电机参考值,需实测后填入 + switch (shoot_cmd_recv.bullet_speed) + { + case SMALL_AMU_15: + DJIMotorSetRef(friction_l, 0); + DJIMotorSetRef(friction_r, 0); + break; + case SMALL_AMU_18: + DJIMotorSetRef(friction_l, 0); + DJIMotorSetRef(friction_r, 0); + break; + case SMALL_AMU_30: + DJIMotorSetRef(friction_l, 0); + DJIMotorSetRef(friction_r, 0); + break; + default: // 当前为了调试设定的默认值4000,因为还没有加入裁判系统无法读取弹速. + DJIMotorSetRef(friction_l, 30000); + DJIMotorSetRef(friction_r, 30000); + break; + } + } + else // 关闭摩擦轮 + { + DJIMotorSetRef(friction_l, 0); + DJIMotorSetRef(friction_r, 0); + } + + // 开关弹舱盖 + if (shoot_cmd_recv.lid_mode == LID_CLOSE) + { + //... + } + else if (shoot_cmd_recv.lid_mode == LID_OPEN) + { + //... + } + + // 反馈数据,目前暂时没有要设定的反馈数据,后续可能增加应用离线监测以及卡弹反馈 + PubPushMessage(shoot_pub, (void *)&shoot_feedback_data); +} \ No newline at end of file diff --git a/application/shoot/shoot.h b/application/shoot/shoot.h new file mode 100644 index 0000000..45701c3 --- /dev/null +++ b/application/shoot/shoot.h @@ -0,0 +1,16 @@ +#ifndef SHOOT_H +#define SHOOT_H + +/** + * @brief 发射初始化,会被RobotInit()调用 + * + */ +void ShootInit(); + +/** + * @brief 发射任务 + * + */ +void ShootTask(); + +#endif // SHOOT_H \ No newline at end of file diff --git a/application/shoot/shoot.md b/application/shoot/shoot.md new file mode 100644 index 0000000..8608033 --- /dev/null +++ b/application/shoot/shoot.md @@ -0,0 +1,15 @@ +# shoot + + + +## 工作流程 + +初始化3个电机和一个舵机,包括发射的2个m3508,拨盘的m2006和弹仓盖上的舵机(双开门舵机可能要换成2个)。m2006初始化时设置为速度闭环,防止上电乱转。订阅shoot_cmd话题(robot_cmd发布的)并发布shoot_feed话题(robot_cmd会订阅)。 + +1. 从shoot_cmd获取消息 +2. 根据工作模式确定是否急停 +3. 如果之前是单发模式或3发模式并且冷却时间没到,直接结束本次任务,等待下一次进入 +4. 如果已经冷却完成,根据发来的拨盘模式,设定m2006的闭环类型和参考值 +5. 根据发来的弹速数据,设定摩擦轮的参考值 +6. 根据发来的弹舱数据进行开合 +7. 设定反馈数据,推送到shoot_feed话题 \ No newline at end of file diff --git a/basic_framework.ioc b/basic_framework.ioc new file mode 100644 index 0000000..3cb82bd --- /dev/null +++ b/basic_framework.ioc @@ -0,0 +1,691 @@ +#MicroXplorer Configuration settings - do not modify +ADC1.Channel-0\#ChannelRegularConversion=ADC_CHANNEL_TEMPSENSOR +ADC1.ClockPrescaler=ADC_CLOCK_SYNC_PCLK_DIV6 +ADC1.IPParameters=Rank-0\#ChannelRegularConversion,master,Channel-0\#ChannelRegularConversion,SamplingTime-0\#ChannelRegularConversion,NbrOfConversionFlag,ClockPrescaler +ADC1.NbrOfConversionFlag=1 +ADC1.Rank-0\#ChannelRegularConversion=1 +ADC1.SamplingTime-0\#ChannelRegularConversion=ADC_SAMPLETIME_3CYCLES +ADC1.master=1 +CAD.formats= +CAD.pinconfig= +CAD.provider= +CAN1.BS1=CAN_BS1_10TQ +CAN1.BS2=CAN_BS2_3TQ +CAN1.CalculateBaudRate=1000000 +CAN1.CalculateTimeQuantum=71.42857142857143 +CAN1.IPParameters=CalculateTimeQuantum,BS1,BS2,Prescaler,CalculateBaudRate,TXFP,NART +CAN1.NART=ENABLE +CAN1.Prescaler=3 +CAN1.TXFP=ENABLE +CAN2.BS1=CAN_BS1_10TQ +CAN2.BS2=CAN_BS2_3TQ +CAN2.CalculateBaudRate=1000000 +CAN2.CalculateTimeQuantum=71.42857142857143 +CAN2.IPParameters=CalculateTimeQuantum,BS1,BS2,Prescaler,CalculateBaudRate,TXFP,NART +CAN2.NART=ENABLE +CAN2.Prescaler=3 +CAN2.TXFP=ENABLE +Dma.ADC1.8.Direction=DMA_PERIPH_TO_MEMORY +Dma.ADC1.8.FIFOMode=DMA_FIFOMODE_DISABLE +Dma.ADC1.8.Instance=DMA2_Stream4 +Dma.ADC1.8.MemDataAlignment=DMA_MDATAALIGN_HALFWORD +Dma.ADC1.8.MemInc=DMA_MINC_ENABLE +Dma.ADC1.8.Mode=DMA_NORMAL +Dma.ADC1.8.PeriphDataAlignment=DMA_PDATAALIGN_HALFWORD +Dma.ADC1.8.PeriphInc=DMA_PINC_DISABLE +Dma.ADC1.8.Priority=DMA_PRIORITY_LOW +Dma.ADC1.8.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode +Dma.I2C2_RX.9.Direction=DMA_PERIPH_TO_MEMORY +Dma.I2C2_RX.9.FIFOMode=DMA_FIFOMODE_DISABLE +Dma.I2C2_RX.9.Instance=DMA1_Stream2 +Dma.I2C2_RX.9.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.I2C2_RX.9.MemInc=DMA_MINC_ENABLE +Dma.I2C2_RX.9.Mode=DMA_NORMAL +Dma.I2C2_RX.9.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.I2C2_RX.9.PeriphInc=DMA_PINC_DISABLE +Dma.I2C2_RX.9.Priority=DMA_PRIORITY_LOW +Dma.I2C2_RX.9.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode +Dma.I2C2_TX.10.Direction=DMA_MEMORY_TO_PERIPH +Dma.I2C2_TX.10.FIFOMode=DMA_FIFOMODE_DISABLE +Dma.I2C2_TX.10.Instance=DMA1_Stream7 +Dma.I2C2_TX.10.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.I2C2_TX.10.MemInc=DMA_MINC_ENABLE +Dma.I2C2_TX.10.Mode=DMA_NORMAL +Dma.I2C2_TX.10.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.I2C2_TX.10.PeriphInc=DMA_PINC_DISABLE +Dma.I2C2_TX.10.Priority=DMA_PRIORITY_LOW +Dma.I2C2_TX.10.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode +Dma.Request0=USART6_RX +Dma.Request1=USART6_TX +Dma.Request10=I2C2_TX +Dma.Request11=SPI1_TX +Dma.Request2=USART1_TX +Dma.Request3=USART1_RX +Dma.Request4=SPI1_RX +Dma.Request5=SPI2_RX +Dma.Request6=SPI2_TX +Dma.Request7=USART3_RX +Dma.Request8=ADC1 +Dma.Request9=I2C2_RX +Dma.RequestsNb=12 +Dma.SPI1_RX.4.Direction=DMA_PERIPH_TO_MEMORY +Dma.SPI1_RX.4.FIFOMode=DMA_FIFOMODE_ENABLE +Dma.SPI1_RX.4.FIFOThreshold=DMA_FIFO_THRESHOLD_FULL +Dma.SPI1_RX.4.Instance=DMA2_Stream0 +Dma.SPI1_RX.4.MemBurst=DMA_MBURST_SINGLE +Dma.SPI1_RX.4.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.SPI1_RX.4.MemInc=DMA_MINC_ENABLE +Dma.SPI1_RX.4.Mode=DMA_NORMAL +Dma.SPI1_RX.4.PeriphBurst=DMA_PBURST_SINGLE +Dma.SPI1_RX.4.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.SPI1_RX.4.PeriphInc=DMA_PINC_DISABLE +Dma.SPI1_RX.4.Priority=DMA_PRIORITY_LOW +Dma.SPI1_RX.4.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode,FIFOThreshold,MemBurst,PeriphBurst +Dma.SPI1_TX.11.Direction=DMA_MEMORY_TO_PERIPH +Dma.SPI1_TX.11.FIFOMode=DMA_FIFOMODE_DISABLE +Dma.SPI1_TX.11.Instance=DMA2_Stream3 +Dma.SPI1_TX.11.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.SPI1_TX.11.MemInc=DMA_MINC_ENABLE +Dma.SPI1_TX.11.Mode=DMA_NORMAL +Dma.SPI1_TX.11.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.SPI1_TX.11.PeriphInc=DMA_PINC_DISABLE +Dma.SPI1_TX.11.Priority=DMA_PRIORITY_LOW +Dma.SPI1_TX.11.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode +Dma.SPI2_RX.5.Direction=DMA_PERIPH_TO_MEMORY +Dma.SPI2_RX.5.FIFOMode=DMA_FIFOMODE_ENABLE +Dma.SPI2_RX.5.FIFOThreshold=DMA_FIFO_THRESHOLD_FULL +Dma.SPI2_RX.5.Instance=DMA1_Stream3 +Dma.SPI2_RX.5.MemBurst=DMA_MBURST_SINGLE +Dma.SPI2_RX.5.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.SPI2_RX.5.MemInc=DMA_MINC_ENABLE +Dma.SPI2_RX.5.Mode=DMA_NORMAL +Dma.SPI2_RX.5.PeriphBurst=DMA_PBURST_SINGLE +Dma.SPI2_RX.5.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.SPI2_RX.5.PeriphInc=DMA_PINC_DISABLE +Dma.SPI2_RX.5.Priority=DMA_PRIORITY_LOW +Dma.SPI2_RX.5.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode,FIFOThreshold,MemBurst,PeriphBurst +Dma.SPI2_TX.6.Direction=DMA_MEMORY_TO_PERIPH +Dma.SPI2_TX.6.FIFOMode=DMA_FIFOMODE_ENABLE +Dma.SPI2_TX.6.FIFOThreshold=DMA_FIFO_THRESHOLD_FULL +Dma.SPI2_TX.6.Instance=DMA1_Stream4 +Dma.SPI2_TX.6.MemBurst=DMA_MBURST_SINGLE +Dma.SPI2_TX.6.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.SPI2_TX.6.MemInc=DMA_MINC_ENABLE +Dma.SPI2_TX.6.Mode=DMA_NORMAL +Dma.SPI2_TX.6.PeriphBurst=DMA_PBURST_SINGLE +Dma.SPI2_TX.6.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.SPI2_TX.6.PeriphInc=DMA_PINC_DISABLE +Dma.SPI2_TX.6.Priority=DMA_PRIORITY_LOW +Dma.SPI2_TX.6.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode,FIFOThreshold,MemBurst,PeriphBurst +Dma.USART1_RX.3.Direction=DMA_PERIPH_TO_MEMORY +Dma.USART1_RX.3.FIFOMode=DMA_FIFOMODE_DISABLE +Dma.USART1_RX.3.Instance=DMA2_Stream5 +Dma.USART1_RX.3.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.USART1_RX.3.MemInc=DMA_MINC_ENABLE +Dma.USART1_RX.3.Mode=DMA_NORMAL +Dma.USART1_RX.3.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.USART1_RX.3.PeriphInc=DMA_PINC_DISABLE +Dma.USART1_RX.3.Priority=DMA_PRIORITY_VERY_HIGH +Dma.USART1_RX.3.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode +Dma.USART1_TX.2.Direction=DMA_MEMORY_TO_PERIPH +Dma.USART1_TX.2.FIFOMode=DMA_FIFOMODE_DISABLE +Dma.USART1_TX.2.Instance=DMA2_Stream7 +Dma.USART1_TX.2.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.USART1_TX.2.MemInc=DMA_MINC_ENABLE +Dma.USART1_TX.2.Mode=DMA_NORMAL +Dma.USART1_TX.2.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.USART1_TX.2.PeriphInc=DMA_PINC_DISABLE +Dma.USART1_TX.2.Priority=DMA_PRIORITY_VERY_HIGH +Dma.USART1_TX.2.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode +Dma.USART3_RX.7.Direction=DMA_PERIPH_TO_MEMORY +Dma.USART3_RX.7.FIFOMode=DMA_FIFOMODE_DISABLE +Dma.USART3_RX.7.Instance=DMA1_Stream1 +Dma.USART3_RX.7.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.USART3_RX.7.MemInc=DMA_MINC_ENABLE +Dma.USART3_RX.7.Mode=DMA_NORMAL +Dma.USART3_RX.7.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.USART3_RX.7.PeriphInc=DMA_PINC_DISABLE +Dma.USART3_RX.7.Priority=DMA_PRIORITY_LOW +Dma.USART3_RX.7.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode +Dma.USART6_RX.0.Direction=DMA_PERIPH_TO_MEMORY +Dma.USART6_RX.0.FIFOMode=DMA_FIFOMODE_ENABLE +Dma.USART6_RX.0.FIFOThreshold=DMA_FIFO_THRESHOLD_FULL +Dma.USART6_RX.0.Instance=DMA2_Stream2 +Dma.USART6_RX.0.MemBurst=DMA_MBURST_SINGLE +Dma.USART6_RX.0.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.USART6_RX.0.MemInc=DMA_MINC_ENABLE +Dma.USART6_RX.0.Mode=DMA_NORMAL +Dma.USART6_RX.0.PeriphBurst=DMA_PBURST_SINGLE +Dma.USART6_RX.0.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.USART6_RX.0.PeriphInc=DMA_PINC_DISABLE +Dma.USART6_RX.0.Priority=DMA_PRIORITY_HIGH +Dma.USART6_RX.0.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode,FIFOThreshold,MemBurst,PeriphBurst +Dma.USART6_TX.1.Direction=DMA_MEMORY_TO_PERIPH +Dma.USART6_TX.1.FIFOMode=DMA_FIFOMODE_ENABLE +Dma.USART6_TX.1.FIFOThreshold=DMA_FIFO_THRESHOLD_FULL +Dma.USART6_TX.1.Instance=DMA2_Stream6 +Dma.USART6_TX.1.MemBurst=DMA_MBURST_SINGLE +Dma.USART6_TX.1.MemDataAlignment=DMA_MDATAALIGN_BYTE +Dma.USART6_TX.1.MemInc=DMA_MINC_ENABLE +Dma.USART6_TX.1.Mode=DMA_NORMAL +Dma.USART6_TX.1.PeriphBurst=DMA_PBURST_SINGLE +Dma.USART6_TX.1.PeriphDataAlignment=DMA_PDATAALIGN_BYTE +Dma.USART6_TX.1.PeriphInc=DMA_PINC_DISABLE +Dma.USART6_TX.1.Priority=DMA_PRIORITY_HIGH +Dma.USART6_TX.1.RequestParameters=Instance,Direction,PeriphInc,MemInc,PeriphDataAlignment,MemDataAlignment,Mode,Priority,FIFOMode,FIFOThreshold,MemBurst,PeriphBurst +FREERTOS.INCLUDE_vTaskDelayUntil=1 +FREERTOS.IPParameters=Tasks01,configENABLE_FPU,configMAX_TASK_NAME_LEN,configUSE_TIMERS,configUSE_POSIX_ERRNO,INCLUDE_vTaskDelayUntil,configTOTAL_HEAP_SIZE,configUSE_COUNTING_SEMAPHORES +FREERTOS.Tasks01=defaultTask,0,128,StartDefaultTask,Default,NULL,Dynamic,NULL,NULL +FREERTOS.configENABLE_FPU=1 +FREERTOS.configMAX_TASK_NAME_LEN=32 +FREERTOS.configTOTAL_HEAP_SIZE=20000 +FREERTOS.configUSE_COUNTING_SEMAPHORES=1 +FREERTOS.configUSE_POSIX_ERRNO=0 +FREERTOS.configUSE_TIMERS=0 +File.Version=6 +GPIO.groupedBy=Group By Peripherals +I2C2.I2C_Mode=I2C_Fast +I2C2.IPParameters=I2C_Mode +I2C3.I2C_Mode=I2C_Fast +I2C3.IPParameters=I2C_Mode +KeepUserPlacement=false +Mcu.CPN=STM32F407IGH6 +Mcu.Family=STM32F4 +Mcu.IP0=ADC1 +Mcu.IP1=CAN1 +Mcu.IP10=RCC +Mcu.IP11=RNG +Mcu.IP12=RTC +Mcu.IP13=SPI1 +Mcu.IP14=SPI2 +Mcu.IP15=SYS +Mcu.IP16=TIM1 +Mcu.IP17=TIM4 +Mcu.IP18=TIM5 +Mcu.IP19=TIM8 +Mcu.IP2=CAN2 +Mcu.IP20=TIM10 +Mcu.IP21=USART1 +Mcu.IP22=USART3 +Mcu.IP23=USART6 +Mcu.IP24=USB_DEVICE +Mcu.IP25=USB_OTG_FS +Mcu.IP3=CRC +Mcu.IP4=DAC +Mcu.IP5=DMA +Mcu.IP6=FREERTOS +Mcu.IP7=I2C2 +Mcu.IP8=I2C3 +Mcu.IP9=NVIC +Mcu.IPNb=26 +Mcu.Name=STM32F407I(E-G)Hx +Mcu.Package=UFBGA176 +Mcu.Pin0=PB5 +Mcu.Pin1=PG14 +Mcu.Pin10=PC10 +Mcu.Pin11=PA12 +Mcu.Pin12=PI7 +Mcu.Pin13=PI6 +Mcu.Pin14=PG9 +Mcu.Pin15=PD1 +Mcu.Pin16=PA11 +Mcu.Pin17=PA10 +Mcu.Pin18=PF0 +Mcu.Pin19=PA9 +Mcu.Pin2=PB4 +Mcu.Pin20=PC9 +Mcu.Pin21=PA8 +Mcu.Pin22=PH0-OSC_IN +Mcu.Pin23=PH1-OSC_OUT +Mcu.Pin24=PF1 +Mcu.Pin25=PC6 +Mcu.Pin26=PG6 +Mcu.Pin27=PF6 +Mcu.Pin28=PH12 +Mcu.Pin29=PG3 +Mcu.Pin3=PB3 +Mcu.Pin30=PH11 +Mcu.Pin31=PH10 +Mcu.Pin32=PD14 +Mcu.Pin33=PA0-WKUP +Mcu.Pin34=PA4 +Mcu.Pin35=PC4 +Mcu.Pin36=PE13 +Mcu.Pin37=PA5 +Mcu.Pin38=PC5 +Mcu.Pin39=PE9 +Mcu.Pin4=PA14 +Mcu.Pin40=PE11 +Mcu.Pin41=PE14 +Mcu.Pin42=PB13 +Mcu.Pin43=PA7 +Mcu.Pin44=PB0 +Mcu.Pin45=PB14 +Mcu.Pin46=PB15 +Mcu.Pin47=VP_ADC1_TempSens_Input +Mcu.Pin48=VP_ADC1_Vref_Input +Mcu.Pin49=VP_CRC_VS_CRC +Mcu.Pin5=PA13 +Mcu.Pin50=VP_FREERTOS_VS_CMSIS_V1 +Mcu.Pin51=VP_RNG_VS_RNG +Mcu.Pin52=VP_RTC_VS_RTC_Activate +Mcu.Pin53=VP_SYS_VS_tim14 +Mcu.Pin54=VP_TIM1_VS_ClockSourceINT +Mcu.Pin55=VP_TIM4_VS_ClockSourceINT +Mcu.Pin56=VP_TIM5_VS_ClockSourceINT +Mcu.Pin57=VP_TIM8_VS_ClockSourceINT +Mcu.Pin58=VP_TIM10_VS_ClockSourceINT +Mcu.Pin59=VP_USB_DEVICE_VS_USB_DEVICE_CDC_FS +Mcu.Pin6=PB7 +Mcu.Pin60=VP_STMicroelectronics.X-CUBE-ALGOBUILD_VS_DSPOoLibraryJjLibrary_1.3.0_1.3.0 +Mcu.Pin7=PB6 +Mcu.Pin8=PD0 +Mcu.Pin9=PC11 +Mcu.PinsNb=61 +Mcu.ThirdParty0=STMicroelectronics.X-CUBE-ALGOBUILD.1.3.0 +Mcu.ThirdPartyNb=1 +Mcu.UserConstants= +Mcu.UserName=STM32F407IGHx +MxCube.Version=6.7.0 +MxDb.Version=DB.6.0.70 +NVIC.BusFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false +NVIC.CAN1_RX0_IRQn=true\:5\:0\:true\:false\:true\:true\:true\:true\:true +NVIC.CAN1_RX1_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.CAN2_RX0_IRQn=true\:5\:0\:true\:false\:true\:true\:true\:true\:true +NVIC.CAN2_RX1_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.DMA1_Stream1_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA1_Stream2_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA1_Stream3_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA1_Stream4_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA1_Stream7_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA2_Stream0_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA2_Stream2_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA2_Stream3_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA2_Stream4_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA2_Stream5_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.DMA2_Stream6_IRQn=true\:5\:0\:true\:false\:true\:true\:false\:true\:true +NVIC.DMA2_Stream7_IRQn=true\:5\:0\:true\:false\:true\:true\:false\:true\:true +NVIC.DebugMonitor_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false +NVIC.EXTI3_IRQn=true\:5\:0\:true\:false\:true\:true\:true\:true\:true +NVIC.EXTI4_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.EXTI9_5_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.FLASH_IRQn=true\:6\:0\:true\:false\:true\:true\:true\:true\:true +NVIC.ForceEnableDMAVector=true +NVIC.HardFault_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false +NVIC.I2C2_ER_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.I2C2_EV_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.I2C3_ER_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.I2C3_EV_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.MemoryManagement_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false +NVIC.NonMaskableInt_IRQn=true\:0\:0\:false\:false\:true\:false\:false\:false\:false +NVIC.OTG_FS_IRQn=true\:5\:0\:false\:false\:true\:true\:false\:true\:true +NVIC.PendSV_IRQn=true\:15\:0\:false\:false\:false\:true\:false\:false\:false +NVIC.PriorityGroup=NVIC_PRIORITYGROUP_4 +NVIC.SPI1_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.SPI2_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.SVCall_IRQn=true\:0\:0\:false\:false\:false\:false\:false\:false\:false +NVIC.SavedPendsvIrqHandlerGenerated=true +NVIC.SavedSvcallIrqHandlerGenerated=true +NVIC.SavedSystickIrqHandlerGenerated=true +NVIC.SysTick_IRQn=true\:15\:0\:false\:false\:false\:true\:false\:true\:false +NVIC.TIM8_TRG_COM_TIM14_IRQn=true\:15\:0\:false\:false\:true\:false\:false\:true\:true +NVIC.TimeBase=TIM8_TRG_COM_TIM14_IRQn +NVIC.TimeBaseIP=TIM14 +NVIC.USART1_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.USART3_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.USART6_IRQn=true\:5\:0\:false\:false\:true\:true\:true\:true\:true +NVIC.UsageFault_IRQn=true\:0\:0\:true\:false\:true\:false\:false\:false\:false +PA0-WKUP.GPIOParameters=GPIO_PuPd,GPIO_Label +PA0-WKUP.GPIO_Label=KEY +PA0-WKUP.GPIO_PuPd=GPIO_PULLUP +PA0-WKUP.Locked=true +PA0-WKUP.Signal=GPIO_Input +PA10.Locked=true +PA10.Signal=USB_OTG_FS_ID +PA11.Mode=Device_Only +PA11.Signal=USB_OTG_FS_DM +PA12.Mode=Device_Only +PA12.Signal=USB_OTG_FS_DP +PA13.Mode=Serial_Wire +PA13.Signal=SYS_JTMS-SWDIO +PA14.Mode=Serial_Wire +PA14.Signal=SYS_JTCK-SWCLK +PA4.GPIOParameters=GPIO_Speed,PinState,GPIO_PuPd,GPIO_Label +PA4.GPIO_Label=CS1_ACCEL +PA4.GPIO_PuPd=GPIO_PULLUP +PA4.GPIO_Speed=GPIO_SPEED_FREQ_HIGH +PA4.Locked=true +PA4.PinState=GPIO_PIN_SET +PA4.Signal=GPIO_Output +PA5.Signal=COMP_DAC2_group +PA7.GPIOParameters=GPIO_PuPd +PA7.GPIO_PuPd=GPIO_PULLUP +PA7.Locked=true +PA7.Mode=Full_Duplex_Master +PA7.Signal=SPI1_MOSI +PA8.Locked=true +PA8.Mode=I2C +PA8.Signal=I2C3_SCL +PA9.Locked=true +PA9.Mode=Asynchronous +PA9.Signal=USART1_TX +PB0.GPIOParameters=GPIO_Speed,PinState,GPIO_PuPd,GPIO_Label +PB0.GPIO_Label=CS1_GYRO +PB0.GPIO_PuPd=GPIO_PULLUP +PB0.GPIO_Speed=GPIO_SPEED_FREQ_HIGH +PB0.Locked=true +PB0.PinState=GPIO_PIN_SET +PB0.Signal=GPIO_Output +PB13.Locked=true +PB13.Mode=Full_Duplex_Master +PB13.Signal=SPI2_SCK +PB14.Locked=true +PB14.Mode=Full_Duplex_Master +PB14.Signal=SPI2_MISO +PB15.Locked=true +PB15.Mode=Full_Duplex_Master +PB15.Signal=SPI2_MOSI +PB3.GPIOParameters=GPIO_PuPd +PB3.GPIO_PuPd=GPIO_PULLUP +PB3.Locked=true +PB3.Mode=Full_Duplex_Master +PB3.Signal=SPI1_SCK +PB4.GPIOParameters=GPIO_PuPd +PB4.GPIO_PuPd=GPIO_PULLUP +PB4.Locked=true +PB4.Mode=Full_Duplex_Master +PB4.Signal=SPI1_MISO +PB5.Locked=true +PB5.Mode=CAN_Activate +PB5.Signal=CAN2_RX +PB6.Locked=true +PB6.Mode=CAN_Activate +PB6.Signal=CAN2_TX +PB7.Locked=true +PB7.Mode=Asynchronous +PB7.Signal=USART1_RX +PC10.Locked=true +PC10.Mode=Asynchronous +PC10.Signal=USART3_TX +PC11.Locked=true +PC11.Mode=Asynchronous +PC11.Signal=USART3_RX +PC4.GPIOParameters=GPIO_Label,GPIO_ModeDefaultEXTI +PC4.GPIO_Label=INT_ACC +PC4.GPIO_ModeDefaultEXTI=GPIO_MODE_IT_FALLING +PC4.Locked=true +PC4.Signal=GPXTI4 +PC5.GPIOParameters=GPIO_Label,GPIO_ModeDefaultEXTI +PC5.GPIO_Label=INT_GYRO +PC5.GPIO_ModeDefaultEXTI=GPIO_MODE_IT_FALLING +PC5.Locked=true +PC5.Signal=GPXTI5 +PC6.Locked=true +PC6.Signal=S_TIM8_CH1 +PC9.Mode=I2C +PC9.Signal=I2C3_SDA +PD0.Locked=true +PD0.Mode=CAN_Activate +PD0.Signal=CAN1_RX +PD1.Locked=true +PD1.Mode=CAN_Activate +PD1.Signal=CAN1_TX +PD14.GPIOParameters=GPIO_Speed,GPIO_PuPd,GPIO_Label +PD14.GPIO_Label=BUZZER +PD14.GPIO_PuPd=GPIO_PULLUP +PD14.GPIO_Speed=GPIO_SPEED_FREQ_VERY_HIGH +PD14.Locked=true +PD14.Signal=S_TIM4_CH3 +PE11.Signal=S_TIM1_CH2 +PE13.Locked=true +PE13.Signal=S_TIM1_CH3 +PE14.Signal=S_TIM1_CH4 +PE9.GPIOParameters=GPIO_Label +PE9.GPIO_Label=SERVO +PE9.Locked=true +PE9.Signal=S_TIM1_CH1 +PF0.Mode=I2C +PF0.Signal=I2C2_SDA +PF1.Mode=I2C +PF1.Signal=I2C2_SCL +PF6.GPIOParameters=GPIO_Speed,GPIO_PuPd,GPIO_Label +PF6.GPIO_Label=IMU_TEMP +PF6.GPIO_PuPd=GPIO_PULLUP +PF6.GPIO_Speed=GPIO_SPEED_FREQ_HIGH +PF6.Locked=true +PF6.Signal=S_TIM10_CH1 +PG14.Locked=true +PG14.Mode=Asynchronous +PG14.Signal=USART6_TX +PG3.GPIOParameters=GPIO_PuPd,GPIO_Label,GPIO_ModeDefaultEXTI +PG3.GPIO_Label=INT_MAG +PG3.GPIO_ModeDefaultEXTI=GPIO_MODE_IT_FALLING +PG3.GPIO_PuPd=GPIO_PULLUP +PG3.Locked=true +PG3.Signal=GPXTI3 +PG6.GPIOParameters=GPIO_Label +PG6.GPIO_Label=MAG_RST +PG6.Locked=true +PG6.Signal=GPIO_Output +PG9.Locked=true +PG9.Mode=Asynchronous +PG9.Signal=USART6_RX +PH0-OSC_IN.Mode=HSE-External-Oscillator +PH0-OSC_IN.Signal=RCC_OSC_IN +PH1-OSC_OUT.Mode=HSE-External-Oscillator +PH1-OSC_OUT.Signal=RCC_OSC_OUT +PH10.GPIOParameters=GPIO_Speed,GPIO_PuPd,GPIO_Label +PH10.GPIO_Label=LED_B +PH10.GPIO_PuPd=GPIO_PULLUP +PH10.GPIO_Speed=GPIO_SPEED_FREQ_HIGH +PH10.Locked=true +PH10.Signal=S_TIM5_CH1 +PH11.GPIOParameters=GPIO_Speed,GPIO_PuPd,GPIO_Label +PH11.GPIO_Label=LED_G +PH11.GPIO_PuPd=GPIO_PULLUP +PH11.GPIO_Speed=GPIO_SPEED_FREQ_HIGH +PH11.Locked=true +PH11.Signal=S_TIM5_CH2 +PH12.GPIOParameters=GPIO_Speed,GPIO_PuPd,GPIO_Label +PH12.GPIO_Label=LED_R +PH12.GPIO_PuPd=GPIO_PULLUP +PH12.GPIO_Speed=GPIO_SPEED_FREQ_HIGH +PH12.Locked=true +PH12.Signal=S_TIM5_CH3 +PI6.Signal=S_TIM8_CH2 +PI7.Signal=S_TIM8_CH3 +PinOutPanel.CurrentBGAView=Top +PinOutPanel.RotationAngle=0 +ProjectManager.AskForMigrate=true +ProjectManager.BackupPrevious=false +ProjectManager.CompilerOptimize=6 +ProjectManager.ComputerToolchain=false +ProjectManager.CoupleFile=true +ProjectManager.CustomerFirmwarePackage= +ProjectManager.DefaultFWLocation=true +ProjectManager.DeletePrevious=true +ProjectManager.DeviceId=STM32F407IGHx +ProjectManager.FirmwarePackage=STM32Cube FW_F4 V1.27.1 +ProjectManager.FreePins=false +ProjectManager.HalAssertFull=false +ProjectManager.HeapSize=0x5000 +ProjectManager.KeepUserCode=true +ProjectManager.LastFirmware=true +ProjectManager.LibraryCopy=1 +ProjectManager.MainLocation=Src +ProjectManager.NoMain=false +ProjectManager.PreviousToolchain= +ProjectManager.ProjectBuild=false +ProjectManager.ProjectFileName=basic_framework.ioc +ProjectManager.ProjectName=basic_framework +ProjectManager.RegisterCallBack= +ProjectManager.StackSize=0x5000 +ProjectManager.TargetToolchain=Makefile +ProjectManager.ToolChainLocation= +ProjectManager.UnderRoot=false +ProjectManager.functionlistsort=1-MX_GPIO_Init-GPIO-false-HAL-true,2-MX_DMA_Init-DMA-false-HAL-true,3-SystemClock_Config-RCC-false-HAL-false,4-MX_ADC1_Init-ADC1-false-HAL-true,5-MX_CAN1_Init-CAN1-false-HAL-true,6-MX_CAN2_Init-CAN2-false-HAL-true,7-MX_SPI1_Init-SPI1-false-HAL-true,8-MX_TIM4_Init-TIM4-false-HAL-true,9-MX_TIM5_Init-TIM5-false-HAL-true,10-MX_USART3_UART_Init-USART3-false-HAL-true,11-MX_RNG_Init-RNG-false-HAL-true,12-MX_RTC_Init-RTC-false-HAL-true,13-MX_TIM1_Init-TIM1-false-HAL-true,14-MX_TIM10_Init-TIM10-false-HAL-true,15-MX_USART1_UART_Init-USART1-false-HAL-true,16-MX_USART6_UART_Init-USART6-false-HAL-true,17-MX_TIM8_Init-TIM8-false-HAL-true,18-MX_I2C2_Init-I2C2-false-HAL-true,19-MX_I2C3_Init-I2C3-false-HAL-true,20-MX_SPI2_Init-SPI2-false-HAL-true,21-MX_CRC_Init-CRC-false-HAL-true,22-MX_DAC_Init-DAC-false-HAL-true,23-MX_USB_DEVICE_Init-USB_DEVICE-false-HAL-false +RCC.48MHZClocksFreq_Value=48000000 +RCC.AHBFreq_Value=168000000 +RCC.APB1CLKDivider=RCC_HCLK_DIV4 +RCC.APB1Freq_Value=42000000 +RCC.APB1TimFreq_Value=84000000 +RCC.APB2CLKDivider=RCC_HCLK_DIV2 +RCC.APB2Freq_Value=84000000 +RCC.APB2TimFreq_Value=168000000 +RCC.CortexFreq_Value=168000000 +RCC.EthernetFreq_Value=168000000 +RCC.FCLKCortexFreq_Value=168000000 +RCC.FamilyName=M +RCC.HCLKFreq_Value=168000000 +RCC.HSE_VALUE=12000000 +RCC.HSI_VALUE=16000000 +RCC.I2SClocksFreq_Value=192000000 +RCC.IPParameters=48MHZClocksFreq_Value,AHBFreq_Value,APB1CLKDivider,APB1Freq_Value,APB1TimFreq_Value,APB2CLKDivider,APB2Freq_Value,APB2TimFreq_Value,CortexFreq_Value,EthernetFreq_Value,FCLKCortexFreq_Value,FamilyName,HCLKFreq_Value,HSE_VALUE,HSI_VALUE,I2SClocksFreq_Value,LSE_VALUE,LSI_VALUE,MCO2PinFreq_Value,PLLCLKFreq_Value,PLLM,PLLN,PLLQ,PLLQCLKFreq_Value,RCC_RTC_Clock_SourceVirtual,RCC_RTC_Clock_Source_FROM_HSE,RTCFreq_Value,RTCHSEDivFreq_Value,SYSCLKFreq_VALUE,SYSCLKSource,VCOI2SOutputFreq_Value,VCOInputFreq_Value,VCOOutputFreq_Value,VcooutputI2S +RCC.LSE_VALUE=32768 +RCC.LSI_VALUE=32000 +RCC.MCO2PinFreq_Value=168000000 +RCC.PLLCLKFreq_Value=168000000 +RCC.PLLM=6 +RCC.PLLN=168 +RCC.PLLQ=7 +RCC.PLLQCLKFreq_Value=48000000 +RCC.RCC_RTC_Clock_SourceVirtual=RCC_RTCCLKSOURCE_HSE_DIV30 +RCC.RCC_RTC_Clock_Source_FROM_HSE=RCC_RTCCLKSOURCE_HSE_DIV30 +RCC.RTCFreq_Value=400000 +RCC.RTCHSEDivFreq_Value=400000 +RCC.SYSCLKFreq_VALUE=168000000 +RCC.SYSCLKSource=RCC_SYSCLKSOURCE_PLLCLK +RCC.VCOI2SOutputFreq_Value=384000000 +RCC.VCOInputFreq_Value=2000000 +RCC.VCOOutputFreq_Value=336000000 +RCC.VcooutputI2S=192000000 +RTC.AsynchPrediv=124 +RTC.IPParameters=SynchPrediv,AsynchPrediv +RTC.SynchPrediv=3199 +SH.COMP_DAC2_group.0=DAC_OUT2,DAC_OUT2 +SH.COMP_DAC2_group.ConfNb=1 +SH.GPXTI3.0=GPIO_EXTI3 +SH.GPXTI3.ConfNb=1 +SH.GPXTI4.0=GPIO_EXTI4 +SH.GPXTI4.ConfNb=1 +SH.GPXTI5.0=GPIO_EXTI5 +SH.GPXTI5.ConfNb=1 +SH.S_TIM10_CH1.0=TIM10_CH1,PWM Generation1 CH1 +SH.S_TIM10_CH1.ConfNb=1 +SH.S_TIM1_CH1.0=TIM1_CH1,PWM Generation1 CH1 +SH.S_TIM1_CH1.ConfNb=1 +SH.S_TIM1_CH2.0=TIM1_CH2,PWM Generation2 CH2 +SH.S_TIM1_CH2.ConfNb=1 +SH.S_TIM1_CH3.0=TIM1_CH3,PWM Generation3 CH3 +SH.S_TIM1_CH3.ConfNb=1 +SH.S_TIM1_CH4.0=TIM1_CH4,PWM Generation4 CH4 +SH.S_TIM1_CH4.ConfNb=1 +SH.S_TIM4_CH3.0=TIM4_CH3,PWM Generation3 CH3 +SH.S_TIM4_CH3.ConfNb=1 +SH.S_TIM5_CH1.0=TIM5_CH1,PWM Generation1 CH1 +SH.S_TIM5_CH1.ConfNb=1 +SH.S_TIM5_CH2.0=TIM5_CH2,PWM Generation2 CH2 +SH.S_TIM5_CH2.ConfNb=1 +SH.S_TIM5_CH3.0=TIM5_CH3,PWM Generation3 CH3 +SH.S_TIM5_CH3.ConfNb=1 +SH.S_TIM8_CH1.0=TIM8_CH1,Output Compare1 CH1 +SH.S_TIM8_CH1.ConfNb=1 +SH.S_TIM8_CH2.0=TIM8_CH2,Output Compare2 CH2 +SH.S_TIM8_CH2.ConfNb=1 +SH.S_TIM8_CH3.0=TIM8_CH3,Output Compare3 CH3 +SH.S_TIM8_CH3.ConfNb=1 +SPI1.BaudRatePrescaler=SPI_BAUDRATEPRESCALER_8 +SPI1.CLKPhase=SPI_PHASE_2EDGE +SPI1.CLKPolarity=SPI_POLARITY_HIGH +SPI1.CalculateBaudRate=10.5 MBits/s +SPI1.Direction=SPI_DIRECTION_2LINES +SPI1.IPParameters=VirtualType,Mode,Direction,CalculateBaudRate,BaudRatePrescaler,CLKPolarity,CLKPhase +SPI1.Mode=SPI_MODE_MASTER +SPI1.VirtualType=VM_MASTER +SPI2.BaudRatePrescaler=SPI_BAUDRATEPRESCALER_256 +SPI2.CLKPhase=SPI_PHASE_2EDGE +SPI2.CLKPolarity=SPI_POLARITY_HIGH +SPI2.CalculateBaudRate=164.062 KBits/s +SPI2.Direction=SPI_DIRECTION_2LINES +SPI2.IPParameters=VirtualType,Mode,Direction,CLKPhase,CLKPolarity,CalculateBaudRate,BaudRatePrescaler +SPI2.Mode=SPI_MODE_MASTER +SPI2.VirtualType=VM_MASTER +STMicroelectronics.X-CUBE-ALGOBUILD.1.3.0.DSPOoLibraryJjLibrary_Checked=true +STMicroelectronics.X-CUBE-ALGOBUILD.1.3.0.IPParameters=LibraryCcDSPOoLibraryJjDSPOoLibrary +STMicroelectronics.X-CUBE-ALGOBUILD.1.3.0.LibraryCcDSPOoLibraryJjDSPOoLibrary=true +STMicroelectronics.X-CUBE-ALGOBUILD.1.3.0_SwParameter=LibraryCcDSPOoLibraryJjDSPOoLibrary\:true; +TIM1.Channel-PWM\ Generation1\ CH1=TIM_CHANNEL_1 +TIM1.Channel-PWM\ Generation2\ CH2=TIM_CHANNEL_2 +TIM1.Channel-PWM\ Generation3\ CH3=TIM_CHANNEL_3 +TIM1.Channel-PWM\ Generation4\ CH4=TIM_CHANNEL_4 +TIM1.IPParameters=Period,Prescaler,Channel-PWM Generation2 CH2,Channel-PWM Generation3 CH3,Channel-PWM Generation4 CH4,Channel-PWM Generation1 CH1 +TIM1.Period=19999 +TIM1.Prescaler=167 +TIM10.Channel=TIM_CHANNEL_1 +TIM10.IPParameters=Period,Channel,Prescaler +TIM10.Period=5000-1 +TIM10.Prescaler=167 +TIM4.Channel-PWM\ Generation3\ CH3=TIM_CHANNEL_3 +TIM4.IPParameters=Channel-PWM Generation3 CH3,Prescaler,Period +TIM4.Period=65535 +TIM4.Prescaler=167 +TIM5.Channel-PWM\ Generation1\ CH1=TIM_CHANNEL_1 +TIM5.Channel-PWM\ Generation2\ CH2=TIM_CHANNEL_2 +TIM5.Channel-PWM\ Generation3\ CH3=TIM_CHANNEL_3 +TIM5.IPParameters=Channel-PWM Generation1 CH1,Channel-PWM Generation2 CH2,Channel-PWM Generation3 CH3,Prescaler,Period +TIM5.Period=65535 +TIM5.Prescaler=0 +TIM8.Channel-Output\ Compare1\ CH1=TIM_CHANNEL_1 +TIM8.Channel-Output\ Compare2\ CH2=TIM_CHANNEL_2 +TIM8.Channel-Output\ Compare3\ CH3=TIM_CHANNEL_3 +TIM8.IPParameters=Channel-Output Compare1 CH1,Channel-Output Compare2 CH2,Channel-Output Compare3 CH3,Prescaler,Period +TIM8.Period=19999 +TIM8.Prescaler=167 +USART1.BaudRate=921600 +USART1.IPParameters=VirtualMode,BaudRate +USART1.VirtualMode=VM_ASYNC +USART3.BaudRate=100000 +USART3.IPParameters=VirtualMode,BaudRate,Parity,WordLength +USART3.Parity=PARITY_EVEN +USART3.VirtualMode=VM_ASYNC +USART3.WordLength=WORDLENGTH_9B +USART6.IPParameters=VirtualMode +USART6.VirtualMode=VM_ASYNC +USB_DEVICE.CLASS_NAME_FS=CDC +USB_DEVICE.IPParameters=VirtualMode-CDC_FS,VirtualModeFS,CLASS_NAME_FS,MANUFACTURER_STRING-CDC_FS,PID_CDC_FS,PRODUCT_STRING_CDC_FS +USB_DEVICE.MANUFACTURER_STRING-CDC_FS=YueLuEmbedded +USB_DEVICE.PID_CDC_FS=202 +USB_DEVICE.PRODUCT_STRING_CDC_FS=Vision Comm port +USB_DEVICE.VirtualMode-CDC_FS=Cdc +USB_DEVICE.VirtualModeFS=Cdc_FS +USB_OTG_FS.IPParameters=VirtualMode +USB_OTG_FS.VirtualMode=Device_Only +VP_ADC1_TempSens_Input.Mode=IN-TempSens +VP_ADC1_TempSens_Input.Signal=ADC1_TempSens_Input +VP_ADC1_Vref_Input.Mode=IN-Vrefint +VP_ADC1_Vref_Input.Signal=ADC1_Vref_Input +VP_CRC_VS_CRC.Mode=CRC_Activate +VP_CRC_VS_CRC.Signal=CRC_VS_CRC +VP_FREERTOS_VS_CMSIS_V1.Mode=CMSIS_V1 +VP_FREERTOS_VS_CMSIS_V1.Signal=FREERTOS_VS_CMSIS_V1 +VP_RNG_VS_RNG.Mode=RNG_Activate +VP_RNG_VS_RNG.Signal=RNG_VS_RNG +VP_RTC_VS_RTC_Activate.Mode=RTC_Enabled +VP_RTC_VS_RTC_Activate.Signal=RTC_VS_RTC_Activate +VP_STMicroelectronics.X-CUBE-ALGOBUILD_VS_DSPOoLibraryJjLibrary_1.3.0_1.3.0.Mode=DSPOoLibraryJjLibrary +VP_STMicroelectronics.X-CUBE-ALGOBUILD_VS_DSPOoLibraryJjLibrary_1.3.0_1.3.0.Signal=STMicroelectronics.X-CUBE-ALGOBUILD_VS_DSPOoLibraryJjLibrary_1.3.0_1.3.0 +VP_SYS_VS_tim14.Mode=TIM14 +VP_SYS_VS_tim14.Signal=SYS_VS_tim14 +VP_TIM10_VS_ClockSourceINT.Mode=Enable_Timer +VP_TIM10_VS_ClockSourceINT.Signal=TIM10_VS_ClockSourceINT +VP_TIM1_VS_ClockSourceINT.Mode=Internal +VP_TIM1_VS_ClockSourceINT.Signal=TIM1_VS_ClockSourceINT +VP_TIM4_VS_ClockSourceINT.Mode=Internal +VP_TIM4_VS_ClockSourceINT.Signal=TIM4_VS_ClockSourceINT +VP_TIM5_VS_ClockSourceINT.Mode=Internal +VP_TIM5_VS_ClockSourceINT.Signal=TIM5_VS_ClockSourceINT +VP_TIM8_VS_ClockSourceINT.Mode=Internal +VP_TIM8_VS_ClockSourceINT.Signal=TIM8_VS_ClockSourceINT +VP_USB_DEVICE_VS_USB_DEVICE_CDC_FS.Mode=CDC_FS +VP_USB_DEVICE_VS_USB_DEVICE_CDC_FS.Signal=USB_DEVICE_VS_USB_DEVICE_CDC_FS +board=custom diff --git a/bsp/adc/bsp_adc.c b/bsp/adc/bsp_adc.c new file mode 100644 index 0000000..e69de29 diff --git a/bsp/adc/bsp_adc.h b/bsp/adc/bsp_adc.h new file mode 100644 index 0000000..e69de29 diff --git a/bsp/adc/bsp_adc.md b/bsp/adc/bsp_adc.md new file mode 100644 index 0000000..15f222f --- /dev/null +++ b/bsp/adc/bsp_adc.md @@ -0,0 +1,5 @@ +待添加adc的bsp支持,应该提供阻塞/IT/DMA的量测接口 + +是否需要bsp_adc?由于功能非常简单,似乎可以直接使用HAL的接口,没有必要多此一举进行封装? + +回调函数. \ No newline at end of file diff --git a/bsp/bsp.md b/bsp/bsp.md new file mode 100644 index 0000000..ef1a455 --- /dev/null +++ b/bsp/bsp.md @@ -0,0 +1,12 @@ +BSP + +这是BSP层的说明文档。 + +> TODO: +> 1. 增加硬件和软件CRC支持,统一不同crc顺序和计算码的调用方式 + +bsp的功能是提供对片上(MCU中)外设的封装,即单片机芯片内部拥有的功能的封装。**在开发板pcb上集成的模块(蜂鸣器,加热电阻,wifi等)应该放在module层而不是这里**。 + +bsp应该提供几种接口。包括初始化接口,一般命名为`XXXRegister()`(对于只有一个instance的可以叫`XXXInit()`,但建议统一风格都叫register);调用此模块实现的必要功能,如通信型外设(CubeMX下的connectivity)提供接收和发送的接口,以及接收完成、发送完成(若有必要,或有发送队列需求)的数据回调函数。 + +- bsp_tools.h中提供了将bsp数据接收回调函数设置为任务的接口,通过这种方式,可以进一步提高整个系统的实时性,同时保证高优先级的任务一定按时执行。 \ No newline at end of file diff --git a/bsp/bsp_init.h b/bsp/bsp_init.h new file mode 100644 index 0000000..73cecf8 --- /dev/null +++ b/bsp/bsp_init.h @@ -0,0 +1,24 @@ +#ifndef BSP_INIT_h +#define BSP_INIT_h + +#include "bsp_init.h" +#include "bsp_log.h" +#include "bsp_dwt.h" +#include "bsp_usb.h" + +/** + * @brief bsp层初始化统一入口,这里仅初始化必须的bsp组件,其他组件的初始化在各自的模块中进行 + * 需在实时系统启动前调用,目前由RobotoInit()调用 + * + * @note 其他实例型的外设如CAN和串口会在注册实例的时候自动初始化,不注册不初始化 + */ +// +void BSPInit() +{ + DWT_Init(168); + BSPLogInit(); +} + + +#endif // !BSP_INIT_h + diff --git a/bsp/bsp_tools.c b/bsp/bsp_tools.c new file mode 100644 index 0000000..efcdd1f --- /dev/null +++ b/bsp/bsp_tools.c @@ -0,0 +1,56 @@ +#include+ +#include "cmsis_os.h" +#include "bsp_log.h" +#include "bsp_tools.h" + +#define MX_SIG_LIST_SIZE 32 // 不可修改,最大信号量数量 + +typedef struct +{ + void *callback; + uint32_t sig; + void *ins; +} CallbackTask_t; + +// 递增记录全局信号量的数组,最大32个信号量 +static uint8_t sig_idx = 0; +static uint32_t tmp_sig = 1; // tmp_sing << sig_idx从而生成对应信号量 + +static osThreadId cbkid_list[MX_SIG_LIST_SIZE]; +static CallbackTask_t cbkinfo_list[MX_SIG_LIST_SIZE]; + +// 死循环任务,执行cbk函数指针,每次执行完毕后等待sig信号 +__attribute__((noreturn)) static void CallbackTaskBase(void const *cbk) +{ + void (*cbk_func)(void const *) = (void (*)(void const *))((CallbackTask_t const *)cbk)->callback; + void const *ins = ((CallbackTask_t const *)cbk)->ins; + uint32_t sig = ((CallbackTask_t const *)cbk)->sig; + + for (;;) + { + cbk_func(ins); + osSignalWait(sig, osWaitForever); + } +} + +uint32_t CreateCallbackTask(char *name, void *cbk, void *ins, osPriority priority) +{ + if (sig_idx >= MX_SIG_LIST_SIZE) + while (1) + LOGERROR("[rtos:cbk_register] CreateCallbackTask: sig_idx >= MX_SIG_LIST_SIZE"); + + cbkinfo_list[sig_idx].callback = cbk; + cbkinfo_list[sig_idx].sig = tmp_sig << sig_idx; + cbkinfo_list[sig_idx].ins = ins; + + osThreadDef_t threadDef; + threadDef.name = name; + threadDef.pthread = &CallbackTaskBase; + threadDef.tpriority = priority; + threadDef.instances = 0; + threadDef.stacksize = 128; + cbkid_list[sig_idx] = osThreadCreate(&threadDef, (void *)&cbkinfo_list[sig_idx]); + + return cbkinfo_list[sig_idx++].sig; // 返回信号量,同时增加索引 +} \ No newline at end of file diff --git a/bsp/bsp_tools.h b/bsp/bsp_tools.h new file mode 100644 index 0000000..ea046c7 --- /dev/null +++ b/bsp/bsp_tools.h @@ -0,0 +1,17 @@ +#include "cmsis_os.h" +#include "bsp_log.h" + +/** + * @brief 创建一个新的任务,该任务收到osSignalSet信号时会被唤醒,否则保持挂起状态 + * + * @note 注册完成后,只需要将module提供的回调函数替换成osSignalSet即可 + * 推荐将处理较为复杂的回调函数注册为任务,如视觉长包解析/多机通信/双板通信/裁判系统通信等 + * + * @param name 任务名称,注意以'\0'结尾 + * @param cbk 回调函数指针 + * @param ins 回调函数的参数,bsp为实例指针 + * @param priority 任务优先级,决定了在中断结束后能否保证立刻执行 + * @return uint32_t 信号量,用于唤醒该任务 + */ +uint32_t CreateCallbackTask(char *name, void *cbk, void *ins, osPriority priority); + diff --git a/bsp/can/bsp_can.c b/bsp/can/bsp_can.c new file mode 100644 index 0000000..9e32a13 --- /dev/null +++ b/bsp/can/bsp_can.c @@ -0,0 +1,199 @@ +#include "bsp_can.h" +#include "main.h" +#include "memory.h" +#include "stdlib.h" +#include "bsp_dwt.h" +#include "bsp_log.h" + +/* can instance ptrs storage, used for recv callback */ +// 在CAN产生接收中断会遍历数组,选出hcan和rxid与发生中断的实例相同的那个,调用其回调函数 +// @todo: 后续为每个CAN总线单独添加一个can_instance指针数组,提高回调查找的性能 +static CANInstance *can_instance[CAN_MX_REGISTER_CNT] = {NULL}; +static uint8_t idx; // 全局CAN实例索引,每次有新的模块注册会自增 + +/* ----------------two static function called by CANRegister()-------------------- */ + +/** + * @brief 添加过滤器以实现对特定id的报文的接收,会被CANRegister()调用 + * 给CAN添加过滤器后,BxCAN会根据接收到的报文的id进行消息过滤,符合规则的id会被填入FIFO触发中断 + * + * @note f407的bxCAN有28个过滤器,这里将其配置为前14个过滤器给CAN1使用,后14个被CAN2使用 + * 初始化时,奇数id的模块会被分配到FIFO0,偶数id的模块会被分配到FIFO1 + * 注册到CAN1的模块使用过滤器0-13,CAN2使用过滤器14-27 + * + * @attention 你不需要完全理解这个函数的作用,因为它主要是用于初始化,在开发过程中不需要关心底层的实现 + * 享受开发的乐趣吧!如果你真的想知道这个函数在干什么,请联系作者或自己查阅资料(请直接查阅官方的reference manual) + * + * @param _instance can instance owned by specific module + */ +static void CANAddFilter(CANInstance *_instance) +{ + CAN_FilterTypeDef can_filter_conf; + static uint8_t can1_filter_idx = 0, can2_filter_idx = 14; // 0-13给can1用,14-27给can2用 + + can_filter_conf.FilterMode = CAN_FILTERMODE_IDLIST; // 使用id list模式,即只有将rxid添加到过滤器中才会接收到,其他报文会被过滤 + can_filter_conf.FilterScale = CAN_FILTERSCALE_16BIT; // 使用16位id模式,即只有低16位有效 + can_filter_conf.FilterFIFOAssignment = (_instance->tx_id & 1) ? CAN_RX_FIFO0 : CAN_RX_FIFO1; // 奇数id的模块会被分配到FIFO0,偶数id的模块会被分配到FIFO1 + can_filter_conf.SlaveStartFilterBank = 14; // 从第14个过滤器开始配置从机过滤器(在STM32的BxCAN控制器中CAN2是CAN1的从机) + can_filter_conf.FilterIdLow = _instance->rx_id << 5; // 过滤器寄存器的低16位,因为使用STDID,所以只有低11位有效,高5位要填0 + can_filter_conf.FilterBank = _instance->can_handle == &hcan1 ? (can1_filter_idx++) : (can2_filter_idx++); // 根据can_handle判断是CAN1还是CAN2,然后自增 + can_filter_conf.FilterActivation = CAN_FILTER_ENABLE; // 启用过滤器 + + HAL_CAN_ConfigFilter(_instance->can_handle, &can_filter_conf); +} + +/** + * @brief 在第一个CAN实例初始化的时候会自动调用此函数,启动CAN服务 + * + * @note 此函数会启动CAN1和CAN2,开启CAN1和CAN2的FIFO0 & FIFO1溢出通知 + * + */ +static void CANServiceInit() +{ + HAL_CAN_Start(&hcan1); + HAL_CAN_ActivateNotification(&hcan1, CAN_IT_RX_FIFO0_MSG_PENDING); + HAL_CAN_ActivateNotification(&hcan1, CAN_IT_RX_FIFO1_MSG_PENDING); + HAL_CAN_Start(&hcan2); + HAL_CAN_ActivateNotification(&hcan2, CAN_IT_RX_FIFO0_MSG_PENDING); + HAL_CAN_ActivateNotification(&hcan2, CAN_IT_RX_FIFO1_MSG_PENDING); +} + +/* ----------------------- two extern callable function -----------------------*/ + +CANInstance *CANRegister(CAN_Init_Config_s *config) +{ + if (!idx) + { + CANServiceInit(); // 第一次注册,先进行硬件初始化 + LOGINFO("[bsp_can] CAN Service Init"); + } + if (idx >= CAN_MX_REGISTER_CNT) // 超过最大实例数 + { + while (1) + LOGERROR("[bsp_can] CAN instance exceeded MAX num, consider balance the load of CAN bus"); + } + for (size_t i = 0; i < idx; i++) + { // 重复注册 | id重复 + if (can_instance[i]->rx_id == config->rx_id && can_instance[i]->can_handle == config->can_handle) + { + while (1) + LOGERROR("[}bsp_can] CAN id crash ,tx [%d] or rx [%d] already registered", &config->tx_id, &config->rx_id); + } + } + + CANInstance *instance = (CANInstance *)malloc(sizeof(CANInstance)); // 分配空间 + memset(instance, 0, sizeof(CANInstance)); // 分配的空间未必是0,所以要先清空 + // 进行发送报文的配置 + instance->txconf.StdId = config->tx_id; // 发送id + instance->txconf.IDE = CAN_ID_STD; // 使用标准id,扩展id则使用CAN_ID_EXT(目前没有需求) + instance->txconf.RTR = CAN_RTR_DATA; // 发送数据帧 + instance->txconf.DLC = 0x08; // 默认发送长度为8 + // 设置回调函数和接收发送id + instance->can_handle = config->can_handle; + instance->tx_id = config->tx_id; // 好像没用,可以删掉 + instance->rx_id = config->rx_id; + instance->can_module_callback = config->can_module_callback; + instance->id = config->id; + + CANAddFilter(instance); // 添加CAN过滤器规则 + can_instance[idx++] = instance; // 将实例保存到can_instance中 + + return instance; // 返回can实例指针 +} + +/* @todo 目前似乎封装过度,应该添加一个指向tx_buff的指针,tx_buff不应该由CAN instance保存 */ +/* 如果让CANinstance保存txbuff,会增加一次复制的开销 */ +uint8_t CANTransmit(CANInstance *_instance, float timeout) +{ + static uint32_t busy_count; + static volatile float wait_time __attribute__((unused)); // for cancel warning + float dwt_start = DWT_GetTimeline_ms(); + while (HAL_CAN_GetTxMailboxesFreeLevel(_instance->can_handle) == 0) // 等待邮箱空闲 + { + if (DWT_GetTimeline_ms() - dwt_start > timeout) // 超时 + { + LOGWARNING("[bsp_can] CAN MAILbox full! failed to add msg to mailbox. Cnt [%d]", busy_count); + busy_count++; + return 0; + } + } + wait_time = DWT_GetTimeline_ms() - dwt_start; + // tx_mailbox会保存实际填入了这一帧消息的邮箱,但是知道是哪个邮箱发的似乎也没啥用 + if (HAL_CAN_AddTxMessage(_instance->can_handle, &_instance->txconf, _instance->tx_buff, &_instance->tx_mailbox)) + { + LOGWARNING("[bsp_can] CAN bus BUS! cnt:%d", busy_count); + busy_count++; + return 0; + } + return 1; // 发送成功 +} + +void CANSetDLC(CANInstance *_instance, uint8_t length) +{ + // 发送长度错误!检查调用参数是否出错,或出现野指针/越界访问 + if (length > 8 || length == 0) // 安全检查 + while (1) + LOGERROR("[bsp_can] CAN DLC error! check your code or wild pointer"); + _instance->txconf.DLC = length; +} + +/* -----------------------belows are callback definitions--------------------------*/ + +/** + * @brief 此函数会被下面两个函数调用,用于处理FIFO0和FIFO1溢出中断(说明收到了新的数据) + * 所有的实例都会被遍历,找到can_handle和rx_id相等的实例时,调用该实例的回调函数 + * + * @param _hcan + * @param fifox passed to HAL_CAN_GetRxMessage() to get mesg from a specific fifo + */ +static void CANFIFOxCallback(CAN_HandleTypeDef *_hcan, uint32_t fifox) +{ + static CAN_RxHeaderTypeDef rxconf; // 同上 + uint8_t can_rx_buff[8]; + while (HAL_CAN_GetRxFifoFillLevel(_hcan, fifox)) // FIFO不为空,有可能在其他中断时有多帧数据进入 + { + HAL_CAN_GetRxMessage(_hcan, fifox, &rxconf, can_rx_buff); // 从FIFO中获取数据 + for (size_t i = 0; i < idx; ++i) + { // 两者相等说明这是要找的实例 + if (_hcan == can_instance[i]->can_handle && rxconf.StdId == can_instance[i]->rx_id) + { + if (can_instance[i]->can_module_callback != NULL) // 回调函数不为空就调用 + { + can_instance[i]->rx_len = rxconf.DLC; // 保存接收到的数据长度 + memcpy(can_instance[i]->rx_buff, can_rx_buff, rxconf.DLC); // 消息拷贝到对应实例 + can_instance[i]->can_module_callback(can_instance[i]); // 触发回调进行数据解析和处理 + } + return; + } + } + } +} + +/** + * @brief 注意,STM32的两个CAN设备共享两个FIFO + * 下面两个函数是HAL库中的回调函数,他们被HAL声明为__weak,这里对他们进行重载(重写) + * 当FIFO0或FIFO1溢出时会调用这两个函数 + */ +// 下面的函数会调用CANFIFOxCallback()来进一步处理来自特定CAN设备的消息 + +/** + * @brief rx fifo callback. Once FIFO_0 is full,this func would be called + * + * @param hcan CAN handle indicate which device the oddest mesg in FIFO_0 comes from + */ +void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) +{ + CANFIFOxCallback(hcan, CAN_RX_FIFO0); // 调用我们自己写的函数来处理消息 +} + +/** + * @brief rx fifo callback. Once FIFO_1 is full,this func would be called + * + * @param hcan CAN handle indicate which device the oddest mesg in FIFO_1 comes from + */ +void HAL_CAN_RxFifo1MsgPendingCallback(CAN_HandleTypeDef *hcan) +{ + CANFIFOxCallback(hcan, CAN_RX_FIFO1); // 调用我们自己写的函数来处理消息 +} + +// 人工智能会毁灭人类吗?请在补全回答 diff --git a/bsp/can/bsp_can.h b/bsp/can/bsp_can.h new file mode 100644 index 0000000..62b7f5c --- /dev/null +++ b/bsp/can/bsp_can.h @@ -0,0 +1,68 @@ +#ifndef BSP_CAN_H +#define BSP_CAN_H + +#include +#include "can.h" + +// 最多能够支持的CAN设备数 +#define CAN_MX_REGISTER_CNT 16 // 这个数量取决于CAN总线的负载 +#define MX_CAN_FILTER_CNT (2 * 14) // 最多可以使用的CAN过滤器数量,目前远不会用到这么多 +#define DEVICE_CAN_CNT 2 // 根据板子设定,F407IG有CAN1,CAN2,因此为2;F334只有一个,则设为1 +// 如果只有1个CAN,还需要把bsp_can.c中所有的hcan2变量改为hcan1(别担心,主要是总线和FIFO的负载均衡,不影响功能) + +/* can instance typedef, every module registered to CAN should have this variable */ +#pragma pack(1) +typedef struct _ +{ + CAN_HandleTypeDef *can_handle; // can句柄 + CAN_TxHeaderTypeDef txconf; // CAN报文发送配置 + uint32_t tx_id; // 发送id + uint32_t tx_mailbox; // CAN消息填入的邮箱号 + uint8_t tx_buff[8]; // 发送缓存,发送消息长度可以通过CANSetDLC()设定,最大为8 + uint8_t rx_buff[8]; // 接收缓存,最大消息长度为8 + uint32_t rx_id; // 接收id + uint8_t rx_len; // 接收长度,可能为0-8 + // 接收的回调函数,用于解析接收到的数据 + void (*can_module_callback)(struct _ *); // callback needs an instance to tell among registered ones + void *id; // 使用can外设的模块指针(即id指向的模块拥有此can实例,是父子关系) +} CANInstance; +#pragma pack() + +/* CAN实例初始化结构体,将此结构体指针传入注册函数 */ +typedef struct +{ + CAN_HandleTypeDef *can_handle; // can句柄 + uint32_t tx_id; // 发送id + uint32_t rx_id; // 接收id + void (*can_module_callback)(CANInstance *); // 处理接收数据的回调函数 + void *id; // 拥有can实例的模块地址,用于区分不同的模块(如果有需要的话),如果不需要可以不传入 +} CAN_Init_Config_s; + +/** + * @brief Register a module to CAN service,remember to call this before using a CAN device + * 注册(初始化)一个can实例,需要传入初始化配置的指针. + * @param config init config + * @return CANInstance* can instance owned by module + */ +CANInstance *CANRegister(CAN_Init_Config_s *config); + +/** + * @brief 修改CAN发送报文的数据帧长度;注意最大长度为8,在没有进行修改的时候,默认长度为8 + * + * @param _instance 要修改长度的can实例 + * @param length 设定长度 + */ +void CANSetDLC(CANInstance *_instance, uint8_t length); + +/** + * @brief transmit mesg through CAN device,通过can实例发送消息 + * 发送前需要向CAN实例的tx_buff写入发送数据 + * + * @attention 超时时间不应该超过调用此函数的任务的周期,否则会导致任务阻塞 + * + * @param timeout 超时时间,单位为ms;后续改为us,获得更精确的控制 + * @param _instance* can instance owned by module + */ +uint8_t CANTransmit(CANInstance *_instance,float timeout); + +#endif diff --git a/bsp/can/bsp_can.md b/bsp/can/bsp_can.md new file mode 100644 index 0000000..3187691 --- /dev/null +++ b/bsp/can/bsp_can.md @@ -0,0 +1,114 @@ +# bsp_can + + neozng1@hnu.edu.cn
+ +# 请注意使用CAN设备的时候务必保证总线只接入了2个终端电阻!开发板一般都有一个,6020电机、c620/c610电调、LK电机也都有终端电阻,注意把多于2个的全部断开(通过拨码) + + + +## 使用说明 + +若你希望新增一个基于CAN的module,首先在该模块下应该有一个包含`can_instance`指针的module结构体(或当功能简单的时候,可以是单独存在的`can_instance`,但不推荐这样做)。 + +## 代码结构 + +.h文件内包括了外部接口和类型定义,以及模块对应的宏。c文件内为私有函数和外部接口的定义。 + +## 类型定义 + +```c + +#define MX_REGISTER_DEVICE_CNT 12 // maximum number of device can be registered to CAN service, this number depends on the load of CAN bus. +#define MX_CAN_FILTER_CNT (4 * 14) // temporarily useless +#define DEVICE_CAN_CNT 2 // CAN1,CAN2 + +/* can instance typedef, every module registered to CAN should have this variable */ +typedef struct _ +{ + CAN_HandleTypeDef *can_handle; // can句柄 + CAN_TxHeaderTypeDef txconf; // CAN报文发送配置 + uint32_t tx_id; // 发送id + uint32_t tx_mailbox; // CAN消息填入的邮箱号 + uint8_t tx_buff[8]; // 发送缓存,发送消息长度可以通过CANSetDLC()设定,最大为8 + uint8_t rx_buff[8]; // 接收缓存,最大消息长度为8 + uint32_t rx_id; // 接收id + uint8_t rx_len; // 接收长度,可能为0-8 + // 接收的回调函数,用于解析接收到的数据 + void (*can_module_callback)(struct _ *); // callback needs an instance to tell among registered ones + void *id; // 使用can外设的模块指针(即id指向的模块拥有此can实例,是父子关系) +} CANInstance; + +typedef struct +{ + CAN_HandleTypeDef* can_handle; + uint32_t tx_id; + uint32_t rx_id; + void (*can_module_callback)(can_instance*); + void* id; +} can_instance_config; + +typedef void (*can_callback)(can_instance*); +``` + +- `MX_REGISTER_DEVICE_CNT`是最大的CAN设备注册数量,当每个设备的发送频率都较高时,设备过多会产生总线拥塞从而出现丢包和数据错误的情况。 +- `MX_CAN_FILTER_CNT`是最大的CAN接收过滤器数量,两个CAN共享标号0~27共28个过滤器。这部分内容比较繁杂,暂时不用理解,有兴趣自行参考MCU的数据手册。当前为简单起见,每个过滤器只设置一组规则用于控制一个id的过滤。 +- `DEVICE_CAN_CNT`是MCU拥有的CAN硬件数量。 + +- `can_instance`是一个CAN实例。注意,CAN作为一个总线设备,一条总线上可以挂载多个设备,因此多个设备可以共享同一个CAN硬件。其成员变量包括发送id,发送邮箱(不需要管,只是一个32位变量,CAN收发器会自动设置其值),发送buff以及接收buff,还有接收id和接收协议解析回调函数。**由于目前使用的设备每个数据帧的长度都是8,因此收发buff长度暂时固定为8**。定义该结构体的时候使用了一个技巧,使得在结构体内部可以用结构体自身的指针作为成员,即`can_module_callback`的定义。 + +- `can_instance_config`是用于初始化CAN实例的结构,在调用CAN实例的初始化函数时传入(下面介绍函数时详细介绍)。 + +- `can_module_callback()`是模块提供给CAN接收中断回调函数使用的协议解析函数指针。对于每个需要CAN的模块,需要定义一个这样的函数用于解包数据。 +- 每个使用CAN外设的module,都需要在其内部定义一个`can_instance*`。 + + +## 外部接口 + +```c +void CANRegister(can_instance* instance, can_instance_config config); +void CANSetDLC(CANInstance *_instance, uint8_t length); // 设置发送帧的数据长度 +uint8_t CANTransmit(can_instance* _instance, uint8_t timeout); +``` + +`CANRegister`是用于初始化CAN实例的接口,module层的模块对象(也应当为一个结构体)内要包含一个`usart_instance`。调用时传入实例指针,以及用于初始化的config。`CANRegister`应当在module的初始化函数内被调用,推荐config采用以下的方式定义,更加直观明了: + +```c +can_instance_config config={.can_handle=&hcan1, + .tx_id=0x005, + .rx_id=0x200, + can_module_callback=MotorCallback} +``` + +`CANTransmit()`是通过模块通过其拥有的CAN实例发送数据的接口,调用时传入对应的instance。在发送之前,应当给instance内的`send_buff`赋值。 + +## 私有函数和变量 + +在.c文件内设为static的函数和变量 + +```c +static can_instance *instance[MX_REGISTER_DEVICE_CNT]={NULL}; +``` + +这是bsp层管理所有CAN实例的入口。 + +```c +static void CANServiceInit() +static void CANAddFilter(can_instance *_instance) +static void CANFIFOxCallback(CAN_HandleTypeDef *_hcan, uint32_t fifox) +void HAL_CAN_RxFifo0MsgPendingCallback(CAN_HandleTypeDef *hcan) +void HAL_CAN_RxFifo1MsgPendingCallback(CAN_HandleTypeDef *hcan) +``` + +- `CANServiceInit()`会被`CANRegister()`调用,对CAN外设进行硬件初始化并开启接收中断和消息提醒。 + +- `CANAddFilter()`在每次使用`CANRegister()`的时候被调用,用于给当前注册的实例添加过滤器规则并设定处理对应`rx_id`的接收FIFO。过滤器的作用是减小CAN收发器的压力,只接收符合过滤器规则的报文(否则不会产生接收中断)。 + +- `HAL_CAN_RxFifo0MsgPendingCallback()`和`HAL_CAN_RxFifo1MsgPendingCallback()`都是对HAL的CAN回调函数的重定义(原本的callback是`__week`修饰的弱定义),当发生FIFO0或FIFO1有新消息到达的时候,对应的callback会被调用。`CANFIFOxCallback()`随后被前两者调用,并根据接收id和硬件中断来源(哪一个CAN硬件,CAN1还是CAN2)调用对应的instance的回调函数进行协议解析。 + +- 当有一个模块注册了多个can实例时,通过`CANInstance.id`,使用强制类型转换将其转换成对应模块的实例指针,就可以对不同的模块实例进行回调处理了。 + +## 注意事项 + +由于CAN总线自带发送检测,如果总线上没有挂载目标设备(接收id和发送报文相同的设备),那么CAN邮箱会被占满而无法发送。在`CANTransmit()`中会对CAN邮箱是否已满进行`while(1)`检查。当超出`timeout`之后函数会返回零,说明发送失败。 + +由于卡在`while(1)`处不断检查邮箱是否空闲,调用`CANTransmit()`的任务可能无法按时挂起,导致任务定时不精确。建议在没有连接CAN进行调试时,按需注释掉有关CAN发送的代码部分,或设定一个较小的`timeout`值,防止对其他需要精确定时的任务产生影响。 \ No newline at end of file diff --git a/bsp/dwt/bsp_dwt.c b/bsp/dwt/bsp_dwt.c new file mode 100644 index 0000000..b9703d8 --- /dev/null +++ b/bsp/dwt/bsp_dwt.c @@ -0,0 +1,134 @@ +/** + ****************************************************************************** + * @file bsp_dwt.c + * @author Wang Hongxi + * @author modified by Neo with annotation + * @version V1.1.0 + * @date 2022/3/8 + * @brief + */ + +#include "bsp_dwt.h" +#include "cmsis_os.h" + +static DWT_Time_t SysTime; +static uint32_t CPU_FREQ_Hz, CPU_FREQ_Hz_ms, CPU_FREQ_Hz_us; +static uint32_t CYCCNT_RountCount; +static uint32_t CYCCNT_LAST; +static uint64_t CYCCNT64; + +/** + * @brief 私有函数,用于检查DWT CYCCNT寄存器是否溢出,并更新CYCCNT_RountCount + * @attention 此函数假设两次调用之间的时间间隔不超过一次溢出 + * + * @todo 更好的方案是为dwt的时间更新单独设置一个任务? + * 不过,使用dwt的初衷是定时不被中断/任务等因素影响,因此该实现仍然有其存在的意义 + * + */ +static void DWT_CNT_Update(void) +{ + static volatile uint8_t bit_locker = 0; + if (!bit_locker) + { + bit_locker = 1; + volatile uint32_t cnt_now = DWT->CYCCNT; + if (cnt_now < CYCCNT_LAST) + CYCCNT_RountCount++; + + CYCCNT_LAST = DWT->CYCCNT; + bit_locker = 0; + } +} + +void DWT_Init(uint32_t CPU_Freq_mHz) +{ + /* 使能DWT外设 */ + CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; + + /* DWT CYCCNT寄存器计数清0 */ + DWT->CYCCNT = (uint32_t)0u; + + /* 使能Cortex-M DWT CYCCNT寄存器 */ + DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; + + CPU_FREQ_Hz = CPU_Freq_mHz * 1000000; + CPU_FREQ_Hz_ms = CPU_FREQ_Hz / 1000; + CPU_FREQ_Hz_us = CPU_FREQ_Hz / 1000000; + CYCCNT_RountCount = 0; + + DWT_CNT_Update(); +} + +float DWT_GetDeltaT(uint32_t *cnt_last) +{ + volatile uint32_t cnt_now = DWT->CYCCNT; + float dt = ((uint32_t)(cnt_now - *cnt_last)) / ((float)(CPU_FREQ_Hz)); + *cnt_last = cnt_now; + + DWT_CNT_Update(); + + return dt; +} + +double DWT_GetDeltaT64(uint32_t *cnt_last) +{ + volatile uint32_t cnt_now = DWT->CYCCNT; + double dt = ((uint32_t)(cnt_now - *cnt_last)) / ((double)(CPU_FREQ_Hz)); + *cnt_last = cnt_now; + + DWT_CNT_Update(); + + return dt; +} + +void DWT_SysTimeUpdate(void) +{ + volatile uint32_t cnt_now = DWT->CYCCNT; + static uint64_t CNT_TEMP1, CNT_TEMP2, CNT_TEMP3; + + DWT_CNT_Update(); + + CYCCNT64 = (uint64_t)CYCCNT_RountCount * (uint64_t)UINT32_MAX + (uint64_t)cnt_now; + CNT_TEMP1 = CYCCNT64 / CPU_FREQ_Hz; + CNT_TEMP2 = CYCCNT64 - CNT_TEMP1 * CPU_FREQ_Hz; + SysTime.s = CNT_TEMP1; + SysTime.ms = CNT_TEMP2 / CPU_FREQ_Hz_ms; + CNT_TEMP3 = CNT_TEMP2 - SysTime.ms * CPU_FREQ_Hz_ms; + SysTime.us = CNT_TEMP3 / CPU_FREQ_Hz_us; +} + +float DWT_GetTimeline_s(void) +{ + DWT_SysTimeUpdate(); + + float DWT_Timelinef32 = SysTime.s + SysTime.ms * 0.001f + SysTime.us * 0.000001f; + + return DWT_Timelinef32; +} + +float DWT_GetTimeline_ms(void) +{ + DWT_SysTimeUpdate(); + + float DWT_Timelinef32 = SysTime.s * 1000 + SysTime.ms + SysTime.us * 0.001f; + + return DWT_Timelinef32; +} + +uint64_t DWT_GetTimeline_us(void) +{ + DWT_SysTimeUpdate(); + + uint64_t DWT_Timelinef32 = SysTime.s * 1000000 + SysTime.ms * 1000 + SysTime.us; + + return DWT_Timelinef32; +} + +void DWT_Delay(float Delay) +{ + uint32_t tickstart = DWT->CYCCNT; + float wait = Delay; + + while ((DWT->CYCCNT - tickstart) < wait * (float)CPU_FREQ_Hz) + ; +} diff --git a/bsp/dwt/bsp_dwt.h b/bsp/dwt/bsp_dwt.h new file mode 100644 index 0000000..b1a223d --- /dev/null +++ b/bsp/dwt/bsp_dwt.h @@ -0,0 +1,101 @@ +/** + ****************************************************************************** + * @file bsp_dwt.h + * @author Wang Hongxi + * @author modified by NeoZng + * @version V1.2.0 + * @date 2022/3/8 + * @brief + ****************************************************************************** + * @attention + * + ****************************************************************************** + */ +#ifndef _BSP_DWT_H +#define _BSP_DWT_H + +#include "main.h" +#include "stdint.h" +#include "bsp_log.h" + +typedef struct +{ + uint32_t s; + uint16_t ms; + uint16_t us; +} DWT_Time_t; + +/** + * @brief 该宏用于计算代码段执行时间,单位为秒/s,返回值为float类型 + * 首先需要创建一个float类型的变量,用于存储时间间隔 + * 计算得到的时间间隔同时还会通过RTT打印到日志终端,你也可以将你的dt变量添加到查看 + */ +#define TIME_ELAPSE(dt, code) \ + do \ + { \ + float tstart = DWT_GetTimeline_s(); \ + code; \ + dt = DWT_GetTimeline_s() - tstart; \ + LOGINFO("[DWT] " #dt " = %f s\r\n", dt); \ + } while (0) + +/** + * @brief 初始化DWT,传入参数为CPU频率,单位MHz + * + * @param CPU_Freq_mHz c板为168MHz,A板为180MHz + */ +void DWT_Init(uint32_t CPU_Freq_mHz); + +/** + * @brief 获取两次调用之间的时间间隔,单位为秒/s + * + * @param cnt_last 上一次调用的时间戳 + * @return float 时间间隔,单位为秒/s + */ +float DWT_GetDeltaT(uint32_t *cnt_last); + +/** + * @brief 获取两次调用之间的时间间隔,单位为秒/s,高精度 + * + * @param cnt_last 上一次调用的时间戳 + * @return double 时间间隔,单位为秒/s + */ +double DWT_GetDeltaT64(uint32_t *cnt_last); + +/** + * @brief 获取当前时间,单位为秒/s,即初始化后的时间 + * + * @return float 时间轴 + */ +float DWT_GetTimeline_s(void); + +/** + * @brief 获取当前时间,单位为毫秒/ms,即初始化后的时间 + * + * @return float + */ +float DWT_GetTimeline_ms(void); + +/** + * @brief 获取当前时间,单位为微秒/us,即初始化后的时间 + * + * @return uint64_t + */ +uint64_t DWT_GetTimeline_us(void); + +/** + * @brief DWT延时函数,单位为秒/s + * @attention 该函数不受中断是否开启的影响,可以在临界区和关闭中断时使用 + * @note 禁止在__disable_irq()和__enable_irq()之间使用HAL_Delay()函数,应使用本函数 + * + * @param Delay 延时时间,单位为秒/s + */ +void DWT_Delay(float Delay); + +/** + * @brief DWT更新时间轴函数,会被三个timeline函数调用 + * @attention 如果长时间不调用timeline函数,则需要手动调用该函数更新时间轴,否则CYCCNT溢出后定时和时间轴不准确 + */ +void DWT_SysTimeUpdate(void); + +#endif /* BSP_DWT_H_ */ diff --git a/bsp/dwt/bsp_dwt.md b/bsp/dwt/bsp_dwt.md new file mode 100644 index 0000000..921245f --- /dev/null +++ b/bsp/dwt/bsp_dwt.md @@ -0,0 +1,54 @@ +# bsp_dwt + +DWT是stm32内部的一个"隐藏资源",他的用途是给下载器提供准确的定时,从而为调试信息加上时间戳.并在固定的时间间隔将调试数据发送到你的xxlink上. + +## 常用功能 + +### 计算两次进入同一个函数的时间间隔 + +```c +static uint32_t cnt; +float deltaT; + +deltaT=DWT_GetDeltaT(&cnt); +``` + +### 计算执行某部分代码的耗时 + +```c +float start,end; +start=DWT_DetTimeline_ms(); + +// some proc to go... +for(uint8_t i=0;i<10;i++) + foo(); + +end = DWT_DetTimeline_ms()-start; +``` + +我们还提供了一个宏用于调试计时: + +```c +#define TIME_ELAPSE(dt, code) \ + do \ + { \ + float tstart = DWT_GetTimeline_s(); \ + code; \ + dt = DWT_GetTimeline_s() - tstart; \ + LOGINFO("[DWT] " #dt " = %f s\r\n", dt); \ + } while (0) + +``` + +传入一个float类型的变量,并将你要执行的代码写入第二个参数: + +```c + static float my_func_dt; + TIME_ELAPSE(my_func_dt, + Function1(vara); + Function2(some, var); + Function3(your,param); + // something more + ); + // my_func_dt can be used for other purpose then; +``` diff --git a/bsp/flash/bsp_flash.c b/bsp/flash/bsp_flash.c new file mode 100644 index 0000000..dfdf9a9 --- /dev/null +++ b/bsp/flash/bsp_flash.c @@ -0,0 +1,289 @@ +#include "bsp_flash.h" +#include "main.h" +#include "string.h" + +static uint32_t ger_sector(uint32_t address); + +/** + * @brief erase flash + * @param[in] address: flash address + * @param[in] len: page num + * @retval none + */ +/** + * @brief ²Á³ýflash + * @param[in] address: flash µØַ + * @param[in] len: ҳÊýÁ¿ + * @retval none + */ +void flash_erase_address(uint32_t address, uint16_t len) +{ + FLASH_EraseInitTypeDef flash_erase; + uint32_t error; + + flash_erase.Sector = ger_sector(address); + flash_erase.TypeErase = FLASH_TYPEERASE_SECTORS; + flash_erase.VoltageRange = FLASH_VOLTAGE_RANGE_3; + flash_erase.NbSectors = len; + + HAL_FLASH_Unlock(); + HAL_FLASHEx_Erase(&flash_erase, &error); + HAL_FLASH_Lock(); +} + +/** + * @brief write data to one page of flash + * @param[in] start_address: flash address + * @param[in] buf: data point + * @param[in] len: data num + * @retval success 0, fail -1 + */ +/** + * @brief ÍùһҳflashдÊý¾Ý + * @param[in] start_address: flash µØַ + * @param[in] buf: Êý¾ÝָÕë + * @param[in] len: Êý¾ݳ¤¶È + * @retval success 0, fail -1 + */ +int8_t flash_write_single_address(uint32_t start_address, uint32_t *buf, uint32_t len) +{ + static uint32_t uw_address; + static uint32_t end_address; + static uint32_t *data_buf; + static uint32_t data_len; + + HAL_FLASH_Unlock(); + + uw_address = start_address; + end_address = get_next_flash_address(start_address); + data_buf = buf; + data_len = 0; + + while (uw_address <= end_address) + { + + if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,uw_address, *data_buf) == HAL_OK) + { + uw_address += 4; + data_buf++; + data_len++; + if (data_len == len) + { + break; + } + } + else + { + HAL_FLASH_Lock(); + return -1; + } + } + + HAL_FLASH_Lock(); + return 0; +} + +/** + * @brief write data to some pages of flash + * @param[in] start_address: flash start address + * @param[in] end_address: flash end address + * @param[in] buf: data point + * @param[in] len: data num + * @retval success 0, fail -1 + */ +/** + * @brief Íù¼¸ҳflashдÊý¾Ý + * @param[in] start_address: flash ¿ªʼµØַ + * @param[in] end_address: flash ½áÊøµØַ + * @param[in] buf: Êý¾ÝָÕë + * @param[in] len: Êý¾ݳ¤¶È + * @retval success 0, fail -1 + */ +int8_t flash_write_muli_address(uint32_t start_address, uint32_t end_address, uint32_t *buf, uint32_t len) +{ + uint32_t uw_address = 0; + uint32_t *data_buf; + uint32_t data_len; + + HAL_FLASH_Unlock(); + + uw_address = start_address; + data_buf = buf; + data_len = 0; + while (uw_address <= end_address) + { + if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD,uw_address, *data_buf) == HAL_OK) + { + uw_address += 4; + data_buf++; + data_len++; + if (data_len == len) + { + break; + } + } + else + { + HAL_FLASH_Lock(); + return -1; + } + } + + HAL_FLASH_Lock(); + return 0; +} + + +/** + * @brief read data for flash + * @param[in] address: flash address + * @param[out] buf: data point + * @param[in] len: data num + * @retval none + */ +/** + * @brief ´Óflash¶ÁÊý¾Ý + * @param[in] start_address: flash µØַ + * @param[out] buf: Êý¾ÝָÕë + * @param[in] len: Êý¾ݳ¤¶È + * @retval none + */ +void flash_read(uint32_t address, uint32_t *buf, uint32_t len) +{ + memcpy(buf, (void*)address, len *4); +} + + +/** + * @brief get the sector number of flash + * @param[in] address: flash address + * @retval sector number + */ +/** + * @brief »ñȡflashµÄsectorºÅ + * @param[in] address: flash µØַ + * @retval sectorºÅ + */ +static uint32_t ger_sector(uint32_t address) +{ + uint32_t sector = 0; + if ((address < ADDR_FLASH_SECTOR_1) && (address >= ADDR_FLASH_SECTOR_0)) + { + sector = FLASH_SECTOR_0; + } + else if ((address < ADDR_FLASH_SECTOR_2) && (address >= ADDR_FLASH_SECTOR_1)) + { + sector = FLASH_SECTOR_1; + } + else if ((address < ADDR_FLASH_SECTOR_3) && (address >= ADDR_FLASH_SECTOR_2)) + { + sector = FLASH_SECTOR_2; + } + else if ((address < ADDR_FLASH_SECTOR_4) && (address >= ADDR_FLASH_SECTOR_3)) + { + sector = FLASH_SECTOR_3; + } + else if ((address < ADDR_FLASH_SECTOR_5) && (address >= ADDR_FLASH_SECTOR_4)) + { + sector = FLASH_SECTOR_4; + } + else if ((address < ADDR_FLASH_SECTOR_6) && (address >= ADDR_FLASH_SECTOR_5)) + { + sector = FLASH_SECTOR_5; + } + else if ((address < ADDR_FLASH_SECTOR_7) && (address >= ADDR_FLASH_SECTOR_6)) + { + sector = FLASH_SECTOR_6; + } + else if ((address < ADDR_FLASH_SECTOR_8) && (address >= ADDR_FLASH_SECTOR_7)) + { + sector = FLASH_SECTOR_7; + } + else if ((address < ADDR_FLASH_SECTOR_9) && (address >= ADDR_FLASH_SECTOR_8)) + { + sector = FLASH_SECTOR_8; + } + else if ((address < ADDR_FLASH_SECTOR_10) && (address >= ADDR_FLASH_SECTOR_9)) + { + sector = FLASH_SECTOR_9; + } + else if ((address < ADDR_FLASH_SECTOR_11) && (address >= ADDR_FLASH_SECTOR_10)) + { + sector = FLASH_SECTOR_10; + } + else if ((address < ADDR_FLASH_SECTOR_12) && (address >= ADDR_FLASH_SECTOR_11)) + { + sector = FLASH_SECTOR_11; + } + else + { + sector = FLASH_SECTOR_11; + } + + return sector; +} + +/** + * @brief get the next page flash address + * @param[in] address: flash address + * @retval next page flash address + */ +/** + * @brief »ñȡÏÂһҳflashµØַ + * @param[in] address: flash µØַ + * @retval ÏÂһҳflashµØַ + */ +uint32_t get_next_flash_address(uint32_t address) +{ + uint32_t sector = 0; + + if ((address < ADDR_FLASH_SECTOR_1) && (address >= ADDR_FLASH_SECTOR_0)) + { + sector = ADDR_FLASH_SECTOR_1; + } + else if ((address < ADDR_FLASH_SECTOR_2) && (address >= ADDR_FLASH_SECTOR_1)) + { + sector = ADDR_FLASH_SECTOR_2; + } + else if ((address < ADDR_FLASH_SECTOR_3) && (address >= ADDR_FLASH_SECTOR_2)) + { + sector = ADDR_FLASH_SECTOR_3; + } + else if ((address < ADDR_FLASH_SECTOR_4) && (address >= ADDR_FLASH_SECTOR_3)) + { + sector = ADDR_FLASH_SECTOR_4; + } + else if ((address < ADDR_FLASH_SECTOR_5) && (address >= ADDR_FLASH_SECTOR_4)) + { + sector = ADDR_FLASH_SECTOR_5; + } + else if ((address < ADDR_FLASH_SECTOR_6) && (address >= ADDR_FLASH_SECTOR_5)) + { + sector = ADDR_FLASH_SECTOR_6; + } + else if ((address < ADDR_FLASH_SECTOR_7) && (address >= ADDR_FLASH_SECTOR_6)) + { + sector = ADDR_FLASH_SECTOR_7; + } + else if ((address < ADDR_FLASH_SECTOR_8) && (address >= ADDR_FLASH_SECTOR_7)) + { + sector = ADDR_FLASH_SECTOR_8; + } + else if ((address < ADDR_FLASH_SECTOR_9) && (address >= ADDR_FLASH_SECTOR_8)) + { + sector = ADDR_FLASH_SECTOR_9; + } + else if ((address < ADDR_FLASH_SECTOR_10) && (address >= ADDR_FLASH_SECTOR_9)) + { + sector = ADDR_FLASH_SECTOR_10; + } + else if ((address < ADDR_FLASH_SECTOR_11) && (address >= ADDR_FLASH_SECTOR_10)) + { + sector = ADDR_FLASH_SECTOR_11; + } + else /*(address < FLASH_END_ADDR) && (address >= ADDR_FLASH_SECTOR_23))*/ + { + sector = FLASH_END_ADDR; + } + return sector; +} diff --git a/bsp/flash/bsp_flash.h b/bsp/flash/bsp_flash.h new file mode 100644 index 0000000..ed4a83f --- /dev/null +++ b/bsp/flash/bsp_flash.h @@ -0,0 +1,80 @@ +#ifndef _BSP_FLASH_H +#define _BSP_FLASH_H +#include "main.h" + +/* Base address of the Flash sectors */ +#define ADDR_FLASH_SECTOR_0 ((uint32_t)0x08000000) /* Base address of Sector 0, 16 Kbytes */ +#define ADDR_FLASH_SECTOR_1 ((uint32_t)0x08004000) /* Base address of Sector 1, 16 Kbytes */ +#define ADDR_FLASH_SECTOR_2 ((uint32_t)0x08008000) /* Base address of Sector 2, 16 Kbytes */ +#define ADDR_FLASH_SECTOR_3 ((uint32_t)0x0800C000) /* Base address of Sector 3, 16 Kbytes */ +#define ADDR_FLASH_SECTOR_4 ((uint32_t)0x08010000) /* Base address of Sector 4, 64 Kbytes */ +#define ADDR_FLASH_SECTOR_5 ((uint32_t)0x08020000) /* Base address of Sector 5, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_6 ((uint32_t)0x08040000) /* Base address of Sector 6, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_7 ((uint32_t)0x08060000) /* Base address of Sector 7, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_8 ((uint32_t)0x08080000) /* Base address of Sector 8, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_9 ((uint32_t)0x080A0000) /* Base address of Sector 9, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_10 ((uint32_t)0x080C0000) /* Base address of Sector 10, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_11 ((uint32_t)0x080E0000) /* Base address of Sector 11, 128 Kbytes */ + +#define FLASH_END_ADDR ((uint32_t)0x08100000) /* Base address of Sector 23, 128 Kbytes */ + + +#define ADDR_FLASH_SECTOR_12 ((uint32_t)0x08100000) /* Base address of Sector 12, 16 Kbytes */ +#define ADDR_FLASH_SECTOR_13 ((uint32_t)0x08104000) /* Base address of Sector 13, 16 Kbytes */ +#define ADDR_FLASH_SECTOR_14 ((uint32_t)0x08108000) /* Base address of Sector 14, 16 Kbytes */ +#define ADDR_FLASH_SECTOR_15 ((uint32_t)0x0810C000) /* Base address of Sector 15, 16 Kbytes */ +#define ADDR_FLASH_SECTOR_16 ((uint32_t)0x08110000) /* Base address of Sector 16, 64 Kbytes */ +#define ADDR_FLASH_SECTOR_17 ((uint32_t)0x08120000) /* Base address of Sector 17, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_18 ((uint32_t)0x08140000) /* Base address of Sector 18, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_19 ((uint32_t)0x08160000) /* Base address of Sector 19, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_20 ((uint32_t)0x08180000) /* Base address of Sector 20, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_21 ((uint32_t)0x081A0000) /* Base address of Sector 21, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_22 ((uint32_t)0x081C0000) /* Base address of Sector 22, 128 Kbytes */ +#define ADDR_FLASH_SECTOR_23 ((uint32_t)0x081E0000) /* Base address of Sector 23, 128 Kbytes */ + + + +/** + * @brief erase flash + * @param[in] address: flash address + * @param[in] len: page num + * @retval none + */ +void flash_erase_address(uint32_t address, uint16_t len); + +/** + * @brief write data to one page of flash + * @param[in] start_address: flash address + * @param[in] buf: data point + * @param[in] len: data num + * @retval success 0, fail -1 + */ +int8_t flash_write_single_address(uint32_t start_address, uint32_t *buf, uint32_t len); + + +/** + * @brief write data to some pages of flash + * @param[in] start_address: flash start address + * @param[in] end_address: flash end address + * @param[in] buf: data point + * @param[in] len: data num + * @retval success 0, fail -1 + */ +int8_t flash_write_muli_address(uint32_t start_address, uint32_t end_address, uint32_t *buf, uint32_t len); + +/** + * @brief read data for flash + * @param[in] address: flash address + * @param[out] buf: data point + * @param[in] len: data num + * @retval none + */ +void flash_read(uint32_t address, uint32_t *buf, uint32_t len); + +/** + * @brief get the next page flash address + * @param[in] address: flash address + * @retval next page flash address + */ +uint32_t get_next_flash_address(uint32_t address); +#endif diff --git a/bsp/flash/bsp_flash.md b/bsp/flash/bsp_flash.md new file mode 100644 index 0000000..e69de29 diff --git a/bsp/gpio/bsp_gpio.c b/bsp/gpio/bsp_gpio.c new file mode 100644 index 0000000..970b81f --- /dev/null +++ b/bsp/gpio/bsp_gpio.c @@ -0,0 +1,66 @@ +#include "bsp_gpio.h" +#include "memory.h" +#include "stdlib.h" + +static uint8_t idx; +static GPIOInstance *gpio_instance[GPIO_MX_DEVICE_NUM] = {NULL}; + +/** + * @brief EXTI中断回调函数,根据GPIO_Pin找到对应的GPIOInstance,并调用模块回调函数(如果有) + * @note 如何判断具体是哪一个GPIO的引脚连接到这个EXTI中断线上? + * 一个EXTI中断线只能连接一个GPIO引脚,因此可以通过GPIO_Pin来判断,PinX对应EXTIX + * 一个Pin号只会对应一个EXTI,详情见gpio.md + * @param GPIO_Pin 发生中断的GPIO_Pin + */ +void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) +{ + // 如有必要,可以根据pinstate和HAL_GPIO_ReadPin来判断是上升沿还是下降沿/rise&fall等 + GPIOInstance *gpio; + for (size_t i = 0; i < idx; i++) + { + gpio = gpio_instance[i]; + if (gpio->GPIO_Pin == GPIO_Pin && gpio->gpio_model_callback != NULL) + { + gpio->gpio_model_callback(gpio); + return; + } + } +} + +GPIOInstance *GPIORegister(GPIO_Init_Config_s *GPIO_config) +{ + GPIOInstance *ins = (GPIOInstance *)malloc(sizeof(GPIOInstance)); + memset(ins, 0, sizeof(GPIOInstance)); + + ins->GPIOx = GPIO_config->GPIOx; + ins->GPIO_Pin = GPIO_config->GPIO_Pin; + ins->pin_state = GPIO_config->pin_state; + ins->exti_mode = GPIO_config->exti_mode; + ins->id = GPIO_config->id; + ins->gpio_model_callback = GPIO_config->gpio_model_callback; + gpio_instance[idx++] = ins; + return ins; +} + +// ----------------- GPIO API ----------------- +// 都是对HAL的形式上的封装,后续考虑增加GPIO state变量,可以直接读取state + +void GPIOToggel(GPIOInstance *_instance) +{ + HAL_GPIO_TogglePin(_instance->GPIOx, _instance->GPIO_Pin); +} + +void GPIOSet(GPIOInstance *_instance) +{ + HAL_GPIO_WritePin(_instance->GPIOx, _instance->GPIO_Pin, GPIO_PIN_SET); +} + +void GPIOReset(GPIOInstance *_instance) +{ + HAL_GPIO_WritePin(_instance->GPIOx, _instance->GPIO_Pin, GPIO_PIN_RESET); +} + +GPIO_PinState GPIORead(GPIOInstance *_instance) +{ + return HAL_GPIO_ReadPin(_instance->GPIOx, _instance->GPIO_Pin); +} diff --git a/bsp/gpio/bsp_gpio.h b/bsp/gpio/bsp_gpio.h new file mode 100644 index 0000000..2eab198 --- /dev/null +++ b/bsp/gpio/bsp_gpio.h @@ -0,0 +1,87 @@ +#include "gpio.h" +#include "stdint.h" + +#define GPIO_MX_DEVICE_NUM 10 + +/** + * @brief 用于判断中断来源,注意和CUBEMX中配置一致 + * + */ +typedef enum +{ + GPIO_EXTI_MODE_RISING, + GPIO_EXTI_MODE_FALLING, + GPIO_EXTI_MODE_RISING_FALLING, + GPIO_EXTI_MODE_NONE, +} GPIO_EXTI_MODE_e; + +/** + * @brief GPIO实例结构体定义 + * + */ +typedef struct tmpgpio +{ + GPIO_TypeDef *GPIOx; // GPIOA,GPIOB,GPIOC... + GPIO_PinState pin_state; // 引脚状态,Set,Reset;not frequently used + GPIO_EXTI_MODE_e exti_mode; // 外部中断模式 not frequently used + uint16_t GPIO_Pin; // 引脚号, + // 这些引脚是stm32f4xx_hal_gpio.h中定义的宏!!! 一定要注意 + // 随便取个名字当临时声明 + void (*gpio_model_callback)(struct tmpgpio *); // exti中断回调函数 + void *id; // 区分不同的GPIO实例 + +} GPIOInstance; + +/** + * @brief GPIO初始化配置结构体定义 + * + */ +typedef struct +{ + GPIO_TypeDef *GPIOx; // GPIOA,GPIOB,GPIOC... + GPIO_PinState pin_state; // 引脚状态,Set,Reset not frequently used + GPIO_EXTI_MODE_e exti_mode; // 外部中断模式 not frequently used + uint16_t GPIO_Pin; // 引脚号,@note 这里的引脚号是GPIO_PIN_0,GPIO_PIN_1... + // 这些引脚是stm32f4xx_hal_gpio.h中定义的宏!!! 一定要注意 + + void (*gpio_model_callback)(GPIOInstance *); // exti中断回调函数 + void *id; // 区分不同的GPIO实例 + +} GPIO_Init_Config_s; + +/** + * @brief 注册GPIO实例 + * + * @param GPIO_config + * @return GPIOInstance* + */ +GPIOInstance *GPIORegister(GPIO_Init_Config_s *GPIO_config); + +/** + * @brief GPIO API,切换GPIO电平 + * + * @param _instance + */ +void GPIOToggel(GPIOInstance *_instance); + +/** + * @brief 设置GPIO电平 + * + * @param _instance + */ +void GPIOSet(GPIOInstance *_instance); + +/** + * @brief 复位GPIO电平 + * + * @param _instance + */ +void GPIOReset(GPIOInstance *_instance); + +/** + * @brief 读取GPIO电平 + * + * @param _instance + * @return GPIO_PinState + */ +GPIO_PinState GPIORead(GPIOInstance *_instance); \ No newline at end of file diff --git a/bsp/gpio/bsp_gpio.md b/bsp/gpio/bsp_gpio.md new file mode 100644 index 0000000..d35dfba --- /dev/null +++ b/bsp/gpio/bsp_gpio.md @@ -0,0 +1,23 @@ + +可以作为io接口,也可以处理外部中断. + + + + + +使用示例 + +```c +//在app层只需要设置前三个,callback由module自动设置 + +GPIO_Init_Config_s gpio_init = { + .exti_mode = GPIO_EXTI_MODE_FALLING, // 注意和CUBEMX的配置一致 + .GPIO_Pin = GPIO_PIN_6, // GPIO引脚 + .GPIOx = GPIOG, // GPIO外设 + .gpio_model_callback = NULL, // EXTI回调函数 +}, + +GPIOInstance* test_example = GPIORegister(&gpio_init); +GPIOSet(test_example); +// GPIOxxx(test_exmaple, ...); +``` diff --git a/bsp/iic/bsp_iic.c b/bsp/iic/bsp_iic.c new file mode 100644 index 0000000..26c34f5 --- /dev/null +++ b/bsp/iic/bsp_iic.c @@ -0,0 +1,151 @@ +#include "bsp_iic.h" +#include "memory.h" +#include "stdlib.h" + +static uint8_t idx = 0; // 配合中断以及初始化 +static IICInstance *iic_instance[IIC_DEVICE_CNT] = {NULL}; + +IICInstance *IICRegister(IIC_Init_Config_s *conf) +{ + if (idx >= MX_IIC_SLAVE_CNT) // 超过最大实例数 + while (1) // 酌情增加允许的实例上限,也有可能是内存泄漏 + ; + // 申请到的空间未必是0, 所以需要手动初始化 + IICInstance *instance = (IICInstance *)malloc(sizeof(IICInstance)); + instance = (IICInstance *)malloc(sizeof(IICInstance)); + memset(instance, 0, sizeof(IICInstance)); + + instance->dev_address = conf->dev_address << 1; // 地址左移一位,最低位为读写位 + instance->callback = conf->callback; + instance->work_mode = conf->work_mode; + instance->handle = conf->handle; + instance->id = conf->id; + + iic_instance[idx++] = instance; + return instance; +} + +void IICSetMode(IICInstance *iic, IIC_Work_Mode_e mode) +{ // HAL自带重入保护,不需要手动终止或等待传输完成 + if (iic->work_mode != mode) + { + iic->work_mode = mode; // 如果不同才需要修改 + } +} + +void IICTransmit(IICInstance *iic, uint8_t *data, uint16_t size, IIC_Seq_Mode_e seq_mode) +{ + if (seq_mode != IIC_SEQ_RELEASE && seq_mode != IIC_SEQ_HOLDON) + while (1) + ; // 未知传输模式, 程序停止 + + // 根据不同的工作模式进行不同的传输 + switch (iic->work_mode) + { + case IIC_BLOCK_MODE: + if (seq_mode != IIC_SEQ_RELEASE) + while (1) + ; // 阻塞模式下不支持HOLD ON模式!!!只能传输完成后立刻释放总线 + HAL_I2C_Master_Transmit(iic->handle, iic->dev_address, data, size, 100); // 默认超时时间100ms + break; + case IIC_IT_MODE: + if (seq_mode == IIC_SEQ_RELEASE) + HAL_I2C_Master_Seq_Transmit_IT(iic->handle, iic->dev_address, data, size, I2C_OTHER_AND_LAST_FRAME); + else if (seq_mode == IIC_SEQ_HOLDON) + HAL_I2C_Master_Seq_Transmit_IT(iic->handle, iic->dev_address, data, size, I2C_OTHER_FRAME); + break; + case IIC_DMA_MODE: + if (seq_mode == IIC_SEQ_RELEASE) + HAL_I2C_Master_Seq_Transmit_DMA(iic->handle, iic->dev_address, data, size, I2C_OTHER_AND_LAST_FRAME); + else if (seq_mode == IIC_SEQ_HOLDON) + HAL_I2C_Master_Seq_Transmit_DMA(iic->handle, iic->dev_address, data, size, I2C_OTHER_FRAME); + break; + default: + while (1) + ; // 未知传输模式, 程序停止 + } +} + +void IICReceive(IICInstance *iic, uint8_t *data, uint16_t size, IIC_Seq_Mode_e seq_mode) +{ + if (seq_mode != IIC_SEQ_RELEASE && seq_mode != IIC_SEQ_HOLDON) + while (1) + ; // 未知传输模式, 程序停止,请检查指针越界 + + // 初始化接收缓冲区地址以及接受长度, 用于中断回调函数 + iic->rx_buffer = data; + iic->rx_len = size; + + switch (iic->work_mode) + { + case IIC_BLOCK_MODE: + if (seq_mode != IIC_SEQ_RELEASE) + while (1) + ; // 阻塞模式下不支持HOLD ON模式!!! + HAL_I2C_Master_Receive(iic->handle, iic->dev_address, data, size, 100); // 默认超时时间100ms + break; + case IIC_IT_MODE: + if (seq_mode == IIC_SEQ_RELEASE) + HAL_I2C_Master_Seq_Receive_IT(iic->handle, iic->dev_address, data, size, I2C_OTHER_AND_LAST_FRAME); + else if (seq_mode == IIC_SEQ_HOLDON) + HAL_I2C_Master_Seq_Receive_IT(iic->handle, iic->dev_address, data, size, I2C_OTHER_FRAME); + break; + case IIC_DMA_MODE: + if (seq_mode == IIC_SEQ_RELEASE) + HAL_I2C_Master_Seq_Receive_DMA(iic->handle, iic->dev_address, data, size, I2C_OTHER_AND_LAST_FRAME); + else if (seq_mode == IIC_SEQ_HOLDON) + HAL_I2C_Master_Seq_Receive_DMA(iic->handle, iic->dev_address, data, size, I2C_OTHER_FRAME); + break; + default: + while (1) + ; // 未知传输模式, 程序停止 + break; + } +} + +void IICAccessMem(IICInstance *iic, uint16_t mem_addr, uint8_t *data, uint16_t size, IIC_Mem_Mode_e mem_mode, uint8_t mem8bit_flag) +{ + uint16_t bit_flag = mem8bit_flag ? I2C_MEMADD_SIZE_8BIT : I2C_MEMADD_SIZE_16BIT; + if (mem_mode == IIC_WRITE_MEM) + { + HAL_I2C_Mem_Write(iic->handle, iic->dev_address, mem_addr, bit_flag, data, size, 100); + } + else if (mem_mode == IIC_READ_MEM) + { + HAL_I2C_Mem_Read(iic->handle, iic->dev_address, mem_addr, bit_flag, data, size, 100); + } + else + { + while (1) + ; // 未知模式, 程序停止 + } +} + +/** + * @brief IIC接收完成回调函数 + * + * @param hi2c handle + */ +void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + // 如果是当前i2c硬件发出的complete,且dev_address和之前发起接收的地址相同,同时回到函数不为空, 则调用回调函数 + for (uint8_t i = 0; i < idx; i++) + { + if (iic_instance[i]->handle == hi2c && hi2c->Devaddress == iic_instance[i]->dev_address) + { + if (iic_instance[i]->callback != NULL) // 回调函数不为空 + iic_instance[i]->callback(iic_instance[i]); + return; + } + } +} + +/** + * @brief 内存访问回调函数,仅做形式上的封装,仍然使用HAL_I2C_MasterRxCpltCallback + * + * @param hi2c handle + */ +void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + HAL_I2C_MasterRxCpltCallback(hi2c); +} diff --git a/bsp/iic/bsp_iic.h b/bsp/iic/bsp_iic.h new file mode 100644 index 0000000..507d23f --- /dev/null +++ b/bsp/iic/bsp_iic.h @@ -0,0 +1,106 @@ +#include "i2c.h" +#include "stdint.h" + +#define IIC_DEVICE_CNT 2 // C板引出了I2C2和I2C3 +#define MX_IIC_SLAVE_CNT 8 // 最大从机数目,根据需要修改 + +/* i2c 工作模式枚举 */ +typedef enum +{ + // 基本工作模式 + IIC_BLOCK_MODE = 0, // 阻塞模式 + IIC_IT_MODE, // 中断模式 + IIC_DMA_MODE, // DMA模式 + +} IIC_Work_Mode_e; + +/* I2C MEM工作模式枚举,这两种方法都是阻塞 */ +typedef enum +{ + IIC_READ_MEM = 0, // 读取从机内部的寄存器or内存 + IIC_WRITE_MEM, // 写入从机内部的寄存器or内存 +} IIC_Mem_Mode_e; + +/* Seq传输工作模式枚举,注意HOLD_ON要在IT或DMA下使用 */ +// 必须以IIC_RELEASE为最后一次传输,否则会导致总线占有权无法释放 +typedef enum +{ + IIC_SEQ_RELEASE, // 完成传输后释放总线占有权,这是默认的传输方式 + IIC_SEQ_HOLDON = 0, // 保持总线占有权不释放,只支持IT和DMA模式 +} IIC_Seq_Mode_e; + +/* i2c实例 */ +typedef struct iic_temp_s +{ + I2C_HandleTypeDef *handle; // i2c handle + uint8_t dev_address; // 暂时只支持7位地址(还有一位是读写位) + + IIC_Work_Mode_e work_mode; // 工作模式 + uint8_t *rx_buffer; // 接收缓冲区指针 + uint8_t rx_len; // 接收长度 + void (*callback)(struct iic_temp_s *); // 接收完成后的回调函数 + + void *id; // 用于标识i2c instance +} IICInstance; + +/* I2C 初始化结构体配置 */ +typedef struct +{ + I2C_HandleTypeDef *handle; // i2c handle + uint8_t dev_address; // 暂时只支持7位地址(还有一位是读写位),注意不需要左移 + IIC_Work_Mode_e work_mode; // 工作模式 + void (*callback)(IICInstance *); // 接收完成后的回调函数 + void *id; // 用于标识i2c instance +} IIC_Init_Config_s; + +/** + * @brief IIC初始化 + * + * @param conf 初始化配置 + * @return IICInstance* + */ +IICInstance *IICRegister(IIC_Init_Config_s *conf); + +/** + * @brief IIC设置工作模式 + * + * @param iic 要设置的iic实例 + * @param mode 工作模式 + */ +void IICSetMode(IICInstance *iic, IIC_Work_Mode_e mode); + +/** + * @brief IIC发送数据 + * + * @param iic iic实例 + * @param data 待发送的数据首地址指针 + * @param size 发送长度 + * @param mode 序列传输模式 + * @note 注意,如果发送结构体,那么该结构体在声明时务必使用#pragma pack(1)进行对齐,并在声明结束后使用#pragma pack()恢复对齐 + * + */ +void IICTransmit(IICInstance *iic, uint8_t *data, uint16_t size, IIC_Seq_Mode_e mode); + +/** + * @brief IIC接收数据 + * + * @param iic iic实例 + * @param data 接收数据的首地址指针 + * @param size 接收长度 + * @param mode 序列传输模式 + * @note 注意,如果直接将接收数据memcpy到目标结构体或通过强制类型转换进行逐字节写入, + * 那么该结构体在声明时务必使用#pragma pack(1)进行对齐,并在声明结束后使用#pragma pack()恢复对齐 + */ +void IICReceive(IICInstance *iic, uint8_t *data, uint16_t size, IIC_Seq_Mode_e mode); + +/** + * @brief IIC读取从机寄存器(内存),只支持阻塞模式,超时默认为1ms + * + * @param iic iic实例 + * @param mem_addr 要读取的从机内存地址,目前只支持8位地址 + * @param data 要读取或写入的数据首地址指针 + * @param size 要读取或写入的数据长度 + * @param mode 写入或读取模式: IIC_READ_MEM or IIC_WRITE_MEM + * @param mem8bit_flag 从机内存地址是否为8位 + */ +void IICAccessMem(IICInstance *iic, uint16_t mem_addr, uint8_t *data, uint16_t size, IIC_Mem_Mode_e mode, uint8_t mem8bit_flag); diff --git a/bsp/iic/bsp_iic.md b/bsp/iic/bsp_iic.md new file mode 100644 index 0000000..57a7dcd --- /dev/null +++ b/bsp/iic/bsp_iic.md @@ -0,0 +1,19 @@ +# bsp iic + +> 预计增加模拟iic + +## 注意事项 + +使用时写入地址,不需要左移!!! + +cubemx未配置dma时请勿使用dma传输,其行为是未定义的。 + +## 总线机制详解 + +关于I2C的序列传输,Restart condition和总线仲裁,请看: + +https://blog.csdn.net/NeoZng/article/details/128496694 + +https://blog.csdn.net/NeoZng/article/details/128486366 + +使用序列通信则在单次通信后不会释放总线,继续占用直到调用传输函数时传入`IIC_RELEASE`参数. 这个功能只在一条总线上挂载多个主机的时候有用. diff --git a/bsp/log/bsp_log.c b/bsp/log/bsp_log.c new file mode 100644 index 0000000..da35f0d --- /dev/null +++ b/bsp/log/bsp_log.c @@ -0,0 +1,34 @@ +#include "bsp_log.h" + +#include "SEGGER_RTT.h" +#include "SEGGER_RTT_Conf.h" +#include+ + +void BSPLogInit() +{ + SEGGER_RTT_Init(); +} + +int PrintLog(const char *fmt, ...) +{ + va_list args; + va_start(args, fmt); + int n = SEGGER_RTT_vprintf(BUFFER_INDEX, fmt, &args); // 一次可以开启多个buffer(多个终端),我们只用一个 + va_end(args); + return n; +} + +void Float2Str(char *str, float va) +{ + int flag = va < 0; + int head = (int)va; + int point = (int)((va - head) * 1000); + head = abs(head); + point = abs(point); + if (flag) + sprintf(str, "-%d.%d", head, point); + else + sprintf(str, "%d.%d", head, point); +} + diff --git a/bsp/log/bsp_log.h b/bsp/log/bsp_log.h new file mode 100644 index 0000000..4d1a1a3 --- /dev/null +++ b/bsp/log/bsp_log.h @@ -0,0 +1,72 @@ +#ifndef _BSP_LOG_H +#define _BSP_LOG_H + +#include "SEGGER_RTT.h" +#include "SEGGER_RTT_Conf.h" +#include + +#define BUFFER_INDEX 0 + +/** + * @brief 日志系统初始化 + * + */ +void BSPLogInit(); + +/** + * @brief 日志功能原型,供下面的LOGI,LOGW,LOGE等使用 + * + */ +#define LOG_PROTO(type, color, format, ...) \ + SEGGER_RTT_printf(BUFFER_INDEX, " %s%s" format "\r\n%s", \ + color, \ + type, \ + ##__VA_ARGS__, \ + RTT_CTRL_RESET) + +/*----------------------------------------下面是日志输出的接口-------------------------------------------------*/ + +/* 清屏 */ +#define LOG_CLEAR() SEGGER_RTT_WriteString(0, " " RTT_CTRL_CLEAR) + +/* 无颜色日志输出 */ +#define LOG(format, ...) LOG_PROTO("", "", format, ##__VA_ARGS__) + +/** + * 有颜色格式日志输出,建议使用这些宏来输出日志 + * @attention 注意这些接口不支持浮点格式化输出,若有需要,请使用Float2Str()函数进行转换后再打印 + * @note 在release版本上车使用时,与makefile中添加的宏DISABLE_LOG_SYSTEM一起使用,可以关闭日志系统 + */ +#if DISABLE_LOG_SYSTEM +#define LOGINFO(format, ...) +#define LOGWARNING(format, ...) +#define LOGERROR(format, ...) +#else +// information level +#define LOGINFO(format, ...) LOG_PROTO("I:", RTT_CTRL_TEXT_BRIGHT_GREEN, format, ##__VA_ARGS__) +// warning level +#define LOGWARNING(format, ...) LOG_PROTO("W:", RTT_CTRL_TEXT_BRIGHT_YELLOW, format, ##__VA_ARGS__) +// error level +#define LOGERROR(format, ...) LOG_PROTO("E:", RTT_CTRL_TEXT_BRIGHT_RED, format, ##__VA_ARGS__) +#endif // DISABLE_LOG_SYSTEM + +/** + * @brief 通过segger RTT打印日志,支持格式化输出,格式化输出的实现参考printf. + * @attention !! 此函数不支持浮点格式化,若有需要,请使用Float2Str()函数进行转换后再打印 !! + * + * @param fmt 格式字符串 + * @param ... 参数列表 + * @return int 打印的log字符数 + */ +int PrintLog(const char *fmt, ...); + +/** + * @brief 利用sprintf(),将float转换为字符串进行打印 + * @attention 浮点数需要转换为字符串后才能通过RTT打印 + * + * @param str 转换后的字符串 + * @param va 待转换的float + */ +void Float2Str(char *str, float va); + +#endif \ No newline at end of file diff --git a/bsp/log/bsp_log.md b/bsp/log/bsp_log.md new file mode 100644 index 0000000..259c296 --- /dev/null +++ b/bsp/log/bsp_log.md @@ -0,0 +1,50 @@ +# bsp_log + + neozng1@hnu.edu.cn
+ +## 使用说明 + +bsp_log是基于segger RTT实现的日志打印模块。 + +推荐使用`bsp_log.h`中提供了三级日志: + +```c +#define LOGINFO(format,...) +#define LOGWARNING(format,...) +#define LOGERROR(format,...) +``` + +分别用于输出不同等级的日志。注意RTT不支持直接使用`%f`进行浮点格式化,要使用`void Float2Str(char *str, float va);`转化成字符串之后再发送。 + +**若想启用RTT,必须通过`launch.json`的`debug-jlink`启动调试(不论使用什么调试器)。** 按照`VSCode+Ozone环境配置`完成配置之后的cmsis dap和daplink是可以支持Jlink全家桶的。 + +另外,若你使用的是cmsis-dap和daplink,**请在 *jlink* 调试任务启动之后再打开`log`任务。**(均在项目文件夹下的.vsocde/task.json中,有注释自行查看)。否则可能出线RTT viewer无法连接客户端的情况。 + +在ozone中查看log输出,直接打开console调试任务台和terminal调试中断便可看到调试输出。 + +> 由于ozone版本的原因,可能出现日志不换行或没有颜色。 + +## 自定义输出 + +你也可以自定义输出格式,详见Segger RTT的文档。 + +```c +int printf_log(const char *fmt, ...); +void Float2Str(char *str, float va); // 输出浮点需要先用此函数进行转换 +``` + +调用第一个函数,可以通过jlink或dap-link向调试器连接的上位机发送信息,格式和printf相同,示例如下: + +```c +printf_log("Hello World!\n"); +printf_log("Motor %d met some problem, error code %d!\n",3,1); +``` + +第二个函数可以将浮点类型转换成字符串以方便发送: + +```c +float current_feedback=114.514; +char* str_buff[64]; +Float2Str(str_buff,current_feedback); +printf_log("Motor %d met some problem, error code %d!\n",3,1); +``` diff --git a/bsp/pwm/bsp_pwm.c b/bsp/pwm/bsp_pwm.c new file mode 100644 index 0000000..6c7bf1d --- /dev/null +++ b/bsp/pwm/bsp_pwm.c @@ -0,0 +1,109 @@ +#include "bsp_pwm.h" +#include "stdlib.h" +#include "memory.h" + +// 配合中断以及初始化 +static uint8_t idx; +static PWMInstance *pwm_instance[PWM_DEVICE_CNT] = {NULL}; // 所有的pwm instance保存于此,用于callback时判断中断来源 +static uint32_t PWMSelectTclk(TIM_HandleTypeDef *htim ); +/** + * @brief pwm dma传输完成回调函数 + * + * @param htim 发生中断的定时器句柄 + */ +void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) +{ + for (uint8_t i = 0; i < idx; i++) + { // 来自同一个定时器的中断且通道相同 + if (pwm_instance[i]->htim == htim && htim->Channel == (1<<(pwm_instance[i]->channel/4))) + { + if (pwm_instance[i]->callback) // 如果有回调函数 + pwm_instance[i]->callback(pwm_instance[i]); + return; // 一次只能有一个通道的中断,所以直接返回 + } + } +} + +PWMInstance *PWMRegister(PWM_Init_Config_s *config) +{ + if (idx >= PWM_DEVICE_CNT) // 超过最大实例数,考虑增加或查看是否有内存泄漏 + while (1) + ; + PWMInstance *pwm = (PWMInstance *)malloc(sizeof(PWMInstance)); + memset(pwm, 0, sizeof(PWMInstance)); + + pwm->htim = config->htim; + pwm->channel = config->channel; + pwm->period = config->period; + pwm->dutyratio = config->dutyratio; + pwm->callback = config->callback; + pwm->id = config->id; + pwm->tclk = PWMSelectTclk(pwm->htim); + // 启动PWM + HAL_TIM_PWM_Start(pwm->htim, pwm->channel); + PWMSetPeriod(pwm, pwm->period); + PWMSetDutyRatio(pwm, pwm->dutyratio); + pwm_instance[idx++] = pwm; + return pwm; +} + +/* 只是对HAL的函数进行了形式上的封装 */ +void PWMStart(PWMInstance *pwm) +{ + HAL_TIM_PWM_Start(pwm->htim, pwm->channel); +} + +/* 只是对HAL的函数进行了形式上的封装 */ +void PWMStop(PWMInstance *pwm) +{ + HAL_TIM_PWM_Stop(pwm->htim, pwm->channel); +} + +/* + * @brief 设置pwm周期 + * + * @param pwm pwm实例 + * @param period 周期 单位 s + */ +void PWMSetPeriod(PWMInstance *pwm, float period) +{ + __HAL_TIM_SetAutoreload(pwm->htim, period*((pwm->tclk)/(pwm->htim->Init.Prescaler+1))); +} +/* + * @brief 设置pwm占空比 + * + * @param pwm pwm实例 + * @param dutyratio 占空比 0~1 +*/ +void PWMSetDutyRatio(PWMInstance *pwm, float dutyratio) +{ + __HAL_TIM_SetCompare(pwm->htim, pwm->channel, dutyratio * (pwm->htim->Instance->ARR)); +} + +/* 只是对HAL的函数进行了形式上的封装 */ +void PWMStartDMA(PWMInstance *pwm, uint32_t *pData, uint32_t Size) +{ + HAL_TIM_PWM_Start_DMA(pwm->htim, pwm->channel, pData, Size); +} + +// 设置pwm对应定时器时钟源频率 +//tim2~7,12~14:APB1 tim1,8~11:APB2 +static uint32_t PWMSelectTclk(TIM_HandleTypeDef *htim ) +{ + uintptr_t tclk_temp = ((uintptr_t)((htim)->Instance)); + if ( + (tclk_temp <= (APB1PERIPH_BASE + 0x2000UL)) && + (tclk_temp >= (APB1PERIPH_BASE + 0x0000UL))) + { + return (HAL_RCC_GetPCLK1Freq() * (APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE1)>> RCC_CFGR_PPRE1_Pos] == 0 ? 1 : 2)); + } + else if ( + ((tclk_temp <= (APB2PERIPH_BASE + 0x0400UL)) && + (tclk_temp >= (APB2PERIPH_BASE + 0x0000UL))) || + ((tclk_temp <= (APB2PERIPH_BASE + 0x4800UL)) && + (tclk_temp >= (APB2PERIPH_BASE + 0x4000UL)))) + { + return (HAL_RCC_GetPCLK2Freq() * (APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE1)>> RCC_CFGR_PPRE1_Pos] == 0 ? 1 : 2)); + } + return 0; +} \ No newline at end of file diff --git a/bsp/pwm/bsp_pwm.h b/bsp/pwm/bsp_pwm.h new file mode 100644 index 0000000..1c2a6fe --- /dev/null +++ b/bsp/pwm/bsp_pwm.h @@ -0,0 +1,91 @@ +/** + * @file bsp_pwm.h + * @author your name (you@domain.com) + * @brief + * @version 0.1 + * @date 2023-02-14 + * + * @copyright Copyright (c) 2023 + * + */ + +#ifndef BSP_PWM_H +#define BSP_PWM_H + +#include "tim.h" +#include "stdint.h" +#include "stm32f4xx_hal_rcc.h" +#include "stm32f407xx.h" +#define PWM_DEVICE_CNT 16 // 最大支持的PWM实例数量 + +/* pwm实例结构体 */ +typedef struct pwm_ins_temp +{ + TIM_HandleTypeDef *htim; // TIM句柄 + uint32_t channel; // 通道 + uint32_t tclk; // 时钟频率 + float period; // 周期 + float dutyratio; // 占空比 + void (*callback)(struct pwm_ins_temp *); // DMA传输完成回调函数 + void *id; // 实例ID +} PWMInstance; + +typedef struct +{ + TIM_HandleTypeDef *htim; // TIM句柄 + uint32_t channel; // 通道 + float period; // 周期 + float dutyratio; // 占空比 + void (*callback)(PWMInstance*); // DMA传输完成回调函数 + void *id; // 实例ID +} PWM_Init_Config_s; + +/** + * @brief 注册一个pwm实例 + * + * @param config 初始化配置 + * @return PWMInstance* + */ +PWMInstance *PWMRegister(PWM_Init_Config_s *config); + +/** + * @brief 启动pwm + * + * @param pwm pwm实例 + */ +void PWMStart(PWMInstance *pwm); +/** + * @brief 设置pwm占空比 + * + * @param pwm pwm实例 + * @param dutyratio 占空比 0~1 + */ + +void PWMSetDutyRatio(PWMInstance *pwm, float dutyratio); +/** + * @brief 停止pwm + * + * @param pwm pwm实例 + */ +void PWMStop(PWMInstance *pwm); + +/** + * @brief 设置pwm周期 + * + * @param pwm pwm实例 + * @param period 周期 单位 s + */ +void PWMSetPeriod(PWMInstance *pwm, float period); + +/** + * @brief 启动pwm dma传输 + * + * @param pwm pwm实例 + * @param pData 数据首地址指针,注意数据的位数必须和CubeMX配置的DMA传输位数(字长)一致 + * @param Size 数据长度 + * @note 如果使用此函数,则需要在CubeMX中配置DMA传输位数为对应位数 + * 例如:使用16位数据,则需要配置DMA传输位数为16位(half word),配置错误会导致指针越界或数据错误 + */ +void PWMStartDMA(PWMInstance *pwm, uint32_t *pData, uint32_t Size); + +#endif // BSP_PWM_H \ No newline at end of file diff --git a/bsp/pwm/bsp_pwm.md b/bsp/pwm/bsp_pwm.md new file mode 100644 index 0000000..b3ba531 --- /dev/null +++ b/bsp/pwm/bsp_pwm.md @@ -0,0 +1,5 @@ +# bsp pwm + +同一定时器下的pwm通道更改周期时请注意该定时器下是否有其他pwm示例,如果有请注意不要影响其他pwm通道的周期。 +使用pwm dma传输中断时注意占空比的设置,设为0将不会进入中断函数 +默认tim psc已在cubemx设置好,详情可参考cubemx配置文件 diff --git a/bsp/spi/bsp_spi.c b/bsp/spi/bsp_spi.c new file mode 100644 index 0000000..c607f26 --- /dev/null +++ b/bsp/spi/bsp_spi.c @@ -0,0 +1,149 @@ +#include "bsp_spi.h" +#include "memory.h" +#include "stdlib.h" + +/* 所有的spi instance保存于此,用于callback时判断中断来源*/ +static SPIInstance *spi_instance[SPI_DEVICE_CNT] = {NULL}; +static uint8_t idx = 0; // 配合中断以及初始化 + +SPIInstance *SPIRegister(SPI_Init_Config_s *conf) +{ + if (idx >= MX_SPI_BUS_SLAVE_CNT) // 超过最大实例数 + while (1) + ; + SPIInstance *instance = (SPIInstance *)malloc(sizeof(SPIInstance)); + memset(instance, 0, sizeof(SPIInstance)); + + instance->spi_handle = conf->spi_handle; + instance->GPIOx = conf->GPIOx; + instance->cs_pin = conf->cs_pin; + instance->spi_work_mode = conf->spi_work_mode; + instance->callback = conf->callback; + instance->id = conf->id; + + spi_instance[idx++] = instance; + return instance; +} + +void SPITransmit(SPIInstance *spi_ins, uint8_t *ptr_data, uint8_t len) +{ + // 拉低片选,开始传输(选中从机) + HAL_GPIO_WritePin(spi_ins->GPIOx, spi_ins->cs_pin, GPIO_PIN_RESET); + switch (spi_ins->spi_work_mode) + { + case SPI_DMA_MODE: + HAL_SPI_Transmit_DMA(spi_ins->spi_handle, ptr_data, len); + break; + case SPI_IT_MODE: + HAL_SPI_Transmit_IT(spi_ins->spi_handle, ptr_data, len); + break; + case SPI_BLOCK_MODE: + HAL_SPI_Transmit(spi_ins->spi_handle, ptr_data, len, 1000); // 默认50ms超时 + // 阻塞模式不会调用回调函数,传输完成后直接拉高片选结束 + HAL_GPIO_WritePin(spi_ins->GPIOx, spi_ins->cs_pin, GPIO_PIN_SET); + break; + default: + while (1) + ; // error mode! 请查看是否正确设置模式,或出现指针越界导致模式被异常修改的情况 + break; + } +} + +void SPIRecv(SPIInstance *spi_ins, uint8_t *ptr_data, uint8_t len) +{ + // 用于稍后回调使用 + spi_ins->rx_size = len; + spi_ins->rx_buffer = ptr_data; + // 拉低片选,开始传输 + HAL_GPIO_WritePin(spi_ins->GPIOx, spi_ins->cs_pin, GPIO_PIN_RESET); + switch (spi_ins->spi_work_mode) + { + case SPI_DMA_MODE: + HAL_SPI_Receive_DMA(spi_ins->spi_handle, ptr_data, len); + break; + case SPI_IT_MODE: + HAL_SPI_Receive_IT(spi_ins->spi_handle, ptr_data, len); + break; + case SPI_BLOCK_MODE: + HAL_SPI_Receive(spi_ins->spi_handle, ptr_data, len, 1000); + // 阻塞模式不会调用回调函数,传输完成后直接拉高片选结束 + HAL_GPIO_WritePin(spi_ins->GPIOx, spi_ins->cs_pin, GPIO_PIN_SET); + break; + default: + while (1) + ; // error mode! 请查看是否正确设置模式,或出现指针越界导致模式被异常修改的情况 + break; + } +} + +void SPITransRecv(SPIInstance *spi_ins, uint8_t *ptr_data_rx, uint8_t *ptr_data_tx, uint8_t len) +{ + // 用于稍后回调使用,请保证ptr_data_rx在回调函数被调用之前仍然在作用域内,否则析构之后的行为是未定义的!!! + spi_ins->rx_size = len; + spi_ins->rx_buffer = ptr_data_rx; + // 拉低片选,开始传输 + HAL_GPIO_WritePin(spi_ins->GPIOx, spi_ins->cs_pin, GPIO_PIN_RESET); + switch (spi_ins->spi_work_mode) + { + case SPI_DMA_MODE: + HAL_SPI_TransmitReceive_DMA(spi_ins->spi_handle, ptr_data_tx, ptr_data_rx, len); + break; + case SPI_IT_MODE: + HAL_SPI_TransmitReceive_IT(spi_ins->spi_handle, ptr_data_tx, ptr_data_rx, len); + break; + case SPI_BLOCK_MODE: + HAL_SPI_TransmitReceive(spi_ins->spi_handle, ptr_data_tx, ptr_data_rx, len, 1000); // 默认50ms超时 + // 阻塞模式不会调用回调函数,传输完成后直接拉高片选结束 + HAL_GPIO_WritePin(spi_ins->GPIOx, spi_ins->cs_pin, GPIO_PIN_SET); + break; + default: + while (1) + ; // error mode! 请查看是否正确设置模式,或出现指针越界导致模式被异常修改的情况 + break; + } +} + +void SPISetMode(SPIInstance *spi_ins, SPI_TXRX_MODE_e spi_mode) +{ + if (spi_mode != SPI_DMA_MODE && spi_mode != SPI_IT_MODE && spi_mode != SPI_BLOCK_MODE) + while (1) + ; // error mode! 请查看是否正确设置模式,或出现指针越界导致模式被异常修改的情况 + + if (spi_ins->spi_work_mode != spi_mode) + { + spi_ins->spi_work_mode = spi_mode; + } +} + +/** + * @brief 当SPI接收完成,将会调用此回调函数,可以进行协议解析或其他必须的数据处理等 + * + * @param hspi spi handle + */ +void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) +{ + for (size_t i = 0; i < idx; i++) + { + // 如果是当前spi硬件发出的complete,且cs_pin为低电平(说明正在传输),则尝试调用回调函数 + if (spi_instance[i]->spi_handle == hspi && // 显然同一时间一条总线只能有一个从机在接收数据 + HAL_GPIO_ReadPin(spi_instance[i]->GPIOx, spi_instance[i]->cs_pin) == GPIO_PIN_RESET) + { + // 先拉高片选,结束传输,在判断是否有回调函数,如果有则调用回调函数 + HAL_GPIO_WritePin(spi_instance[i]->GPIOx, spi_instance[i]->cs_pin, GPIO_PIN_SET); + // @todo 后续添加holdon模式,由用户自行决定何时释放片选,允许进行连续传输 + if (spi_instance[i]->callback != NULL) // 回调函数不为空, 则调用回调函数 + spi_instance[i]->callback(spi_instance[i]); + return; + } + } +} + +/** + * @brief 和RxCpltCallback共用解析即可,这里只是形式上封装一下,不用重复写 + * 这是对HAL库的__weak函数的重写,传输使用IT或DMA模式,在传输完成时会调用此函数 + * @param hspi spi handle + */ +void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) +{ + HAL_SPI_RxCpltCallback(hspi); // 直接调用接收完成的回调函数 +} diff --git a/bsp/spi/bsp_spi.h b/bsp/spi/bsp_spi.h new file mode 100644 index 0000000..75e6b61 --- /dev/null +++ b/bsp/spi/bsp_spi.h @@ -0,0 +1,97 @@ +#include "spi.h" +#include "stdint.h" +#include "gpio.h" + +/* 根据开发板引出的spi引脚以及CubeMX中的初始化配置设定 */ +#define SPI_DEVICE_CNT 2 // C型开发板引出两路spi,分别连接BMI088/作为扩展IO在8pin牛角座引出 +#define MX_SPI_BUS_SLAVE_CNT 4 // 单个spi总线上挂载的从机数目 + +/* spi transmit recv mode enumerate*/ +typedef enum +{ + SPI_BLOCK_MODE = 0, // 默认使用阻塞模式 + SPI_IT_MODE, + SPI_DMA_MODE, +} SPI_TXRX_MODE_e; + +/* SPI实例结构体定义 */ +typedef struct spi_ins_temp +{ + SPI_HandleTypeDef *spi_handle; // SPI外设handle + GPIO_TypeDef *GPIOx; // 片选信号对应的GPIO,如GPIOA,GPIOB等等 + uint16_t cs_pin; // 片选信号对应的引脚号,GPIO_PIN_1,GPIO_PIN_2等等 + + SPI_TXRX_MODE_e spi_work_mode; // 传输工作模式 + uint8_t rx_size; // 本次接收的数据长度 + uint8_t *rx_buffer; // 本次接收的数据缓冲区 + + void (*callback)(struct spi_ins_temp *); // 接收回调函数 + void *id; // 模块指针 +} SPIInstance; + +/* 接收回调函数定义,包含SPI的module按照此格式构建回调函数 */ +typedef void (*spi_rx_callback)(SPIInstance *); + +// @todo: 这里可以将GPIO_TypeDef *GPIOx; uint16_t cs_pin合并为bsp_gpio以简化代码实现 +/* SPI初始化配置,其实基本和SPIIstance一模一样,为了代码风格统一因此再次定义 */ +typedef struct +{ + SPI_HandleTypeDef *spi_handle; // SPI外设handle + GPIO_TypeDef *GPIOx; // 片选信号对应的GPIO,如GPIOA,GPIOB等等 + uint16_t cs_pin; // 片选信号对应的引脚号,GPIO_PIN_1,GPIO_PIN_2等等 + + SPI_TXRX_MODE_e spi_work_mode; // 传输工作模式 + + spi_rx_callback callback; // 接收回调函数 + void *id; // 模块指针 +} SPI_Init_Config_s; + +/** + * @brief 注册一个spi instance + * + * @param conf 传入spi配置 + * @return SPIInstance* 返回一个spi实例指针,之后通过该指针操作spi外设 + */ +SPIInstance *SPIRegister(SPI_Init_Config_s *conf); + +/** + * @brief 通过spi向对应从机发送数据 + * @todo 后续加入阻塞模式下的timeout参数 + * + * @param spi_ins spi实例指针 + * @param ptr_data 要发送的数据 + * @param len 待发送的数据长度 + */ +void SPITransmit(SPIInstance *spi_ins, uint8_t *ptr_data, uint8_t len); + +/** + * @brief 通过spi从从机获取数据 + * @attention 特别注意:请保证ptr_data在回调函数被调用之前仍然在作用域内,否则析构之后的行为是未定义的!!! + * + * @param spi_ins spi实例指针 + * @param ptr_data 接受数据buffer的首地址 + * @param len 待接收的长度 + */ +void SPIRecv(SPIInstance *spi_ins, uint8_t *ptr_data, uint8_t len); + +/** + * @brief 通过spi利用移位寄存器同时收发数据 + * @todo 后续加入阻塞模式下的timeout参数 + * @attention 特别注意:请保证ptr_data_rx在回调函数被调用之前仍然在作用域内,否则析构之后的行为是未定义的!!! + * + * @param spi_ins spi实例指针 + * @param ptr_data_rx 接收数据地址 + * @param ptr_data_tx 发送数据地址 + * @param len 接收&发送的长度 + */ +void SPITransRecv(SPIInstance *spi_ins, uint8_t *ptr_data_rx, uint8_t *ptr_data_tx, uint8_t len); + +/** + * @brief 设定spi收发的工作模式 + * + * @param spi_ins spi实例指针 + * @param spi_mode 工作模式,包括阻塞模式(block),中断模式(IT),DMA模式.详见SPI_TXRX_MODE_e的定义 + * + * @todo 是否直接将mode作为transmit/recv的参数,而不是作为spi实例的属性?两者各有优劣 + */ +void SPISetMode(SPIInstance *spi_ins, SPI_TXRX_MODE_e spi_mode); diff --git a/bsp/spi/bsp_spi.md b/bsp/spi/bsp_spi.md new file mode 100644 index 0000000..8bf1e59 --- /dev/null +++ b/bsp/spi/bsp_spi.md @@ -0,0 +1,9 @@ +# bsp spi + +> 预计增加模拟spi + +初始化传入参数中的GPIOx(GPIOA,GPIOB,...)和cs_pin(GPIO_PIN_1,GPIO_PIN_2, ...)都是HAL库内建的宏,在CubeMX初始化的时候若有给gpio分配标签则填入对应名字即可,否则填入原本的宏。 + +注意,如果你没有在CubeMX中为spi分配dma通道,请不要使用dma模式 + +(后续添加安全检查,通过判断hspi的dma handler是否为空来选择模式,如果为空,则自动将DMA转为IT模式以继续传输,并通过log warning 提醒用户) \ No newline at end of file diff --git a/bsp/usart/bsp_usart.c b/bsp/usart/bsp_usart.c new file mode 100644 index 0000000..ccefeb3 --- /dev/null +++ b/bsp/usart/bsp_usart.c @@ -0,0 +1,139 @@ +/** + * @file bsp_usart.c + * @author neozng + * @brief 串口bsp层的实现 + * @version beta + * @date 2022-11-01 + * + * @copyright Copyright (c) 2022 + * + */ +#include "bsp_usart.h" +#include "bsp_log.h" +#include "stdlib.h" +#include "memory.h" + +/* usart service instance, modules' info would be recoreded here using USARTRegister() */ +/* usart服务实例,所有注册了usart的模块信息会被保存在这里 */ +static uint8_t idx; +static USARTInstance *usart_instance[DEVICE_USART_CNT] = {NULL}; + +/** + * @brief 启动串口服务,会在每个实例注册之后自动启用接收,当前实现为DMA接收,后续可能添加IT和BLOCKING接收 + * + * @todo 串口服务会在每个实例注册之后自动启用接收,当前实现为DMA接收,后续可能添加IT和BLOCKING接收 + * 可能还要将此函数修改为extern,使得module可以控制串口的启停 + * + * @param _instance instance owned by module,模块拥有的串口实例 + */ +void USARTServiceInit(USARTInstance *_instance) +{ + HAL_UARTEx_ReceiveToIdle_DMA(_instance->usart_handle, _instance->recv_buff, _instance->recv_buff_size); + // 关闭dma half transfer中断防止两次进入HAL_UARTEx_RxEventCallback() + // 这是HAL库的一个设计失误,发生DMA传输完成/半完成以及串口IDLE中断都会触发HAL_UARTEx_RxEventCallback() + // 我们只希望处理第一种和第三种情况,因此直接关闭DMA半传输中断 + __HAL_DMA_DISABLE_IT(_instance->usart_handle->hdmarx, DMA_IT_HT); +} + +USARTInstance *USARTRegister(USART_Init_Config_s *init_config) +{ + if (idx >= DEVICE_USART_CNT) // 超过最大实例数 + while (1) + LOGERROR("[bsp_usart] USART exceed max instance count!"); + + for (uint8_t i = 0; i < idx; i++) // 检查是否已经注册过 + if (usart_instance[i]->usart_handle == init_config->usart_handle) + while (1) + LOGERROR("[bsp_usart] USART instance already registered!"); + + USARTInstance *instance = (USARTInstance *)malloc(sizeof(USARTInstance)); + memset(instance, 0, sizeof(USARTInstance)); + + instance->usart_handle = init_config->usart_handle; + instance->recv_buff_size = init_config->recv_buff_size; + instance->module_callback = init_config->module_callback; + + usart_instance[idx++] = instance; + USARTServiceInit(instance); + return instance; +} + +/* @todo 当前仅进行了形式上的封装,后续要进一步考虑是否将module的行为与bsp完全分离 */ +void USARTSend(USARTInstance *_instance, uint8_t *send_buf, uint16_t send_size, USART_TRANSFER_MODE mode) +{ + switch (mode) + { + case USART_TRANSFER_BLOCKING: + HAL_UART_Transmit(_instance->usart_handle, send_buf, send_size, 100); + break; + case USART_TRANSFER_IT: + HAL_UART_Transmit_IT(_instance->usart_handle, send_buf, send_size); + break; + case USART_TRANSFER_DMA: + HAL_UART_Transmit_DMA(_instance->usart_handle, send_buf, send_size); + break; + default: + while (1) + ; // illegal mode! check your code context! 检查定义instance的代码上下文,可能出现指针越界 + break; + } +} + +/* 串口发送时,gstate会被设为BUSY_TX */ +uint8_t USARTIsReady(USARTInstance *_instance) +{ + if (_instance->usart_handle->gState | HAL_UART_STATE_BUSY_TX) + return 0; + else + return 1; +} + +/** + * @brief 每次dma/idle中断发生时,都会调用此函数.对于每个uart实例会调用对应的回调进行进一步的处理 + * 例如:视觉协议解析/遥控器解析/裁判系统解析 + * + * @note 通过__HAL_DMA_DISABLE_IT(huart->hdmarx,DMA_IT_HT)关闭dma half transfer中断防止两次进入HAL_UARTEx_RxEventCallback() + * 这是HAL库的一个设计失误,发生DMA传输完成/半完成以及串口IDLE中断都会触发HAL_UARTEx_RxEventCallback() + * 我们只希望处理,因此直接关闭DMA半传输中断第一种和第三种情况 + * + * @param huart 发生中断的串口 + * @param Size 此次接收到的总数居量,暂时没用 + */ +void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) +{ + for (uint8_t i = 0; i < idx; ++i) + { // find the instance which is being handled + if (huart == usart_instance[i]->usart_handle) + { // call the callback function if it is not NULL + if (usart_instance[i]->module_callback != NULL) + { + usart_instance[i]->module_callback(); + memset(usart_instance[i]->recv_buff, 0, Size); // 接收结束后清空buffer,对于变长数据是必要的 + } + HAL_UARTEx_ReceiveToIdle_DMA(usart_instance[i]->usart_handle, usart_instance[i]->recv_buff, usart_instance[i]->recv_buff_size); + __HAL_DMA_DISABLE_IT(usart_instance[i]->usart_handle->hdmarx, DMA_IT_HT); + return; // break the loop + } + } +} + +/** + * @brief 当串口发送/接收出现错误时,会调用此函数,此时这个函数要做的就是重新启动接收 + * + * @note 最常见的错误:奇偶校验/溢出/帧错误 + * + * @param huart 发生错误的串口 + */ +void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) +{ + for (uint8_t i = 0; i < idx; ++i) + { + if (huart == usart_instance[i]->usart_handle) + { + HAL_UARTEx_ReceiveToIdle_DMA(usart_instance[i]->usart_handle, usart_instance[i]->recv_buff, usart_instance[i]->recv_buff_size); + __HAL_DMA_DISABLE_IT(usart_instance[i]->usart_handle->hdmarx, DMA_IT_HT); + LOGWARNING("[bsp_usart] USART error callback triggered, instance idx [%d]", i); + return; + } + } +} \ No newline at end of file diff --git a/bsp/usart/bsp_usart.h b/bsp/usart/bsp_usart.h new file mode 100644 index 0000000..6cf0c00 --- /dev/null +++ b/bsp/usart/bsp_usart.h @@ -0,0 +1,75 @@ +#ifndef BSP_RC_H +#define BSP_RC_H + +#include+#include "main.h" + +#define DEVICE_USART_CNT 3 // C板至多分配3个串口 +#define USART_RXBUFF_LIMIT 256 // 如果协议需要更大的buff,请修改这里 + +// 模块回调函数,用于解析协议 +typedef void (*usart_module_callback)(); + +/* 发送模式枚举 */ +typedef enum +{ + USART_TRANSFER_NONE=0, + USART_TRANSFER_BLOCKING, + USART_TRANSFER_IT, + USART_TRANSFER_DMA, +} USART_TRANSFER_MODE; + +// 串口实例结构体,每个module都要包含一个实例. +// 由于串口是独占的点对点通信,所以不需要考虑多个module同时使用一个串口的情况,因此不用加入id;当然也可以选择加入,这样在bsp层可以访问到module的其他信息 +typedef struct +{ + uint8_t recv_buff[USART_RXBUFF_LIMIT]; // 预先定义的最大buff大小,如果太小请修改USART_RXBUFF_LIMIT + uint8_t recv_buff_size; // 模块接收一包数据的大小 + UART_HandleTypeDef *usart_handle; // 实例对应的usart_handle + usart_module_callback module_callback; // 解析收到的数据的回调函数 +} USARTInstance; + +/* usart 初始化配置结构体 */ +typedef struct +{ + uint8_t recv_buff_size; // 模块接收一包数据的大小 + UART_HandleTypeDef *usart_handle; // 实例对应的usart_handle + usart_module_callback module_callback; // 解析收到的数据的回调函数 +} USART_Init_Config_s; + +/** + * @brief 注册一个串口实例,返回一个串口实例指针 + * + * @param init_config 传入串口初始化结构体 + */ +USARTInstance *USARTRegister(USART_Init_Config_s *init_config); + +/** + * @brief 启动串口服务,需要传入一个usart实例.一般用于lost callback的情况(使用串口的模块daemon) + * + * @param _instance + */ +void USARTServiceInit(USARTInstance *_instance); + + +/** + * @brief 通过调用该函数可以发送一帧数据,需要传入一个usart实例,发送buff以及这一帧的长度 + * @note 在短时间内连续调用此接口,若采用IT/DMA会导致上一次的发送未完成而新的发送取消. + * @note 若希望连续使用DMA/IT进行发送,请配合USARTIsReady()使用,或自行为你的module实现一个发送队列和任务. + * @todo 是否考虑为USARTInstance增加发送队列以进行连续发送? + * + * @param _instance 串口实例 + * @param send_buf 待发送数据的buffer + * @param send_size how many bytes to send + */ +void USARTSend(USARTInstance *_instance, uint8_t *send_buf, uint16_t send_size,USART_TRANSFER_MODE mode); + +/** + * @brief 判断串口是否准备好,用于连续或异步的IT/DMA发送 + * + * @param _instance 要判断的串口实例 + * @return uint8_t ready 1, busy 0 + */ +uint8_t USARTIsReady(USARTInstance *_instance); + +#endif diff --git a/bsp/usart/bsp_usart.md b/bsp/usart/bsp_usart.md new file mode 100644 index 0000000..532df57 --- /dev/null +++ b/bsp/usart/bsp_usart.md @@ -0,0 +1,80 @@ +# bsp_usart + + neozng1@hnu.edu.cn
+ +> TODO: 增加发送队列以解决短时间内调用`USARTSend()`发生丢包的问题,目前仅支持DMA。还需要提供阻塞和IT模式以供选择,参考bspiic和spi进行实现。 +> 可以直接在发送函数的参数列表添加发送模式选择,或增加instance成员变量,并提供设置模式接口,两者各有优劣 + +## 使用说明 + +若你需要构建新的基于串口的module,首先需要拥有一个`usart_instance`的指针用于操作串口对象。 + +需要在串口实例下设定接收的数据包的长度,实例对应的串口硬件(通过`UART_HandleTypeDef`指定,如`&huart1`),解析接收数据对应的回调函数这三个参数。然后,调用`USARTRegister()`并传入配置好的`usart_instance`指针即可。 + +若要发送数据,调用`USARTSend()`。注意buffsize务必小于你创建的buff的大小,否则造成指针越界后果未知。 + +串口硬件收到数据时,会将其存入`usart_instance.recv_buff[]`中,当收到完整一包数据,会调用设定的回调函数`module_callback`(即你注册时提供的解析函数)。在此函数中,你可以通过`usart_instance.recv_buff[]`访问串口收到的数据。 + +## 代码结构 + +.h文件内包括了外部接口和类型定义,以及模块对应的宏。c文件内为私有函数和外部接口的定义。 + +## 类型定义 + +```c +#define DEVICE_USART_CNT 3 // C板至多分配3个串口 +#define USART_RXBUFF_LIMIT 128 // if your protocol needs bigger buff, modify here + +typedef void (*usart_module_callback)(); + +/* usart_instance struct,each app would have one instance */ +typedef struct +{ + uint8_t recv_buff[USART_RXBUFF_LIMIT]; // 预先定义的最大buff大小,如果太小请修改USART_RXBUFF_LIMIT + uint8_t recv_buff_size; // 模块接收一包数据的大小 + UART_HandleTypeDef *usart_handle; // 实例对应的usart_handle + usart_module_callback module_callback; // 解析收到的数据的回调函数 +} usart_instance; +``` + +- `DEVICE_USART_CNT`是开发板上可用的串口数量。 + +- `USART_RXBUFF_LIMIT`是串口单次接收的数据长度上限,暂时设为128,如果需要更大的buffer容量,修改该值。 + +- `usart_module_callback()`是模块提供给串口接收中断回调函数使用的协议解析函数指针。对于每个需要串口的模块,需要定义一个这样的函数用于解包数据。 + +- 每定义一个`usart_instance`,就代表一个串口的**实例**(对象)。一个串口实例内有接收buffer,单个数据包的大小,该串口对应的`HAL handle`(代表其使用的串口硬件具体是哪一个)以及用于解包数据的回调函数。 + + +## 外部接口 + +```c +void USARTRegister(usart_instance *_instance); +void USARTSend(usart_instance *_instance, uint8_t *send_buf, uint16_t send_size); +``` + +- `USARTRegister`是用于初始化串口对象的接口,module层的模块对象(也应当为一个结构体)内要包含一个`usart_instance`。 + + **在调用该函数之前,需要先对其成员变量`*usart_handle`,`module_callback()`以及`recv_buff_size`进行赋值。** + +- `USARTSend()`是通过模块通过其拥有的串口对象发送数据的接口,调用时传入的参数为串口实例指针,发送缓存以及此次要发送的数据长度(8-bit\*n)。 + +## 私有函数和变量 + +在.c文件内设为static的函数和变量 + +```c +static usart_instance *instance[DEVICE_USART_CNT]; +``` + +这是bsp层管理所有串口实例的入口。 + +```c +static void USARTServiceInit(usart_instance *_instance) +void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size) +void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) +``` + +- `USARTServiceInit()`会被`USARTRegister()`调用,开启接收中断 + +- `HAL_UARTEx_RxEventCallback()`和`HAL_UART_ErrorCallback()`都是对HAL的回调函数的重定义(原本的callback是`__week`修饰的弱定义),前者在发生**IDLE中断**或**单次DMA传输中断**后会被调用(说明收到了完整的一包数据),随后在里面根据中断来源,调用拥有产生了该中断的模块的协议解析函数进行数据解包;后者在串口传输出错的时候会被调用,重新开启接收。 \ No newline at end of file diff --git a/bsp/usb/bsp_usb.c b/bsp/usb/bsp_usb.c new file mode 100644 index 0000000..9c4ad2f --- /dev/null +++ b/bsp/usb/bsp_usb.c @@ -0,0 +1,31 @@ +/** + * @file bsp_usb.c + * @author your name (you@domain.com) + * @brief usb是单例bsp,因此不保存实例 + * @version 0.1 + * @date 2023-02-09 + * + * @copyright Copyright (c) 2023 + * + */ + +#include "bsp_usb.h" +#include "bsp_log.h" +#include "bsp_dwt.h" + +static uint8_t *bsp_usb_rx_buffer; // 接收到的数据会被放在这里,buffer size为2048 +// 注意usb单个数据包(Full speed模式下)最大为64byte,超出可能会出现丢包情况 + +uint8_t *USBInit(USB_Init_Config_s usb_conf) +{ + // usb的软件复位(模拟拔插)在usbd_conf.c中的HAL_PCD_MspInit()中 + bsp_usb_rx_buffer = CDCInitRxbufferNcallback(usb_conf.tx_cbk, usb_conf.rx_cbk); // 获取接收数据指针 + // usb的接收回调函数会在这里被设置,并将数据保存在bsp_usb_rx_buffer中 + LOGINFO("USB init success"); + return bsp_usb_rx_buffer; +} + +void USBTransmit(uint8_t *buffer, uint16_t len) +{ + CDC_Transmit_FS(buffer, len); // 发送 +} diff --git a/bsp/usb/bsp_usb.h b/bsp/usb/bsp_usb.h new file mode 100644 index 0000000..5ab1588 --- /dev/null +++ b/bsp/usb/bsp_usb.h @@ -0,0 +1,30 @@ +/** + * @file bsp_usb.h + * @author your name (you@domain.com) + * @brief 提供对usb vpc(virtal com port)的操作接口,hid和msf考虑后续添加 + * @attention 这一版usb修改了usbd_cdc_if.c中的CDC_Receive_FS函数,若使用cube生成后会被覆盖.后续需要由usbcdciftemplate创建一套自己的模板 + * @version 0.1 + * @date 2023-02-09 + * + * @copyright Copyright (c) 2023 + * + */ +#pragma once +#include "usb_device.h" +#include "usbd_cdc.h" +#include "usbd_conf.h" +#include "usbd_desc.h" +#include "usbd_cdc_if.h" + +typedef struct +{ + USBCallback tx_cbk; + USBCallback rx_cbk; +} USB_Init_Config_s; + +/* @note 虚拟串口的波特率/校验位/数据位等动态可变,取决于上位机的设定 */ +/* 使用时不需要关心这些设置(作为从机) */ + +uint8_t *USBInit(USB_Init_Config_s usb_conf); // bsp初始化时调用会重新枚举设备 + +void USBTransmit(uint8_t *buffer, uint16_t len); // 通过usb发送数据 \ No newline at end of file diff --git a/bsp/usb/bsp_usb.md b/bsp/usb/bsp_usb.md new file mode 100644 index 0000000..739fcc3 --- /dev/null +++ b/bsp/usb/bsp_usb.md @@ -0,0 +1,5 @@ +# bsp usb + +简单写点,有待优化. 目前仅支持虚拟串口通信,暂未开发其他内容. + +注意,为了增加发送完成和接收完成回调,对Inc/usbd_xxxx.h四个文件做了修改,对Src/usbxxx.c也进行了修改。 diff --git a/modules/BMI088/bmi088-datasheet.pdf b/modules/BMI088/bmi088-datasheet.pdf new file mode 100644 index 0000000..eecb83d Binary files /dev/null and b/modules/BMI088/bmi088-datasheet.pdf differ diff --git a/modules/BMI088/bmi088.c b/modules/BMI088/bmi088.c new file mode 100644 index 0000000..04ffbdc --- /dev/null +++ b/modules/BMI088/bmi088.c @@ -0,0 +1,446 @@ +#include "bmi088_regNdef.h" +#include "bmi088.h" +#include "user_lib.h" + +// ---------------------------以下私有函数,用于读写BMI088寄存器封装,blocking--------------------------------// +/** + * @brief 读取BMI088寄存器Accel. BMI088要求在不释放CS的情况下连续读取 + * + * @param bmi088 待读取的BMI088实例 + * @param reg 待读取的寄存器地址 + * @param dataptr 读取到的数据存放的指针 + * @param len 读取长度 + */ +static void BMI088AccelRead(BMI088Instance *bmi088, uint8_t reg, uint8_t *dataptr, uint8_t len) +{ + if (len > 6) + while (1) + ; + // 一次读取最多6个字节,加上两个dummy data 第一个字节的第一个位是读写位,1为读,0为写,1-7bit是寄存器地址 + static uint8_t tx[8]; // 读取,第一个字节为0x80|reg ,第二个是dummy data,后面的没用都是dummy write + static uint8_t rx[8]; // 前两个字节是dummy data,第三个开始是真正的数据 + tx[0] = 0x80 | reg; // 静态变量每次进来还是上次的值,所以要每次都要给tx[0]赋值0x80 + SPITransRecv(bmi088->spi_acc, rx, tx, len + 2); + memcpy(dataptr, rx + 2, len); // @todo : memcpy有额外开销,后续可以考虑优化,在SPI中加入接口或模式,使得在一次传输结束后不释放CS,直接接着传输 +} + +/** + * @brief 读取BMI088寄存器Gyro, BMI088要求在不释放CS的情况下连续读取 + * + * @param bmi088 待读取的BMI088实例 + * @param reg 待读取的寄存器地址 + * @param dataptr 读取到的数据存放的指针 + * @param len 读取长度 + */ +static void BMI088GyroRead(BMI088Instance *bmi088, uint8_t reg, uint8_t *dataptr, uint8_t len) +{ + if (len > 6) + while (1) + ; + // 一次读取最多6个字节,加上一个dummy data ,第一个字节的第一个位是读写位,1为读,0为写,1-7bit是寄存器地址 + static uint8_t tx[7] = {0x80}; // 读取,第一个字节为0x80 | reg ,之后是dummy data + static uint8_t rx[7]; // 第一个是dummy data,第三个开始是真正的数据 + tx[0] = 0x80 | reg; + SPITransRecv(bmi088->spi_gyro, rx, tx, len + 1); + memcpy(dataptr, rx + 1, len); // @todo : memcpy有额外开销,后续可以考虑优化,在SPI中加入接口或模式,使得在一次传输结束后不释放CS,直接接着传输 +} + +/** + * @brief 写accel寄存器.对spitransmit形式上的封装 + * @attention 只会向目标reg写入一个字节,因为只有1个字节所以直接传值(指针是32位反而浪费) + * + * @param bmi088 待写入的BMI088实例 + * @param reg 待写入的寄存器地址 + * @param data 待写入的数据(注意不是指针) + */ +static void BMI088AccelWriteSingleReg(BMI088Instance *bmi088, uint8_t reg, uint8_t data) +{ + uint8_t tx[2] = {reg, data}; + SPITransmit(bmi088->spi_acc, tx, 2); +} + +/** + * @brief 写gyro寄存器.形式上的封装 + * @attention 只会向目标reg写入一个字节,因为只有1个字节所以直接传值(指针是32位反而浪费) + * + * @param bmi088 待写入的BMI088实例 + * @param reg 待写入的寄存器地址 + * @param data 待写入的数据(注意不是指针) + */ +static void BMI088GyroWriteSingleReg(BMI088Instance *bmi088, uint8_t reg, uint8_t data) +{ + uint8_t tx[2] = {reg, data}; + SPITransmit(bmi088->spi_gyro, tx, 2); +} +// -------------------------以上为私有函数,封装了BMI088寄存器读写函数,blocking--------------------------------// + +// -------------------------以下为私有函数,用于初始化BMI088acc和gyro的硬件和配置--------------------------------// +#define BMI088REG 0 +#define BMI088DATA 1 +#define BMI088ERROR 2 +// BMI088初始化配置数组for accel,第一列为reg地址,第二列为写入的配置值,第三列为错误码(如果出错) +static uint8_t BMI088_Accel_Init_Table[BMI088_WRITE_ACCEL_REG_NUM][3] = + { + {BMI088_ACC_PWR_CTRL, BMI088_ACC_ENABLE_ACC_ON, BMI088_ACC_PWR_CTRL_ERROR}, + {BMI088_ACC_PWR_CONF, BMI088_ACC_PWR_ACTIVE_MODE, BMI088_ACC_PWR_CONF_ERROR}, + {BMI088_ACC_CONF, BMI088_ACC_NORMAL | BMI088_ACC_800_HZ | BMI088_ACC_CONF_MUST_Set, BMI088_ACC_CONF_ERROR}, + {BMI088_ACC_RANGE, BMI088_ACC_RANGE_6G, BMI088_ACC_RANGE_ERROR}, + {BMI088_INT1_IO_CTRL, BMI088_ACC_INT1_IO_ENABLE | BMI088_ACC_INT1_GPIO_PP | BMI088_ACC_INT1_GPIO_LOW, BMI088_INT1_IO_CTRL_ERROR}, + {BMI088_INT_MAP_DATA, BMI088_ACC_INT1_DRDY_INTERRUPT, BMI088_INT_MAP_DATA_ERROR}}; +// BMI088初始化配置数组for gyro,第一列为reg地址,第二列为写入的配置值,第三列为错误码(如果出错) +static uint8_t BMI088_Gyro_Init_Table[BMI088_WRITE_GYRO_REG_NUM][3] = + { + {BMI088_GYRO_RANGE, BMI088_GYRO_2000, BMI088_GYRO_RANGE_ERROR}, + {BMI088_GYRO_BANDWIDTH, BMI088_GYRO_2000_230_HZ | BMI088_GYRO_BANDWIDTH_MUST_Set, BMI088_GYRO_BANDWIDTH_ERROR}, + {BMI088_GYRO_LPM1, BMI088_GYRO_NORMAL_MODE, BMI088_GYRO_LPM1_ERROR}, + {BMI088_GYRO_CTRL, BMI088_DRDY_ON, BMI088_GYRO_CTRL_ERROR}, + {BMI088_GYRO_INT3_INT4_IO_CONF, BMI088_GYRO_INT3_GPIO_PP | BMI088_GYRO_INT3_GPIO_LOW, BMI088_GYRO_INT3_INT4_IO_CONF_ERROR}, + {BMI088_GYRO_INT3_INT4_IO_MAP, BMI088_GYRO_DRDY_IO_INT3, BMI088_GYRO_INT3_INT4_IO_MAP_ERROR}}; +// @attention : 以上两个数组配合各自的初始化函数使用. 若要修改请参照BMI088 datasheet + +/** + * @brief 初始化BMI088加速度计,提高可读性分拆功能 + * + * @param bmi088 待初始化的BMI088实例 + * @return uint8_t BMI088ERROR CODE if any problems here + */ +static uint8_t BMI088AccelInit(BMI088Instance *bmi088) +{ + uint8_t whoami_check = 0; + + // 加速度计以I2C模式启动,需要一次上升沿来切换到SPI模式,因此进行一次fake write + BMI088AccelRead(bmi088, BMI088_ACC_CHIP_ID, &whoami_check, 1); + DWT_Delay(0.001); + + BMI088AccelWriteSingleReg(bmi088, BMI088_ACC_SOFTRESET, BMI088_ACC_SOFTRESET_VALUE); // 软复位 + DWT_Delay(BMI088_COM_WAIT_SENSOR_TIME / 1000); + + // 检查ID,如果不是0x1E(bmi088 whoami寄存器值),则返回错误 + BMI088AccelRead(bmi088, BMI088_ACC_CHIP_ID, &whoami_check, 1); + if (whoami_check != BMI088_ACC_CHIP_ID_VALUE) + return BMI088_NO_SENSOR; + DWT_Delay(0.001); + // 初始化寄存器,提高可读性 + uint8_t reg = 0, data = 0; + BMI088_ERORR_CODE_e error = 0; + // 使用sizeof而不是magic number,这样如果修改了数组大小,不用修改这里的代码;或者使用宏定义 + for (uint8_t i = 0; i < sizeof(BMI088_Accel_Init_Table) / sizeof(BMI088_Accel_Init_Table[0]); i++) + { + reg = BMI088_Accel_Init_Table[i][BMI088REG]; + data = BMI088_Accel_Init_Table[i][BMI088DATA]; + BMI088AccelWriteSingleReg(bmi088, reg, data); // 写入寄存器 + DWT_Delay(0.01); + BMI088AccelRead(bmi088, reg, &data, 1); // 写完之后立刻读回检查 + DWT_Delay(0.01); + if (data != BMI088_Accel_Init_Table[i][BMI088DATA]) + error |= BMI088_Accel_Init_Table[i][BMI088ERROR]; + //{i--;} 可以设置retry次数,如果retry次数用完了,则返回error + } + return error; +} + +/** + * @brief 初始化BMI088陀螺仪,提高可读性分拆功能 + * + * @param bmi088 待初始化的BMI088实例 + * @return uint8_t BMI088ERROR CODE + */ +static uint8_t BMI088GyroInit(BMI088Instance *bmi088) +{ + // 后续添加reset和通信检查? + // code to go here ... + BMI088GyroWriteSingleReg(bmi088, BMI088_GYRO_SOFTRESET, BMI088_GYRO_SOFTRESET_VALUE); // 软复位 + DWT_Delay(0.08); + + // 检查ID,如果不是0x0F(bmi088 whoami寄存器值),则返回错误 + uint8_t whoami_check = 0; + BMI088GyroRead(bmi088, BMI088_GYRO_CHIP_ID, &whoami_check, 1); + if (whoami_check != BMI088_GYRO_CHIP_ID_VALUE) + return BMI088_NO_SENSOR; + DWT_Delay(0.001); + + // 初始化寄存器,提高可读性 + uint8_t reg = 0, data = 0; + BMI088_ERORR_CODE_e error = 0; + // 使用sizeof而不是magic number,这样如果修改了数组大小,不用修改这里的代码;或者使用宏定义 + for (uint8_t i = 0; i < sizeof(BMI088_Gyro_Init_Table) / sizeof(BMI088_Gyro_Init_Table[0]); i++) + { + reg = BMI088_Gyro_Init_Table[i][BMI088REG]; + data = BMI088_Gyro_Init_Table[i][BMI088DATA]; + BMI088GyroWriteSingleReg(bmi088, reg, data); // 写入寄存器 + DWT_Delay(0.001); + BMI088GyroRead(bmi088, reg, &data, 1); // 写完之后立刻读回对应寄存器检查是否写入成功 + DWT_Delay(0.001); + if (data != BMI088_Gyro_Init_Table[i][BMI088DATA]) + error |= BMI088_Gyro_Init_Table[i][BMI088ERROR]; + //{i--;} 可以设置retry次数,尝试重新写入.如果retry次数用完了,则返回error + } + + return error; +} +// -------------------------以上为私有函数,用于初始化BMI088acc和gyro的硬件和配置--------------------------------// + +// -------------------------以下为私有函数,private用于IT模式下的中断处理---------------------------------// + +/** + * @brief 待编写,很快! + * + */ +static void BMI088AccSPIFinishCallback(SPIInstance *spi) +{ + // static BMI088Instance *bmi088; + // bmi088 = (BMI088Instance *)(spi->id); + // 若第一次读取加速度,则在这里启动温度读取 + // 如果使用异步姿态更新,此处唤醒量测更新的任务 +} + +static void BMI088GyroSPIFinishCallback(SPIInstance *spi) +{ + // static BMI088Instance *bmi088; + // bmi088 = (BMI088Instance *)(spi->id); + // 若不是异步,啥也不做;否则启动姿态的预测步(propagation) +} + +static void BMI088AccINTCallback(GPIOInstance *gpio) +{ + // static BMI088Instance *bmi088; + // bmi088 = (BMI088Instance *)(gpio->id); + // 启动加速度计数据读取(和温度读取,如果有必要),并转换为实际值 + // 读取完毕会调用BMI088AccSPIFinishCallback +} + +static void BMI088GyroINTCallback(GPIOInstance *gpio) +{ + // static BMI088Instance *bmi088; + // bmi088 = (BMI088Instance *)(gpio->id); + // 启动陀螺仪数据读取,并转换为实际值 + // 读取完毕会调用BMI088GyroSPIFinishCallback +} + +// -------------------------以上为私有函数,private用于IT模式下的中断处理---------------------------------// + +// -------------------------以下为公有函数,用于注册BMI088,标定和数据读取--------------------------------// + +/** + * @brief + * @todo 现在要考虑一下数据返回的方式,指针还是结构体? + * + * @param bmi088 + * @return BMI088_Data_t + */ +uint8_t BMI088Acquire(BMI088Instance *bmi088, BMI088_Data_t *data_store) +{ + // 如果是blocking模式,则主动触发一次读取并返回数据 + if (bmi088->work_mode == BMI088_BLOCK_PERIODIC_MODE) + { + static uint8_t buf[6] = {0}; // 最多读取6个byte(gyro/acc,temp是2) + // 读取accel的x轴数据首地址,bmi088内部自增读取地址 // 3* sizeof(int16_t) + BMI088AccelRead(bmi088, BMI088_ACCEL_XOUT_L, buf, 6); + for (uint8_t i = 0; i < 3; i++) + data_store->acc[i] = bmi088->acc_coef * (float)(int16_t)(((buf[2 * i + 1]) << 8) | buf[2 * i]); + BMI088GyroRead(bmi088, BMI088_GYRO_X_L, buf, 6); // 连续读取3个(3*2=6)轴的角速度 + for (uint8_t i = 0; i < 3; i++) + data_store->gyro[i] = bmi088->BMI088_GYRO_SEN * (float)(int16_t)(((buf[2 * i + 1]) << 8) | buf[2 * i]); + BMI088AccelRead(bmi088, BMI088_TEMP_M, buf, 2); // 读温度,温度传感器在accel上 + data_store->temperature = (float)(int16_t)(((buf[0] << 3) | (buf[1] >> 5))) * BMI088_TEMP_FACTOR + BMI088_TEMP_OFFSET; + + return 1; + } + + // 如果是IT模式,则检查标志位.当传感器数据准备好会触发外部中断,中断服务函数会将标志位置1 + if (bmi088->work_mode == BMI088_BLOCK_TRIGGER_MODE && bmi088->update_flag.imu_ready == 1) + { + memcpy(data_store, &bmi088->gyro, sizeof(BMI088_Data_t)); + bmi088->update_flag.imu_ready = 0; + return 1; + } + + // 如果数据还没准备好,则返回空数据?或者返回上一次的数据?或者返回错误码? @todo + if (bmi088->update_flag.imu_ready == 0) + return 0; + return 1; +} + +/* pre calibrate parameter to go here */ +#pragma message "REMEMBER TO SET PRE CALIBRATE PARAMETER IF YOU CHOOSE NOT TO CALIBRATE" +#define BMI088_PRE_CALI_ACC_X_OFFSET 0.0f +#define BMI088_PRE_CALI_ACC_Y_OFFSET 0.0f +#define BMI088_PRE_CALI_ACC_Z_OFFSET 0.0f +#define BMI088_PRE_CALI_G_NORM 9.805f +/** + * @brief BMI088 acc gyro 标定 + * @note 标定后的数据存储在bmi088->bias和gNorm中,用于后续数据消噪和单位转换归一化 + * @attention 不管工作模式是blocking还是IT,标定时都是blocking模式,所以不用担心中断关闭后无法标定(RobotInit关闭了全局中断) + * @attention 标定精度和等待时间有关,目前使用线性回归.后续考虑引入非线性回归 + * @todo 将标定次数(等待时间)变为参数供设定 + * @section 整体流程为1.累加加速度数据计算gNrom() 2.累加陀螺仪数据计算零飘 + * 3. 如果标定过程运动幅度过大,重新标定 4.保存标定参数 + * + * @param _bmi088 待标定的BMI088实例 + */ +void BMI088CalibrateIMU(BMI088Instance *_bmi088) +{ + if (_bmi088->cali_mode == BMI088_CALIBRATE_ONLINE_MODE) // 性感bmi088在线标定,耗时6s + { + _bmi088->acc_coef = BMI088_ACCEL_6G_SEN; // 标定完后要乘以9.805/gNorm + _bmi088->BMI088_GYRO_SEN = BMI088_GYRO_2000_SEN; // 后续改为从initTable中获取 + // 一次性参数用完就丢,不用static + float startTime; // 开始标定时间,用于确定是否超时 + uint16_t CaliTimes = 6000; // 标定次数(6s) + float gyroMax[3], gyroMin[3]; // 保存标定过程中读取到的数据最大值判断是否满足标定环境 + float gNormTemp, gNormMax, gNormMin; // 同上,计算矢量范数(模长) + float gyroDiff[3], gNormDiff; // 每个轴的最大角速度跨度及其模长 + + BMI088_Data_t raw_data; + startTime = DWT_GetTimeline_s(); + // 循环继续的条件为标定环境不满足 + do // 用do while至少执行一次,省得对上面的参数进行初始化 + { // 标定超时,直接使用预标定参数(如果有) + if (DWT_GetTimeline_s() - startTime > 12.01) + { // 两次都没有成功就切换标定模式,丢给下一个if处理,使用预标定参数 + _bmi088->cali_mode = BMI088_LOAD_PRE_CALI_MODE; + break; + } + + DWT_Delay(0.0005); + _bmi088->gNorm = 0; + for (uint8_t i = 0; i < 3; i++) // 重置gNorm和零飘 + _bmi088->gyro_offset[i] = 0; + + // @todo : 这里也有获取bmi088数据的操作,后续与BMI088Acquire合并.注意标定时的工作模式是阻塞,且offset和acc_coef要初始化成0和1,标定完成后再设定为标定值 + for (uint16_t i = 0; i < CaliTimes; ++i) // 提前计算,优化 + { + BMI088Acquire(_bmi088, &raw_data); + gNormTemp = NormOf3d(raw_data.acc); + _bmi088->gNorm += gNormTemp; // 计算范数并累加,最后除以calib times获取单次值 + for (uint8_t i = 0; i < 3; i++) + _bmi088->gyro_offset[i] += raw_data.gyro[i]; // 因为标定时传感器静止,所以采集到的值就是漂移,累加当前值,最后除以calib times获得零飘 + + if (i == 0) // 避免未定义的行为(else中) + { + gNormMax = gNormMin = gNormTemp; // 初始化成当前的重力加速度模长 + for (uint8_t j = 0; j < 3; ++j) + { + gyroMax[j] = raw_data.gyro[j]; + gyroMin[j] = raw_data.gyro[j]; + } + } + else // 更新gNorm的Min Max和gyro的minmax + { + gNormMax = gNormMax > gNormTemp ? gNormMax : gNormTemp; + gNormMin = gNormMin < gNormTemp ? gNormMin : gNormTemp; + for (uint8_t j = 0; j < 3; ++j) + { + gyroMax[j] = gyroMax[j] > _bmi088->gyro[j] ? gyroMax[j] : _bmi088->gyro[j]; + gyroMin[j] = gyroMin[j] < _bmi088->gyro[j] ? gyroMin[j] : _bmi088->gyro[j]; + } + } + + gNormDiff = gNormMax - gNormMin; // 最大值和最小值的差 + for (uint8_t j = 0; j < 3; ++j) + gyroDiff[j] = gyroMax[j] - gyroMin[j]; // 分别计算三轴 + if (gNormDiff > 0.5f || + gyroDiff[0] > 0.15f || + gyroDiff[1] > 0.15f || + gyroDiff[2] > 0.15f) + break; // 超出范围了,重开! remake到while循环,外面还有一层 + DWT_Delay(0.0005); // 休息一会再开始下一轮数据获取,IMU准备数据需要时间 + } + _bmi088->gNorm /= (float)CaliTimes; // 加速度范数重力 + for (uint8_t i = 0; i < 3; ++i) + _bmi088->gyro_offset[i] /= (float)CaliTimes; // 三轴零飘 + // 这里直接存到temperature,可以另外增加BMI088Instance的成员变量TempWhenCalib + _bmi088->temperature = raw_data.temperature * BMI088_TEMP_FACTOR + BMI088_TEMP_OFFSET; // 保存标定时的温度,如果已知温度和零飘的关系 + // caliTryOutCount++; 保存已经尝试的标定次数?由你. + } while (gNormDiff > 0.5f || + fabsf(_bmi088->gNorm - 9.8f) > 0.5f || + gyroDiff[0] > 0.15f || + gyroDiff[1] > 0.15f || + gyroDiff[2] > 0.15f || + fabsf(_bmi088->gyro_offset[0]) > 0.01f || + fabsf(_bmi088->gyro_offset[1]) > 0.01f || + fabsf(_bmi088->gyro_offset[2]) > 0.01f); // 满足条件说明标定环境不好 + } + + // 离线标定 + if (_bmi088->cali_mode == BMI088_LOAD_PRE_CALI_MODE) // 如果标定失败也会进来,直接使用离线数据 + { + _bmi088->gyro_offset[0] = BMI088_PRE_CALI_ACC_X_OFFSET; + _bmi088->gyro_offset[1] = BMI088_PRE_CALI_ACC_Y_OFFSET; + _bmi088->gyro_offset[2] = BMI088_PRE_CALI_ACC_Z_OFFSET; + _bmi088->gNorm = BMI088_PRE_CALI_G_NORM; + } + _bmi088->acc_coef *= 9.805 / _bmi088->gNorm; +} + +// 考虑阻塞模式和非阻塞模式的兼容性,通过条件编译(则需要在编译前修改宏定义)或runtime参数判断 +// runtime的开销不大(一次性判断),但是需要修改函数原型,增加参数,代码长度增加(但不多) +// runtime如何修改callback?根据参数选择是否给spi传入callback,如果是阻塞模式,则不传入callback,如果是非阻塞模式,则传入callback(bsp会检查是否NULL) +// 条件编译的开销小,但是需要修改宏定义,增加编译时间,同时人力介入 +// 根据实际情况选择(说了和没说一样!) + +BMI088Instance *BMI088Register(BMI088_Init_Config_s *config) +{ + // 申请内存 + BMI088Instance *bmi088_instance = (BMI088Instance *)zmalloc(sizeof(BMI088Instance)); + // 从右向左赋值,让bsp instance保存指向bmi088_instance的指针(父指针),便于在底层中断中访问bmi088_instance + config->acc_int_config.id = + config->gyro_int_config.id = + config->spi_acc_config.id = + config->spi_gyro_config.id = + config->heat_pwm_config.id = bmi088_instance; + // @todo: + // 目前只实现了!!!阻塞读取模式!!!.如果需要使用IT模式,则需要修改这里的代码,为spi和gpio注册callback(默认为NULL) + // 还需要设置SPI的传输模式为DMA模式或IT模式(默认为blocking) + // 可以通过conditional compilation或者runtime参数判断 + // code to go here ... + + // INT_ACC EXTI CALLBACK: 检查是否有传输正在进行,如果没有则开启SPI DMA传输,有则置位wait标志位; + // 第一次是加速度计,第二次是温度. + + // INT_GYRO EXTI CALLBACK: 开启SPI DMA传输,不会出现等待传输的情况 + // SPI_GYRO DMA CALLBACK: 解算陀螺仪数据, + // SPI_ACC DMA CALLBACK: 解算加速度计数据,清除温度wait标志位并启动温度传输,第二次进入中断时解算温度数据 + + // 还有其他方案可用,比如阻塞等待传输完成,但是比较笨. + + // 根据参数选择工作模式 + if (config->work_mode == BMI088_BLOCK_PERIODIC_MODE) + { + config->spi_acc_config.spi_work_mode = SPI_BLOCK_MODE; + config->spi_gyro_config.spi_work_mode = SPI_BLOCK_MODE; + // callbacks are all NULL + } + else if (config->work_mode == BMI088_BLOCK_TRIGGER_MODE) + { + config->spi_gyro_config.spi_work_mode = SPI_DMA_MODE; // 如果DMA资源不够,可以用SPI_IT_MODE + config->spi_gyro_config.spi_work_mode = SPI_DMA_MODE; + // 设置回调函数 + config->spi_acc_config.callback = BMI088AccSPIFinishCallback; + config->spi_gyro_config.callback = BMI088GyroSPIFinishCallback; + config->acc_int_config.gpio_model_callback = BMI088AccINTCallback; + config->gyro_int_config.gpio_model_callback = BMI088GyroINTCallback; + bmi088_instance->acc_int = GPIORegister(&config->acc_int_config); // 只有在非阻塞模式下才需要注册中断 + bmi088_instance->gyro_int = GPIORegister(&config->gyro_int_config); + } // 注册实例 + bmi088_instance->spi_acc = SPIRegister(&config->spi_acc_config); + bmi088_instance->spi_gyro = SPIRegister(&config->spi_gyro_config); + bmi088_instance->heat_pwm = PWMRegister(&config->heat_pwm_config); + PIDInit(&bmi088_instance->heat_pid, &config->heat_pid_config); + + // 初始化acc和gyro + BMI088_ERORR_CODE_e error = BMI088_NO_ERROR; + do + { + error = BMI088_NO_ERROR; + error |= BMI088AccelInit(bmi088_instance); + error |= BMI088GyroInit(bmi088_instance); + // 可以增加try out times,超出次数则返回错误 + } while (error != 0); + + bmi088_instance->work_mode = BMI088_BLOCK_PERIODIC_MODE; // 临时设置为阻塞模式 + BMI088CalibrateIMU(bmi088_instance); // 标定acc和gyro + bmi088_instance->work_mode = config->work_mode; // 恢复工作模式 + + return bmi088_instance; +} diff --git a/modules/BMI088/bmi088.h b/modules/BMI088/bmi088.h new file mode 100644 index 0000000..1ed12da --- /dev/null +++ b/modules/BMI088/bmi088.h @@ -0,0 +1,116 @@ +#ifndef __BMI088_H__ // 防止重复包含 +#define __BMI088_H__ + +#include "bsp_spi.h" +#include "bsp_gpio.h" +#include "controller.h" +#include "bsp_pwm.h" +#include "stdint.h" + +// bmi088工作模式枚举 +typedef enum +{ + BMI088_BLOCK_PERIODIC_MODE = 0, // 阻塞模式,周期性读取 + BMI088_BLOCK_TRIGGER_MODE, // 阻塞模式,触发读取(中断) +} BMI088_Work_Mode_e; + +// bmi088标定方式枚举,若使用预设标定参数,注意修改预设参数 +typedef enum +{ + BMI088_CALIBRATE_ONLINE_MODE = 0, // 初始化时进行标定 + BMI088_LOAD_PRE_CALI_MODE, // 使用预设标定参数, +} BMI088_Calibrate_Mode_e; + +#pragma pack(1) // 1字节对齐 +/* BMI088数据*/ +typedef struct +{ + float gyro[3]; // 陀螺仪数据,xyz + float acc[3]; // 加速度计数据,xyz + float temperature; // 温度 + + // float timestamp; // 时间戳,单位为ms,用于计算两次采样的时间间隔,同时给视觉提供timeline + // uint32_t count; // 第count次采样,用于对齐时间戳 +} BMI088_Data_t; +#pragma pack() // 恢复默认对齐,需要传输的结构体务必开启1字节对齐 + +/* BMI088实例结构体定义 */ +typedef struct +{ + // 传输模式和工作模式控制 + BMI088_Work_Mode_e work_mode; + BMI088_Calibrate_Mode_e cali_mode; + // SPI接口 + SPIInstance *spi_gyro; // 注意,SPIInstnace内部也有一个GPIOInstance,用于控制片选CS + SPIInstance *spi_acc; // 注意,SPIInstnace内部也有一个GPIOInstance,用于控制片选CS + // EXTI GPIO,如果BMI088工作在中断模式,则需要配置中断引脚(有数据产生时触发解算) + GPIOInstance *gyro_int; + GPIOInstance *acc_int; + // 温度控制 + PIDInstance heat_pid; // 恒温PID + PWMInstance *heat_pwm; // 加热PWM + // IMU数据 + float gyro[3]; // 陀螺仪数据,xyz + float acc[3]; // 加速度计数据,xyz + float temperature; // 温度 + // 标定数据 + float gyro_offset[3]; // 陀螺仪零偏 + float gNorm; // 重力加速度模长,从标定获取 + float acc_coef; // 加速度计原始数据转换系数 + // 传感器灵敏度,用于计算实际值(regNdef.h中定义) + float BMI088_ACCEL_SEN; + float BMI088_GYRO_SEN; + // 用于计算两次采样的时间间隔 + uint32_t bias_dwt_cnt; + // 数据更新标志位 + struct // 位域,节省空间提高可读性 + { + uint8_t gyro : 1; // 1:有新数据,0:无新数据 + uint8_t acc : 1; + uint8_t temp : 1; + uint8_t gyro_overrun : 1; // 1:数据溢出,0:无溢出 + uint8_t acc_overrun : 1; + uint8_t temp_overrun : 1; + uint8_t imu_ready : 1; // 1:IMU数据准备好,0:IMU数据未准备好(gyro+acc) + // 后续可添加其他标志位,不够用可以扩充16or32,太多可以删 + } update_flag; +} BMI088Instance; + +/* BMI088初始化配置 */ +typedef struct +{ + BMI088_Work_Mode_e work_mode; + BMI088_Calibrate_Mode_e cali_mode; + SPI_Init_Config_s spi_gyro_config; + SPI_Init_Config_s spi_acc_config; + GPIO_Init_Config_s gyro_int_config; + GPIO_Init_Config_s acc_int_config; + PID_Init_Config_s heat_pid_config; + PWM_Init_Config_s heat_pwm_config; +} BMI088_Init_Config_s; + +/** + * @brief 初始化BMI088,返回BMI088实例指针 + * @note 一般一个开发板只有一个BMI088,所以这里就叫BMI088Init而不是Register + * + * @param config bmi088初始化配置 + * @return BMI088Instance* 实例指针 + */ +BMI088Instance *BMI088Register(BMI088_Init_Config_s *config); + +/** + * @brief 读取BMI088数据 + * @param bmi088 BMI088实例指针 + * @return BMI088_Data_t 读取到的数据 + */ +uint8_t BMI088Acquire(BMI088Instance *bmi088,BMI088_Data_t* data_store); + +/** + * @brief 标定传感器.BMI088在初始化的时候会调用此函数. 提供接口方便标定离线数据 + * @attention @todo 注意,当操作系统开始运行后,此函数会和INS_Task冲突.目前不允许在运行时调用此函数,后续加入标志位判断以提供运行时重新的标定功能 + * + * @param _bmi088 待标定的实例 + */ +void BMI088CalibrateIMU(BMI088Instance *_bmi088); + +#endif // !__BMI088_H__ \ No newline at end of file diff --git a/modules/BMI088/bmi088.md b/modules/BMI088/bmi088.md new file mode 100644 index 0000000..7dbd80f --- /dev/null +++ b/modules/BMI088/bmi088.md @@ -0,0 +1,98 @@ +# BMI088 + +## 示例 + +```c +BMI088_Init_Config_s imu_config = { + .spi_acc_config={ + .GPIOx=GPIOA, + .GPIOx=GPIO_PIN_4, + .spi_handle=&hspi1, + }, + .spi_gyro_config={ + .GPIOx=GPIOB, + .GPIOx=GPIO_PIN_0, + .spi_handle=&hspi1, + }, + .acc_int_config={ + .exti_mode=EXTI_TRIGGER_FALLING, + .GPIO_Pin=GPIO_PIN_4, + .GPIOx=GPIOC, + }, + .gyro_int_config={ + .exti_mode=EXTI_TRIGGER_FALLING, + .GPIO_Pin=GPIO_PIN_5, + .GPIOx=GPIOC, + }, + .heat_pid_config={ + .Kp=0.0f, + .Kd=0.0f, + .Ki=0.0f, + .MaxOut=0.0f, + .DeadBand=0.0f, + }, + .heat_pwm_config={ + .channel=TIM_CHANNEL_1, + .htim=&htim1, + }, + .cali_mode=BMI088_CALIBRATE_ONLINE_MODE, + .work_mode=BMI088_BLOCK_PERIODIC_MODE, + }; + +BMI088Instance* imu=BMI088Register(&imu_config); +``` + +## IT非阻塞模式下BMI088读取流程 + +数据准备完成标志位:`uint8_t BMI088_READY_FLAG` 总共8个位 也可以用位域可读性更高 + +1. 当accel int中断发生,开启DMA SPI传输,完成后将acc ready置位 +2. 当gyro int中断发生,开启DMA SPI传输,完成后将gyro ready置位 +3. 当温度数据中断(温度传感器在accel内部,也是accel int)发生,开启DMA传输,完成后将温度标志位置位 + +> 由于DMA传输非阻塞,启动传输后只有到传输完成时才会拉高片选结束SPI transfer,因此需要在callback中加入标志位置位的操作. +这可以通过条件编译完成. + +温度数据不需要和accel和gyro同步,它不参与姿态解算,可以不用管. + +当加速度数据和陀螺仪数据都准备完成之后,唤醒姿态解算任务INs_taSk,进行一次解算.唤醒可以通过软件开启EXTI中断,在中断中调用实时系统的vTaskNotifyFromISR()完成,也可以将任务ready标志位置位,当运行到对应位置时检查标志位判断是否要进行任务.时间间隔不是大问题,inS_TAsK中有dwt用于计算两次任务执行的间隔,它将会自动处理好bias的大小 + +`__HAL_GPIO_EXTI_GENERATE_SWIT()` `HAL_EXTI_GENERATE_SWI()` 可以触发软件中断 + +of course,两者的数据更新实际上可以异步进行,这里为了方便起见当两者数据都准备好以后再行融合 + +## 数据读写规则(so called 16-bit protocol) + +加速度计读取read: + +1. bit 0 :1 bit 1-7: reg address +2. dummy read,加速度计此时返回的数据无效 +3. 真正的数据从第三个字节开始. + +通过SPI传输三个字节(分三次) +byte1: 1(读)+7位寄存器地址 +byte2: 没用 +byte3: 读取到的数据 + +write写入: + +1. bit 0: 0 bit1-7: reg address +2. 要写入寄存器的数据(注意没有dummy byte) + +--- + +**注意,陀螺仪和加速度计的读取不同** + +陀螺仪gyro读取read: + +1. bit 0 :1 bit1-7: reg address +2. 读回的数据 + +通过SPI传输两个字节(分两次) +byte1: 1(读)+7位寄存器地址 +byte2: 读取到的数据 + +write写入: + +1. bit0 : 0 bit1-7 : reg address +2. 写入的数据 diff --git a/modules/BMI088/bmi088_regNdef.h b/modules/BMI088/bmi088_regNdef.h new file mode 100644 index 0000000..b108bc1 --- /dev/null +++ b/modules/BMI088/bmi088_regNdef.h @@ -0,0 +1,234 @@ +#ifndef BMI088REG_H +#define BMI088REG_H + +/*------- BMI088寄存器地址及其存放的内容-------*/ + +#define BMI088_ACC_CHIP_ID 0x00 // the register is " Who am I " +#define BMI088_ACC_CHIP_ID_VALUE 0x1E + +#define BMI088_ACC_ERR_REG 0x02 +#define BMI088_ACCEL_CONGIF_ERROR_SHFITS 0x2 +#define BMI088_ACCEL_CONGIF_ERROR (1 << BMI088_ACCEL_CONGIF_ERROR_SHFITS) +#define BMI088_FATAL_ERROR_SHFITS 0x0 +#define BMI088_FATAL_ERROR (1 << BMI088_FATAL_ERROR) + +#define BMI088_ACC_STATUS 0x03 +#define BMI088_ACCEL_DRDY_SHFITS 0x7 +#define BMI088_ACCEL_DRDY (1 << BMI088_ACCEL_DRDY_SHFITS) + +#define BMI088_ACCEL_XOUT_L 0x12 +#define BMI088_ACCEL_XOUT_M 0x13 +#define BMI088_ACCEL_YOUT_L 0x14 +#define BMI088_ACCEL_YOUT_M 0x15 +#define BMI088_ACCEL_ZOUT_L 0x16 +#define BMI088_ACCEL_ZOUT_M 0x17 + +#define BMI088_SENSORTIME_DATA_L 0x18 +#define BMI088_SENSORTIME_DATA_M 0x19 +#define BMI088_SENSORTIME_DATA_H 0x1A + +#define BMI088_ACC_INT_STAT_1 0x1D +#define BMI088_ACCEL_DRDY_INTERRUPT_SHFITS 0x7 +#define BMI088_ACCEL_DRDY_INTERRUPT (1 << BMI088_ACCEL_DRDY_INTERRUPT_SHFITS) + +#define BMI088_TEMP_M 0x22 + +#define BMI088_TEMP_L 0x23 + +#define BMI088_ACC_CONF 0x40 +#define BMI088_ACC_CONF_MUST_Set 0x80 +#define BMI088_ACC_BWP_SHFITS 0x4 +#define BMI088_ACC_OSR4 (0x0 << BMI088_ACC_BWP_SHFITS) +#define BMI088_ACC_OSR2 (0x1 << BMI088_ACC_BWP_SHFITS) +#define BMI088_ACC_NORMAL (0x2 << BMI088_ACC_BWP_SHFITS) + +#define BMI088_ACC_ODR_SHFITS 0x0 +#define BMI088_ACC_12_5_HZ (0x5 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_25_HZ (0x6 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_50_HZ (0x7 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_100_HZ (0x8 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_200_HZ (0x9 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_400_HZ (0xA << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_800_HZ (0xB << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_1600_HZ (0xC << BMI088_ACC_ODR_SHFITS) + +#define BMI088_ACC_RANGE 0x41 + +#define BMI088_ACC_RANGE_SHFITS 0x0 +#define BMI088_ACC_RANGE_3G (0x0 << BMI088_ACC_RANGE_SHFITS) +#define BMI088_ACC_RANGE_6G (0x1 << BMI088_ACC_RANGE_SHFITS) +#define BMI088_ACC_RANGE_12G (0x2 << BMI088_ACC_RANGE_SHFITS) +#define BMI088_ACC_RANGE_24G (0x3 << BMI088_ACC_RANGE_SHFITS) + +#define BMI088_INT1_IO_CTRL 0x53 +#define BMI088_ACC_INT1_IO_ENABLE_SHFITS 0x3 +#define BMI088_ACC_INT1_IO_ENABLE (0x1 << BMI088_ACC_INT1_IO_ENABLE_SHFITS) +#define BMI088_ACC_INT1_GPIO_MODE_SHFITS 0x2 +#define BMI088_ACC_INT1_GPIO_PP (0x0 << BMI088_ACC_INT1_GPIO_MODE_SHFITS) +#define BMI088_ACC_INT1_GPIO_OD (0x1 << BMI088_ACC_INT1_GPIO_MODE_SHFITS) +#define BMI088_ACC_INT1_GPIO_LVL_SHFITS 0x1 +#define BMI088_ACC_INT1_GPIO_LOW (0x0 << BMI088_ACC_INT1_GPIO_LVL_SHFITS) +#define BMI088_ACC_INT1_GPIO_HIGH (0x1 << BMI088_ACC_INT1_GPIO_LVL_SHFITS) + +#define BMI088_INT2_IO_CTRL 0x54 +#define BMI088_ACC_INT2_IO_ENABLE_SHFITS 0x3 +#define BMI088_ACC_INT2_IO_ENABLE (0x1 << BMI088_ACC_INT2_IO_ENABLE_SHFITS) +#define BMI088_ACC_INT2_GPIO_MODE_SHFITS 0x2 +#define BMI088_ACC_INT2_GPIO_PP (0x0 << BMI088_ACC_INT2_GPIO_MODE_SHFITS) +#define BMI088_ACC_INT2_GPIO_OD (0x1 << BMI088_ACC_INT2_GPIO_MODE_SHFITS) +#define BMI088_ACC_INT2_GPIO_LVL_SHFITS 0x1 +#define BMI088_ACC_INT2_GPIO_LOW (0x0 << BMI088_ACC_INT2_GPIO_LVL_SHFITS) +#define BMI088_ACC_INT2_GPIO_HIGH (0x1 << BMI088_ACC_INT2_GPIO_LVL_SHFITS) + +#define BMI088_INT_MAP_DATA 0x58 +#define BMI088_ACC_INT2_DRDY_INTERRUPT_SHFITS 0x6 +#define BMI088_ACC_INT2_DRDY_INTERRUPT (0x1 << BMI088_ACC_INT2_DRDY_INTERRUPT_SHFITS) +#define BMI088_ACC_INT1_DRDY_INTERRUPT_SHFITS 0x2 +#define BMI088_ACC_INT1_DRDY_INTERRUPT (0x1 << BMI088_ACC_INT1_DRDY_INTERRUPT_SHFITS) + +#define BMI088_ACC_SELF_TEST 0x6D +#define BMI088_ACC_SELF_TEST_OFF 0x00 +#define BMI088_ACC_SELF_TEST_POSITIVE_SIGNAL 0x0D +#define BMI088_ACC_SELF_TEST_NEGATIVE_SIGNAL 0x09 + +#define BMI088_ACC_PWR_CONF 0x7C +#define BMI088_ACC_PWR_SUSPEND_MODE 0x03 +#define BMI088_ACC_PWR_ACTIVE_MODE 0x00 + +#define BMI088_ACC_PWR_CTRL 0x7D +#define BMI088_ACC_ENABLE_ACC_OFF 0x00 +#define BMI088_ACC_ENABLE_ACC_ON 0x04 + +#define BMI088_ACC_SOFTRESET 0x7E +#define BMI088_ACC_SOFTRESET_VALUE 0xB6 + +#define BMI088_GYRO_CHIP_ID 0x00 +#define BMI088_GYRO_CHIP_ID_VALUE 0x0F + +#define BMI088_GYRO_X_L 0x02 +#define BMI088_GYRO_X_H 0x03 +#define BMI088_GYRO_Y_L 0x04 +#define BMI088_GYRO_Y_H 0x05 +#define BMI088_GYRO_Z_L 0x06 +#define BMI088_GYRO_Z_H 0x07 + +#define BMI088_GYRO_INT_STAT_1 0x0A +#define BMI088_GYRO_DYDR_SHFITS 0x7 +#define BMI088_GYRO_DYDR (0x1 << BMI088_GYRO_DYDR_SHFITS) + +#define BMI088_GYRO_RANGE 0x0F +#define BMI088_GYRO_RANGE_SHFITS 0x0 +#define BMI088_GYRO_2000 (0x0 << BMI088_GYRO_RANGE_SHFITS) +#define BMI088_GYRO_1000 (0x1 << BMI088_GYRO_RANGE_SHFITS) +#define BMI088_GYRO_500 (0x2 << BMI088_GYRO_RANGE_SHFITS) +#define BMI088_GYRO_250 (0x3 << BMI088_GYRO_RANGE_SHFITS) +#define BMI088_GYRO_125 (0x4 << BMI088_GYRO_RANGE_SHFITS) + +#define BMI088_GYRO_BANDWIDTH 0x10 +// the first num means Output data rate, the second num means bandwidth +#define BMI088_GYRO_BANDWIDTH_MUST_Set 0x80 +#define BMI088_GYRO_2000_532_HZ 0x00 +#define BMI088_GYRO_2000_230_HZ 0x01 +#define BMI088_GYRO_1000_116_HZ 0x02 +#define BMI088_GYRO_400_47_HZ 0x03 +#define BMI088_GYRO_200_23_HZ 0x04 +#define BMI088_GYRO_100_12_HZ 0x05 +#define BMI088_GYRO_200_64_HZ 0x06 +#define BMI088_GYRO_100_32_HZ 0x07 + +#define BMI088_GYRO_LPM1 0x11 +#define BMI088_GYRO_NORMAL_MODE 0x00 +#define BMI088_GYRO_SUSPEND_MODE 0x80 +#define BMI088_GYRO_DEEP_SUSPEND_MODE 0x20 + +#define BMI088_GYRO_SOFTRESET 0x14 +#define BMI088_GYRO_SOFTRESET_VALUE 0xB6 + +#define BMI088_GYRO_CTRL 0x15 +#define BMI088_DRDY_OFF 0x00 +#define BMI088_DRDY_ON 0x80 + +#define BMI088_GYRO_INT3_INT4_IO_CONF 0x16 +#define BMI088_GYRO_INT4_GPIO_MODE_SHFITS 0x3 +#define BMI088_GYRO_INT4_GPIO_PP (0x0 << BMI088_GYRO_INT4_GPIO_MODE_SHFITS) +#define BMI088_GYRO_INT4_GPIO_OD (0x1 << BMI088_GYRO_INT4_GPIO_MODE_SHFITS) +#define BMI088_GYRO_INT4_GPIO_LVL_SHFITS 0x2 +#define BMI088_GYRO_INT4_GPIO_LOW (0x0 << BMI088_GYRO_INT4_GPIO_LVL_SHFITS) +#define BMI088_GYRO_INT4_GPIO_HIGH (0x1 << BMI088_GYRO_INT4_GPIO_LVL_SHFITS) +#define BMI088_GYRO_INT3_GPIO_MODE_SHFITS 0x1 +#define BMI088_GYRO_INT3_GPIO_PP (0x0 << BMI088_GYRO_INT3_GPIO_MODE_SHFITS) +#define BMI088_GYRO_INT3_GPIO_OD (0x1 << BMI088_GYRO_INT3_GPIO_MODE_SHFITS) +#define BMI088_GYRO_INT3_GPIO_LVL_SHFITS 0x0 +#define BMI088_GYRO_INT3_GPIO_LOW (0x0 << BMI088_GYRO_INT3_GPIO_LVL_SHFITS) +#define BMI088_GYRO_INT3_GPIO_HIGH (0x1 << BMI088_GYRO_INT3_GPIO_LVL_SHFITS) + +#define BMI088_GYRO_INT3_INT4_IO_MAP 0x18 + +#define BMI088_GYRO_DRDY_IO_OFF 0x00 +#define BMI088_GYRO_DRDY_IO_INT3 0x01 +#define BMI088_GYRO_DRDY_IO_INT4 0x80 +#define BMI088_GYRO_DRDY_IO_BOTH (BMI088_GYRO_DRDY_IO_INT3 | BMI088_GYRO_DRDY_IO_INT4) + +#define BMI088_GYRO_SELF_TEST 0x3C +#define BMI088_GYRO_RATE_OK_SHFITS 0x4 +#define BMI088_GYRO_RATE_OK (0x1 << BMI088_GYRO_RATE_OK_SHFITS) +#define BMI088_GYRO_BIST_FAIL_SHFITS 0x2 +#define BMI088_GYRO_BIST_FAIL (0x1 << BMI088_GYRO_BIST_FAIL_SHFITS) +#define BMI088_GYRO_BIST_RDY_SHFITS 0x1 +#define BMI088_GYRO_BIST_RDY (0x1 << BMI088_GYRO_BIST_RDY_SHFITS) +#define BMI088_GYRO_TRIG_BIST_SHFITS 0x0 +#define BMI088_GYRO_TRIG_BIST (0x1 << BMI088_GYRO_TRIG_BIST_SHFITS) + +/* -------BMI088 配置和传感器灵敏度换算系数等------- */ + +#define BMI088_TEMP_FACTOR 0.125f +#define BMI088_TEMP_OFFSET 23.0f + +#define BMI088_WRITE_ACCEL_REG_NUM 6 +#define BMI088_WRITE_GYRO_REG_NUM 6 + +#define BMI088_GYRO_DATA_READY_BIT 0 +#define BMI088_ACCEL_DATA_READY_BIT 1 +#define BMI088_ACCEL_TEMP_DATA_READY_BIT 2 + +#define BMI088_LONG_DELAY_TIME 80 +#define BMI088_COM_WAIT_SENSOR_TIME 150 + +#define BMI088_ACCEL_IIC_ADDRESSE (0x18 << 1) +#define BMI088_GYRO_IIC_ADDRESSE (0x68 << 1) + +#define BMI088_ACCEL_3G_SEN 0.0008974358974f +#define BMI088_ACCEL_6G_SEN 0.00179443359375f +#define BMI088_ACCEL_12G_SEN 0.0035888671875f +#define BMI088_ACCEL_24G_SEN 0.007177734375f + +#define BMI088_GYRO_2000_SEN 0.00106526443603169529841533860381f +#define BMI088_GYRO_1000_SEN 0.00053263221801584764920766930190693f +#define BMI088_GYRO_500_SEN 0.00026631610900792382460383465095346f +#define BMI088_GYRO_250_SEN 0.00013315805450396191230191732547673f +#define BMI088_GYRO_125_SEN 0.000066579027251980956150958662738366f + +/* BMI088错误码枚举 */ +typedef enum +{ + BMI088_NO_ERROR = 0x00, + BMI088_ACC_PWR_CTRL_ERROR = 0x01, + BMI088_ACC_PWR_CONF_ERROR = 0x02, + BMI088_ACC_CONF_ERROR = 0x03, + BMI088_ACC_SELF_TEST_ERROR = 0x04, + BMI088_ACC_RANGE_ERROR = 0x05, + BMI088_INT1_IO_CTRL_ERROR = 0x06, + BMI088_INT_MAP_DATA_ERROR = 0x07, + BMI088_GYRO_RANGE_ERROR = 0x08, + BMI088_GYRO_BANDWIDTH_ERROR = 0x09, + BMI088_GYRO_LPM1_ERROR = 0x0A, + BMI088_GYRO_CTRL_ERROR = 0x0B, + BMI088_GYRO_INT3_INT4_IO_CONF_ERROR = 0x0C, + BMI088_GYRO_INT3_INT4_IO_MAP_ERROR = 0x0D, + + BMI088_SELF_TEST_ACCEL_ERROR = 0x80, + BMI088_SELF_TEST_GYRO_ERROR = 0x40, + BMI088_NO_SENSOR = 0xFF, +} BMI088_ERORR_CODE_e; + +#endif diff --git a/modules/TFminiPlus/tfminiplus.c b/modules/TFminiPlus/tfminiplus.c new file mode 100644 index 0000000..0b53f18 --- /dev/null +++ b/modules/TFminiPlus/tfminiplus.c @@ -0,0 +1,30 @@ +#include "tfminiplus.h" +#include "stdlib.h" +#include "bsp_dwt.h" + +static TFMiniInstance *tfmini; + +TFMiniInstance *TFMiniRegister(I2C_HandleTypeDef *hi2c) +{ + tfmini = (TFMiniInstance *)malloc(sizeof(TFMiniInstance)); + IIC_Init_Config_s conf = { + .handle = hi2c, + .dev_address = 0x10, + .id = tfmini, + .work_mode = IIC_BLOCK_MODE, + }; + tfmini->iic = IICRegister(&conf); + DWT_Delay(0.5); + return tfmini; +} + +float GetDistance(TFMiniInstance *tfmini) +{ + uint8_t cmd_buf[5] = {0x5A, 0x05, 0x00, 0x06, 0x65}; + IICTransmit(tfmini->iic, cmd_buf, 5, IIC_SEQ_RELEASE); + IICReceive(tfmini->iic, tfmini->buf, 11, IIC_SEQ_RELEASE); + tfmini->Mode = tfmini->buf[6]; + tfmini->Dist = (uint16_t)tfmini->buf[2] + (((uint16_t)tfmini->buf[3]) << 8); + tfmini->Strength = tfmini->buf[4] | (tfmini->buf[5] << 8); + return tfmini->Dist; +} diff --git a/modules/TFminiPlus/tfminiplus.h b/modules/TFminiPlus/tfminiplus.h new file mode 100644 index 0000000..62ed6b7 --- /dev/null +++ b/modules/TFminiPlus/tfminiplus.h @@ -0,0 +1,20 @@ +#ifndef __TFMINIPLUS_H__ +#define __TFMINIPLUS_H__ + +#include "stdint.h" +#include "bsp_iic.h" + +typedef struct +{ + IICInstance *iic; + uint8_t Mode; //= buf[6]; + uint16_t Dist; //= buf[2] | (buf[3] << 8); + uint32_t Strength; //= buf[4] | (buf[5] << 8); + uint8_t buf[9]; +} TFMiniInstance; + +TFMiniInstance *TFMiniRegister(I2C_HandleTypeDef *hi2c); + +float GetDistance(TFMiniInstance *tfmini); + +#endif diff --git a/modules/TFminiPlus/tfminiplus.md b/modules/TFminiPlus/tfminiplus.md new file mode 100644 index 0000000..b833bd8 --- /dev/null +++ b/modules/TFminiPlus/tfminiplus.md @@ -0,0 +1,3 @@ +# tfminiplus + +北醒激光单点激光雷达模块的简单实现。目前使用iic阻塞通信耗时和速度都太慢,需修改为中断读取,bsp_iic已经提供相应的接口。 \ No newline at end of file diff --git a/modules/alarm/buzzer.c b/modules/alarm/buzzer.c new file mode 100644 index 0000000..3051ee4 --- /dev/null +++ b/modules/alarm/buzzer.c @@ -0,0 +1,93 @@ +#include "bsp_pwm.h" +#include "buzzer.h" +#include "bsp_dwt.h" +#include "string.h" + +static PWMInstance *buzzer; +// static uint8_t idx; +static BuzzzerInstance *buzzer_list[BUZZER_DEVICE_CNT] = {0}; + +/** + * @brief 蜂鸣器初始化 + * + */ +void BuzzerInit() +{ + PWM_Init_Config_s buzzer_config = { + .htim = &htim4, + .channel = TIM_CHANNEL_3, + .dutyratio = 0, + .period = 0.001, + }; + buzzer = PWMRegister(&buzzer_config); +} + +BuzzzerInstance *BuzzerRegister(Buzzer_config_s *config) +{ + if (config->alarm_level > BUZZER_DEVICE_CNT) // 超过最大实例数,考虑增加或查看是否有内存泄漏 + while (1) + ; + BuzzzerInstance *buzzer_temp = (BuzzzerInstance *)malloc(sizeof(BuzzzerInstance)); + memset(buzzer_temp, 0, sizeof(BuzzzerInstance)); + + buzzer_temp->alarm_level = config->alarm_level; + buzzer_temp->loudness = config->loudness; + buzzer_temp->octave = config->octave; + buzzer_temp->alarm_state = ALARM_OFF; + + buzzer_list[config->alarm_level] = buzzer_temp; + return buzzer_temp; +} + +void AlarmSetStatus(BuzzzerInstance *buzzer, AlarmState_e state) +{ + buzzer->alarm_state = state; +} + +void BuzzerTask() +{ + BuzzzerInstance *buzz; + for (size_t i = 0; i < BUZZER_DEVICE_CNT; ++i) + { + buzz = buzzer_list[i]; + if (buzz->alarm_level > ALARM_LEVEL_LOW) + { + continue; + } + if (buzz->alarm_state == ALARM_OFF) + { + PWMSetDutyRatio(buzzer, 0); + } + else + { + PWMSetDutyRatio(buzzer, buzz->loudness); + switch (buzz->octave) + { + case OCTAVE_1: + PWMSetPeriod(buzzer, (float)1 / DoFreq); + break; + case OCTAVE_2: + PWMSetPeriod(buzzer, (float)1 / ReFreq); + break; + case OCTAVE_3: + PWMSetPeriod(buzzer, (float)1 / MiFreq); + break; + case OCTAVE_4: + PWMSetPeriod(buzzer, (float)1 / FaFreq); + break; + case OCTAVE_5: + PWMSetPeriod(buzzer, (float)1 / SoFreq); + break; + case OCTAVE_6: + PWMSetPeriod(buzzer, (float)1 / LaFreq); + break; + case OCTAVE_7: + PWMSetPeriod(buzzer, (float)1 / SiFreq); + break; + default: + break; + } + break; + } + } +} diff --git a/modules/alarm/buzzer.h b/modules/alarm/buzzer.h new file mode 100644 index 0000000..e63054c --- /dev/null +++ b/modules/alarm/buzzer.h @@ -0,0 +1,60 @@ +#ifndef BUZZER_H +#define BUZZER_H +#include "bsp_pwm.h" +#define BUZZER_DEVICE_CNT 5 + +#define DoFreq 523 +#define ReFreq 587 +#define MiFreq 659 +#define FaFreq 698 +#define SoFreq 784 +#define LaFreq 880 +#define SiFreq 988 + +typedef enum +{ + OCTAVE_1 = 0, + OCTAVE_2, + OCTAVE_3, + OCTAVE_4, + OCTAVE_5, + OCTAVE_6, + OCTAVE_7, + OCTAVE_8, +}octave_e; + +typedef enum +{ + ALARM_LEVEL_HIGH = 0, + ALARM_LEVEL_ABOVE_MEDIUM, + ALARM_LEVEL_MEDIUM, + ALARM_LEVEL_BELOW_MEDIUM, + ALARM_LEVEL_LOW, +}AlarmLevel_e; + +typedef enum +{ + ALARM_OFF = 0, + ALARM_ON, +}AlarmState_e; +typedef struct +{ + AlarmLevel_e alarm_level; + octave_e octave; + float loudness; +}Buzzer_config_s; + +typedef struct +{ + float loudness; + octave_e octave; + AlarmLevel_e alarm_level; + AlarmState_e alarm_state; +}BuzzzerInstance; + + +void BuzzerInit(); +void BuzzerTask(); +BuzzzerInstance *BuzzerRegister(Buzzer_config_s *config); +void AlarmSetStatus(BuzzzerInstance *buzzer, AlarmState_e state); +#endif // !BUZZER_H diff --git a/modules/alarm/buzzer.md b/modules/alarm/buzzer.md new file mode 100644 index 0000000..a1d02d0 --- /dev/null +++ b/modules/alarm/buzzer.md @@ -0,0 +1,20 @@ +# buzzer + +用于拉响蜂鸣器警报 + +## 使用范例 + +```c +Buzzer_config_s buzzer_config ={ + .alarm_level = ALARM_LEVEL_HIGH, //设置警报等级 同一状态下 高等级的响应 + .loudness= 0.4, //设置响度 + .octave= OCTAVE_1, // 设置音阶 + }; +robocmd_alarm = BuzzerRegister(&buzzer_config); + +AlarmSetStatus(robocmd_alarm, ALARM_ON); +AlarmSetStatus(robocmd_alarm, ALARM_OFF); + +``` + +@todo: 将音阶改为可供选择的搭配 如 Do Re Mi Fa So La Si 自由组合 用户只需输入字符串"DoReMi"即可 \ No newline at end of file diff --git a/modules/algorithm/QuaternionEKF.c b/modules/algorithm/QuaternionEKF.c new file mode 100644 index 0000000..27c06e5 --- /dev/null +++ b/modules/algorithm/QuaternionEKF.c @@ -0,0 +1,489 @@ +/** + ****************************************************************************** + * @file QuaternionEKF.c + * @author Wang Hongxi + * @version V1.2.0 + * @date 2022/3/8 + * @brief attitude update with gyro bias estimate and chi-square test + ****************************************************************************** + * @attention + * 1st order LPF transfer function: + * 1 + * ——————— + * as + 1 + * + ****************************************************************************** + */ +#include "QuaternionEKF.h" + +QEKF_INS_t QEKF_INS; + +const float IMU_QuaternionEKF_F[36] = {1, 0, 0, 0, 0, 0, + 0, 1, 0, 0, 0, 0, + 0, 0, 1, 0, 0, 0, + 0, 0, 0, 1, 0, 0, + 0, 0, 0, 0, 1, 0, + 0, 0, 0, 0, 0, 1}; +float IMU_QuaternionEKF_P[36] = {100000, 0.1, 0.1, 0.1, 0.1, 0.1, + 0.1, 100000, 0.1, 0.1, 0.1, 0.1, + 0.1, 0.1, 100000, 0.1, 0.1, 0.1, + 0.1, 0.1, 0.1, 100000, 0.1, 0.1, + 0.1, 0.1, 0.1, 0.1, 100, 0.1, + 0.1, 0.1, 0.1, 0.1, 0.1, 100}; +float IMU_QuaternionEKF_K[18]; +float IMU_QuaternionEKF_H[18]; + +static float invSqrt(float x); +static void IMU_QuaternionEKF_Observe(KalmanFilter_t *kf); +static void IMU_QuaternionEKF_F_Linearization_P_Fading(KalmanFilter_t *kf); +static void IMU_QuaternionEKF_SetH(KalmanFilter_t *kf); +static void IMU_QuaternionEKF_xhatUpdate(KalmanFilter_t *kf); + +/** + * @brief Quaternion EKF initialization and some reference value + * @param[in] process_noise1 quaternion process noise 10 + * @param[in] process_noise2 gyro bias process noise 0.001 + * @param[in] measure_noise accel measure noise 1000000 + * @param[in] lambda fading coefficient 0.9996 + * @param[in] lpf lowpass filter coefficient 0 + */ +void IMU_QuaternionEKF_Init(float* init_quaternion,float process_noise1, float process_noise2, float measure_noise, float lambda, float lpf) +{ + QEKF_INS.Initialized = 1; + QEKF_INS.Q1 = process_noise1; + QEKF_INS.Q2 = process_noise2; + QEKF_INS.R = measure_noise; + QEKF_INS.ChiSquareTestThreshold = 1e-8; + QEKF_INS.ConvergeFlag = 0; + QEKF_INS.ErrorCount = 0; + QEKF_INS.UpdateCount = 0; + if (lambda > 1) + { + lambda = 1; + } + QEKF_INS.lambda = lambda; + QEKF_INS.accLPFcoef = lpf; + + // 初始化矩阵维度信息 + Kalman_Filter_Init(&QEKF_INS.IMU_QuaternionEKF, 6, 0, 3); + Matrix_Init(&QEKF_INS.ChiSquare, 1, 1, (float *)QEKF_INS.ChiSquare_Data); + + // 姿态初始化 + for(int i = 0; i < 4; i++) + { + QEKF_INS.IMU_QuaternionEKF.xhat_data[i] = init_quaternion[i]; + } + + // 自定义函数初始化,用于扩展或增加kf的基础功能 + QEKF_INS.IMU_QuaternionEKF.User_Func0_f = IMU_QuaternionEKF_Observe; + QEKF_INS.IMU_QuaternionEKF.User_Func1_f = IMU_QuaternionEKF_F_Linearization_P_Fading; + QEKF_INS.IMU_QuaternionEKF.User_Func2_f = IMU_QuaternionEKF_SetH; + QEKF_INS.IMU_QuaternionEKF.User_Func3_f = IMU_QuaternionEKF_xhatUpdate; + + // 设定标志位,用自定函数替换kf标准步骤中的SetK(计算增益)以及xhatupdate(后验估计/融合) + QEKF_INS.IMU_QuaternionEKF.SkipEq3 = TRUE; + QEKF_INS.IMU_QuaternionEKF.SkipEq4 = TRUE; + + memcpy(QEKF_INS.IMU_QuaternionEKF.F_data, IMU_QuaternionEKF_F, sizeof(IMU_QuaternionEKF_F)); + memcpy(QEKF_INS.IMU_QuaternionEKF.P_data, IMU_QuaternionEKF_P, sizeof(IMU_QuaternionEKF_P)); +} + +/** + * @brief Quaternion EKF update + * @param[in] gyro x y z in rad/s + * @param[in] accel x y z in m/s² + * @param[in] update period in s + */ +void IMU_QuaternionEKF_Update(float gx, float gy, float gz, float ax, float ay, float az, float dt) +{ + // 0.5(Ohm-Ohm^bias)*deltaT,用于更新工作点处的状态转移F矩阵 + static float halfgxdt, halfgydt, halfgzdt; + static float accelInvNorm; + + /* F, number with * represent vals to be set + 0 1* 2* 3* 4 5 + 6* 7 8* 9* 10 11 + 12* 13* 14 15* 16 17 + 18* 19* 20* 21 22 23 + 24 25 26 27 28 29 + 30 31 32 33 34 35 + */ + QEKF_INS.dt = dt; + + QEKF_INS.Gyro[0] = gx - QEKF_INS.GyroBias[0]; + QEKF_INS.Gyro[1] = gy - QEKF_INS.GyroBias[1]; + QEKF_INS.Gyro[2] = gz - QEKF_INS.GyroBias[2]; + + // set F + halfgxdt = 0.5f * QEKF_INS.Gyro[0] * dt; + halfgydt = 0.5f * QEKF_INS.Gyro[1] * dt; + halfgzdt = 0.5f * QEKF_INS.Gyro[2] * dt; + + // 此部分设定状态转移矩阵F的左上角部分 4x4子矩阵,即0.5(Ohm-Ohm^bias)*deltaT,右下角有一个2x2单位阵已经初始化好了 + // 注意在predict步F的右上角是4x2的零矩阵,因此每次predict的时候都会调用memcpy用单位阵覆盖前一轮线性化后的矩阵 + memcpy(QEKF_INS.IMU_QuaternionEKF.F_data, IMU_QuaternionEKF_F, sizeof(IMU_QuaternionEKF_F)); + + QEKF_INS.IMU_QuaternionEKF.F_data[1] = -halfgxdt; + QEKF_INS.IMU_QuaternionEKF.F_data[2] = -halfgydt; + QEKF_INS.IMU_QuaternionEKF.F_data[3] = -halfgzdt; + + QEKF_INS.IMU_QuaternionEKF.F_data[6] = halfgxdt; + QEKF_INS.IMU_QuaternionEKF.F_data[8] = halfgzdt; + QEKF_INS.IMU_QuaternionEKF.F_data[9] = -halfgydt; + + QEKF_INS.IMU_QuaternionEKF.F_data[12] = halfgydt; + QEKF_INS.IMU_QuaternionEKF.F_data[13] = -halfgzdt; + QEKF_INS.IMU_QuaternionEKF.F_data[15] = halfgxdt; + + QEKF_INS.IMU_QuaternionEKF.F_data[18] = halfgzdt; + QEKF_INS.IMU_QuaternionEKF.F_data[19] = halfgydt; + QEKF_INS.IMU_QuaternionEKF.F_data[20] = -halfgxdt; + + // accel low pass filter,加速度过一下低通滤波平滑数据,降低撞击和异常的影响 + if (QEKF_INS.UpdateCount == 0) // 如果是第一次进入,需要初始化低通滤波 + { + QEKF_INS.Accel[0] = ax; + QEKF_INS.Accel[1] = ay; + QEKF_INS.Accel[2] = az; + } + QEKF_INS.Accel[0] = QEKF_INS.Accel[0] * QEKF_INS.accLPFcoef / (QEKF_INS.dt + QEKF_INS.accLPFcoef) + ax * QEKF_INS.dt / (QEKF_INS.dt + QEKF_INS.accLPFcoef); + QEKF_INS.Accel[1] = QEKF_INS.Accel[1] * QEKF_INS.accLPFcoef / (QEKF_INS.dt + QEKF_INS.accLPFcoef) + ay * QEKF_INS.dt / (QEKF_INS.dt + QEKF_INS.accLPFcoef); + QEKF_INS.Accel[2] = QEKF_INS.Accel[2] * QEKF_INS.accLPFcoef / (QEKF_INS.dt + QEKF_INS.accLPFcoef) + az * QEKF_INS.dt / (QEKF_INS.dt + QEKF_INS.accLPFcoef); + + // set z,单位化重力加速度向量 + accelInvNorm = invSqrt(QEKF_INS.Accel[0] * QEKF_INS.Accel[0] + QEKF_INS.Accel[1] * QEKF_INS.Accel[1] + QEKF_INS.Accel[2] * QEKF_INS.Accel[2]); + for (uint8_t i = 0; i < 3; ++i) + { + QEKF_INS.IMU_QuaternionEKF.MeasuredVector[i] = QEKF_INS.Accel[i] * accelInvNorm; // 用加速度向量更新量测值 + } + + // get body state + QEKF_INS.gyro_norm = 1.0f / invSqrt(QEKF_INS.Gyro[0] * QEKF_INS.Gyro[0] + + QEKF_INS.Gyro[1] * QEKF_INS.Gyro[1] + + QEKF_INS.Gyro[2] * QEKF_INS.Gyro[2]); + QEKF_INS.accl_norm = 1.0f / accelInvNorm; + + // 如果角速度小于阈值且加速度处于设定范围内,认为运动稳定,加速度可以用于修正角速度 + // 稍后在最后的姿态更新部分会利用StableFlag来确定 + if (QEKF_INS.gyro_norm < 0.3f && QEKF_INS.accl_norm > 9.8f - 0.5f && QEKF_INS.accl_norm < 9.8f + 0.5f) + { + QEKF_INS.StableFlag = 1; + } + else + { + QEKF_INS.StableFlag = 0; + } + + // set Q R,过程噪声和观测噪声矩阵 + QEKF_INS.IMU_QuaternionEKF.Q_data[0] = QEKF_INS.Q1 * QEKF_INS.dt; + QEKF_INS.IMU_QuaternionEKF.Q_data[7] = QEKF_INS.Q1 * QEKF_INS.dt; + QEKF_INS.IMU_QuaternionEKF.Q_data[14] = QEKF_INS.Q1 * QEKF_INS.dt; + QEKF_INS.IMU_QuaternionEKF.Q_data[21] = QEKF_INS.Q1 * QEKF_INS.dt; + QEKF_INS.IMU_QuaternionEKF.Q_data[28] = QEKF_INS.Q2 * QEKF_INS.dt; + QEKF_INS.IMU_QuaternionEKF.Q_data[35] = QEKF_INS.Q2 * QEKF_INS.dt; + QEKF_INS.IMU_QuaternionEKF.R_data[0] = QEKF_INS.R; + QEKF_INS.IMU_QuaternionEKF.R_data[4] = QEKF_INS.R; + QEKF_INS.IMU_QuaternionEKF.R_data[8] = QEKF_INS.R; + + // 调用kalman_filter.c封装好的函数,注意几个User_Funcx_f的调用 + Kalman_Filter_Update(&QEKF_INS.IMU_QuaternionEKF); + + // 获取融合后的数据,包括四元数和xy零飘值 + QEKF_INS.q[0] = QEKF_INS.IMU_QuaternionEKF.FilteredValue[0]; + QEKF_INS.q[1] = QEKF_INS.IMU_QuaternionEKF.FilteredValue[1]; + QEKF_INS.q[2] = QEKF_INS.IMU_QuaternionEKF.FilteredValue[2]; + QEKF_INS.q[3] = QEKF_INS.IMU_QuaternionEKF.FilteredValue[3]; + QEKF_INS.GyroBias[0] = QEKF_INS.IMU_QuaternionEKF.FilteredValue[4]; + QEKF_INS.GyroBias[1] = QEKF_INS.IMU_QuaternionEKF.FilteredValue[5]; + QEKF_INS.GyroBias[2] = 0; // 大部分时候z轴通天,无法观测yaw的漂移 + + // 利用四元数反解欧拉角 + QEKF_INS.Yaw = atan2f(2.0f * (QEKF_INS.q[0] * QEKF_INS.q[3] + QEKF_INS.q[1] * QEKF_INS.q[2]), 2.0f * (QEKF_INS.q[0] * QEKF_INS.q[0] + QEKF_INS.q[1] * QEKF_INS.q[1]) - 1.0f) * 57.295779513f; + QEKF_INS.Pitch = atan2f(2.0f * (QEKF_INS.q[0] * QEKF_INS.q[1] + QEKF_INS.q[2] * QEKF_INS.q[3]), 2.0f * (QEKF_INS.q[0] * QEKF_INS.q[0] + QEKF_INS.q[3] * QEKF_INS.q[3]) - 1.0f) * 57.295779513f; + QEKF_INS.Roll = asinf(-2.0f * (QEKF_INS.q[1] * QEKF_INS.q[3] - QEKF_INS.q[0] * QEKF_INS.q[2])) * 57.295779513f; + + // get Yaw total, yaw数据可能会超过360,处理一下方便其他功能使用(如小陀螺) + if (QEKF_INS.Yaw - QEKF_INS.YawAngleLast > 180.0f) + { + QEKF_INS.YawRoundCount--; + } + else if (QEKF_INS.Yaw - QEKF_INS.YawAngleLast < -180.0f) + { + QEKF_INS.YawRoundCount++; + } + QEKF_INS.YawTotalAngle = 360.0f * QEKF_INS.YawRoundCount + QEKF_INS.Yaw; + QEKF_INS.YawAngleLast = QEKF_INS.Yaw; + QEKF_INS.UpdateCount++; // 初始化低通滤波用,计数测试用 +} + +/** + * @brief 用于更新线性化后的状态转移矩阵F右上角的一个4x2分块矩阵,稍后用于协方差矩阵P的更新; + * 并对零漂的方差进行限制,防止过度收敛并限幅防止发散 + * + * @param kf + */ +static void IMU_QuaternionEKF_F_Linearization_P_Fading(KalmanFilter_t *kf) +{ + static float q0, q1, q2, q3; + static float qInvNorm; + + q0 = kf->xhatminus_data[0]; + q1 = kf->xhatminus_data[1]; + q2 = kf->xhatminus_data[2]; + q3 = kf->xhatminus_data[3]; + + // quaternion normalize + qInvNorm = invSqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3); + for (uint8_t i = 0; i < 4; ++i) + { + kf->xhatminus_data[i] *= qInvNorm; + } + /* F, number with * represent vals to be set + 0 1 2 3 4* 5* + 6 7 8 9 10* 11* + 12 13 14 15 16* 17* + 18 19 20 21 22* 23* + 24 25 26 27 28 29 + 30 31 32 33 34 35 + */ + // set F + kf->F_data[4] = q1 * QEKF_INS.dt / 2; + kf->F_data[5] = q2 * QEKF_INS.dt / 2; + + kf->F_data[10] = -q0 * QEKF_INS.dt / 2; + kf->F_data[11] = q3 * QEKF_INS.dt / 2; + + kf->F_data[16] = -q3 * QEKF_INS.dt / 2; + kf->F_data[17] = -q0 * QEKF_INS.dt / 2; + + kf->F_data[22] = q2 * QEKF_INS.dt / 2; + kf->F_data[23] = -q1 * QEKF_INS.dt / 2; + + // fading filter,防止零飘参数过度收敛 + kf->P_data[28] /= QEKF_INS.lambda; + kf->P_data[35] /= QEKF_INS.lambda; + + // 限幅,防止发散 + if (kf->P_data[28] > 10000) + { + kf->P_data[28] = 10000; + } + if (kf->P_data[35] > 10000) + { + kf->P_data[35] = 10000; + } +} + +/** + * @brief 在工作点处计算观测函数h(x)的Jacobi矩阵H + * + * @param kf + */ +static void IMU_QuaternionEKF_SetH(KalmanFilter_t *kf) +{ + static float doubleq0, doubleq1, doubleq2, doubleq3; + /* H + 0 1 2 3 4 5 + 6 7 8 9 10 11 + 12 13 14 15 16 17 + last two cols are zero + */ + // set H + doubleq0 = 2 * kf->xhatminus_data[0]; + doubleq1 = 2 * kf->xhatminus_data[1]; + doubleq2 = 2 * kf->xhatminus_data[2]; + doubleq3 = 2 * kf->xhatminus_data[3]; + + memset(kf->H_data, 0, sizeof_float * kf->zSize * kf->xhatSize); + + kf->H_data[0] = -doubleq2; + kf->H_data[1] = doubleq3; + kf->H_data[2] = -doubleq0; + kf->H_data[3] = doubleq1; + + kf->H_data[6] = doubleq1; + kf->H_data[7] = doubleq0; + kf->H_data[8] = doubleq3; + kf->H_data[9] = doubleq2; + + kf->H_data[12] = doubleq0; + kf->H_data[13] = -doubleq1; + kf->H_data[14] = -doubleq2; + kf->H_data[15] = doubleq3; +} + +/** + * @brief 利用观测值和先验估计得到最优的后验估计 + * 加入了卡方检验以判断融合加速度的条件是否满足 + * 同时引入发散保护保证恶劣工况下的必要量测更新 + * + * @param kf + */ +static void IMU_QuaternionEKF_xhatUpdate(KalmanFilter_t *kf) +{ + static float q0, q1, q2, q3; + + kf->MatStatus = Matrix_Transpose(&kf->H, &kf->HT); // z|x => x|z + kf->temp_matrix.numRows = kf->H.numRows; + kf->temp_matrix.numCols = kf->Pminus.numCols; + kf->MatStatus = Matrix_Multiply(&kf->H, &kf->Pminus, &kf->temp_matrix); // temp_matrix = H·P'(k) + kf->temp_matrix1.numRows = kf->temp_matrix.numRows; + kf->temp_matrix1.numCols = kf->HT.numCols; + kf->MatStatus = Matrix_Multiply(&kf->temp_matrix, &kf->HT, &kf->temp_matrix1); // temp_matrix1 = H·P'(k)·HT + kf->S.numRows = kf->R.numRows; + kf->S.numCols = kf->R.numCols; + kf->MatStatus = Matrix_Add(&kf->temp_matrix1, &kf->R, &kf->S); // S = H P'(k) HT + R + kf->MatStatus = Matrix_Inverse(&kf->S, &kf->temp_matrix1); // temp_matrix1 = inv(H·P'(k)·HT + R) + + q0 = kf->xhatminus_data[0]; + q1 = kf->xhatminus_data[1]; + q2 = kf->xhatminus_data[2]; + q3 = kf->xhatminus_data[3]; + + kf->temp_vector.numRows = kf->H.numRows; + kf->temp_vector.numCols = 1; + // 计算预测得到的重力加速度方向(通过姿态获取的) + kf->temp_vector_data[0] = 2 * (q1 * q3 - q0 * q2); + kf->temp_vector_data[1] = 2 * (q0 * q1 + q2 * q3); + kf->temp_vector_data[2] = q0 * q0 - q1 * q1 - q2 * q2 + q3 * q3; // temp_vector = h(xhat'(k)) + + // 计算预测值和各个轴的方向余弦 + for (uint8_t i = 0; i < 3; ++i) + { + QEKF_INS.OrientationCosine[i] = acosf(fabsf(kf->temp_vector_data[i])); + } + + // 利用加速度计数据修正 + kf->temp_vector1.numRows = kf->z.numRows; + kf->temp_vector1.numCols = 1; + kf->MatStatus = Matrix_Subtract(&kf->z, &kf->temp_vector, &kf->temp_vector1); // temp_vector1 = z(k) - h(xhat'(k)) + + // chi-square test,卡方检验 + kf->temp_matrix.numRows = kf->temp_vector1.numRows; + kf->temp_matrix.numCols = 1; + kf->MatStatus = Matrix_Multiply(&kf->temp_matrix1, &kf->temp_vector1, &kf->temp_matrix); // temp_matrix = inv(H·P'(k)·HT + R)·(z(k) - h(xhat'(k))) + kf->temp_vector.numRows = 1; + kf->temp_vector.numCols = kf->temp_vector1.numRows; + kf->MatStatus = Matrix_Transpose(&kf->temp_vector1, &kf->temp_vector); // temp_vector = z(k) - h(xhat'(k))' + kf->MatStatus = Matrix_Multiply(&kf->temp_vector, &kf->temp_matrix, &QEKF_INS.ChiSquare); + // rk is small,filter converged/converging + if (QEKF_INS.ChiSquare_Data[0] < 0.5f * QEKF_INS.ChiSquareTestThreshold) + { + QEKF_INS.ConvergeFlag = 1; + } + // rk is bigger than thre but once converged + if (QEKF_INS.ChiSquare_Data[0] > QEKF_INS.ChiSquareTestThreshold && QEKF_INS.ConvergeFlag) + { + if (QEKF_INS.StableFlag) + { + QEKF_INS.ErrorCount++; // 载体静止时仍无法通过卡方检验 + } + else + { + QEKF_INS.ErrorCount = 0; + } + + if (QEKF_INS.ErrorCount > 50) + { + // 滤波器发散 + QEKF_INS.ConvergeFlag = 0; + kf->SkipEq5 = FALSE; // step-5 is cov mat P updating + } + else + { + // 残差未通过卡方检验 仅预测 + // xhat(k) = xhat'(k) + // P(k) = P'(k) + memcpy(kf->xhat_data, kf->xhatminus_data, sizeof_float * kf->xhatSize); + memcpy(kf->P_data, kf->Pminus_data, sizeof_float * kf->xhatSize * kf->xhatSize); + kf->SkipEq5 = TRUE; // part5 is P updating + return; + } + } + else // if divergent or rk is not that big/acceptable,use adaptive gain + { + // scale adaptive,rk越小则增益越大,否则更相信预测值 + if (QEKF_INS.ChiSquare_Data[0] > 0.1f * QEKF_INS.ChiSquareTestThreshold && QEKF_INS.ConvergeFlag) + { + QEKF_INS.AdaptiveGainScale = (QEKF_INS.ChiSquareTestThreshold - QEKF_INS.ChiSquare_Data[0]) / (0.9f * QEKF_INS.ChiSquareTestThreshold); + } + else + { + QEKF_INS.AdaptiveGainScale = 1; + } + QEKF_INS.ErrorCount = 0; + kf->SkipEq5 = FALSE; + } + + // cal kf-gain K + kf->temp_matrix.numRows = kf->Pminus.numRows; + kf->temp_matrix.numCols = kf->HT.numCols; + kf->MatStatus = Matrix_Multiply(&kf->Pminus, &kf->HT, &kf->temp_matrix); // temp_matrix = P'(k)·HT + kf->MatStatus = Matrix_Multiply(&kf->temp_matrix, &kf->temp_matrix1, &kf->K); + + // implement adaptive + for (uint8_t i = 0; i < kf->K.numRows * kf->K.numCols; ++i) + { + kf->K_data[i] *= QEKF_INS.AdaptiveGainScale; + } + for (uint8_t i = 4; i < 6; ++i) + { + for (uint8_t j = 0; j < 3; ++j) + { + kf->K_data[i * 3 + j] *= QEKF_INS.OrientationCosine[i - 4] / 1.5707963f; // 1 rad + } + } + + kf->temp_vector.numRows = kf->K.numRows; + kf->temp_vector.numCols = 1; + kf->MatStatus = Matrix_Multiply(&kf->K, &kf->temp_vector1, &kf->temp_vector); // temp_vector = K(k)·(z(k) - H·xhat'(k)) + + // 零漂修正限幅,一般不会有过大的漂移 + if (QEKF_INS.ConvergeFlag) + { + for (uint8_t i = 4; i < 6; ++i) + { + if (kf->temp_vector.pData[i] > 1e-2f * QEKF_INS.dt) + { + kf->temp_vector.pData[i] = 1e-2f * QEKF_INS.dt; + } + if (kf->temp_vector.pData[i] < -1e-2f * QEKF_INS.dt) + { + kf->temp_vector.pData[i] = -1e-2f * QEKF_INS.dt; + } + } + } + + // 不修正yaw轴数据 + kf->temp_vector.pData[3] = 0; + kf->MatStatus = Matrix_Add(&kf->xhatminus, &kf->temp_vector, &kf->xhat); +} + +/** + * @brief EKF观测环节,其实就是把数据复制一下 + * + * @param kf kf类型定义 + */ +static void IMU_QuaternionEKF_Observe(KalmanFilter_t *kf) +{ + memcpy(IMU_QuaternionEKF_P, kf->P_data, sizeof(IMU_QuaternionEKF_P)); + memcpy(IMU_QuaternionEKF_K, kf->K_data, sizeof(IMU_QuaternionEKF_K)); + memcpy(IMU_QuaternionEKF_H, kf->H_data, sizeof(IMU_QuaternionEKF_H)); +} + +/** + * @brief 自定义1/sqrt(x),速度更快 + * + * @param x x + * @return float + */ +static float invSqrt(float x) +{ + float halfx = 0.5f * x; + float y = x; + long i = *(long *)&y; + i = 0x5f375a86 - (i >> 1); + y = *(float *)&i; + y = y * (1.5f - (halfx * y * y)); + return y; +} diff --git a/modules/algorithm/QuaternionEKF.h b/modules/algorithm/QuaternionEKF.h new file mode 100644 index 0000000..26ab0a9 --- /dev/null +++ b/modules/algorithm/QuaternionEKF.h @@ -0,0 +1,75 @@ +/** + ****************************************************************************** + * @file QuaternionEKF.h + * @author Wang Hongxi + * @version V1.2.0 + * @date 2022/3/8 + * @brief attitude update with gyro bias estimate and chi-square test + ****************************************************************************** + * @attention + * + ****************************************************************************** + */ +#ifndef _QUAT_EKF_H +#define _QUAT_EKF_H +#include "kalman_filter.h" + +/* boolean type definitions */ +#ifndef TRUE +#define TRUE 1 /**< boolean true */ +#endif + +#ifndef FALSE +#define FALSE 0 /**< boolean fails */ +#endif + +typedef struct +{ + uint8_t Initialized; + KalmanFilter_t IMU_QuaternionEKF; + uint8_t ConvergeFlag; + uint8_t StableFlag; + uint64_t ErrorCount; + uint64_t UpdateCount; + + float q[4]; // 四元数估计值 + float GyroBias[3]; // 陀螺仪零偏估计值 + + float Gyro[3]; + float Accel[3]; + + float OrientationCosine[3]; + + float accLPFcoef; + float gyro_norm; + float accl_norm; + float AdaptiveGainScale; + + float Roll; + float Pitch; + float Yaw; + + float YawTotalAngle; + + float Q1; // 四元数更新过程噪声 + float Q2; // 陀螺仪零偏过程噪声 + float R; // 加速度计量测噪声 + + float dt; // 姿态更新周期 + mat ChiSquare; + float ChiSquare_Data[1]; // 卡方检验检测函数 + float ChiSquareTestThreshold; // 卡方检验阈值 + float lambda; // 渐消因子 + + int16_t YawRoundCount; + + float YawAngleLast; +} QEKF_INS_t; + +extern QEKF_INS_t QEKF_INS; +extern float chiSquare; +extern float ChiSquareTestThreshold; +void IMU_QuaternionEKF_Init(float* init_quaternion,float process_noise1, float process_noise2, float measure_noise, float lambda, float lpf); +void IMU_QuaternionEKF_Update(float gx, float gy, float gz, float ax, float ay, float az, float dt); + +#endif diff --git a/modules/algorithm/algorithm.md b/modules/algorithm/algorithm.md new file mode 100644 index 0000000..d2007ad --- /dev/null +++ b/modules/algorithm/algorithm.md @@ -0,0 +1,29 @@ +# algorithms + +neozng1@hnu.edu.cn
+ +> TODO: +> 1. 实现麦轮和全向轮的速度解算 +> 2. 实现一些通用的滤波器,如指数平均,窗平均,低通等 + +## 总览和使用 + +module层的algorithm提供了一些供其他模块以及app的应用层使用的算法,包括: + +1. PID控制器`controller.h` +2. crc8 crc16循环冗余校验 +3. 卡尔曼滤波器`kalman_filter.h`,可以通过用户自定义函数配置为扩展卡尔曼滤波 +4. `LQR.h`,线性二次型调节器 +5. `QuaterninoEKF.h`,用于`ins_task`的四元数姿态解算和扩展卡尔曼滤波融合 +6. `user_lib.h`,一些通用的函数,包括限幅、数据类型转换、角度弧度转换、快速符号判断以及优化开方等功能。多个模块都会使用的、不好区分的函数可以放置于此 + +## 代码结构 + +.c 为算法的实现,.h为算法对外接口的头文件 + + + +在编写应用的时候,你基本不会使用这里的函数,或是修改其实现。 + +若发现bug或需要增加功能,联系组长讨论。 + diff --git a/modules/algorithm/controller.c b/modules/algorithm/controller.c new file mode 100644 index 0000000..7d35614 --- /dev/null +++ b/modules/algorithm/controller.c @@ -0,0 +1,208 @@ +/** + * @file controller.c + * @author wanghongxi + * @author modified by neozng + * @brief PID控制器定义 + * @version beta + * @date 2022-11-01 + * + * @copyrightCopyright (c) 2022 HNU YueLu EC all rights reserved + */ +#include "controller.h" +#include "memory.h" + +/* ----------------------------下面是pid优化环节的实现---------------------------- */ + +// 梯形积分 +static void f_Trapezoid_Intergral(PIDInstance *pid) +{ + // 计算梯形的面积,(上底+下底)*高/2 + pid->ITerm = pid->Ki * ((pid->Err + pid->Last_Err) / 2) * pid->dt; +} + +// 变速积分(误差小时积分作用更强) +static void f_Changing_Integration_Rate(PIDInstance *pid) +{ + if (pid->Err * pid->Iout > 0) + { + // 积分呈累积趋势 + if (abs(pid->Err) <= pid->CoefB) + return; // Full integral + if (abs(pid->Err) <= (pid->CoefA + pid->CoefB)) + pid->ITerm *= (pid->CoefA - abs(pid->Err) + pid->CoefB) / pid->CoefA; + else // 最大阈值,不使用积分 + pid->ITerm = 0; + } +} + +static void f_Integral_Limit(PIDInstance *pid) +{ + static float temp_Output, temp_Iout; + temp_Iout = pid->Iout + pid->ITerm; + temp_Output = pid->Pout + pid->Iout + pid->Dout; + if (abs(temp_Output) > pid->MaxOut) + { + if (pid->Err * pid->Iout > 0) // 积分却还在累积 + { + pid->ITerm = 0; // 当前积分项置零 + } + } + + if (temp_Iout > pid->IntegralLimit) + { + pid->ITerm = 0; + pid->Iout = pid->IntegralLimit; + } + if (temp_Iout < -pid->IntegralLimit) + { + pid->ITerm = 0; + pid->Iout = -pid->IntegralLimit; + } +} + +// 微分先行(仅使用反馈值而不计参考输入的微分) +static void f_Derivative_On_Measurement(PIDInstance *pid) +{ + pid->Dout = pid->Kd * (pid->Last_Measure - pid->Measure) / pid->dt; +} + +// 微分滤波(采集微分时,滤除高频噪声) +static void f_Derivative_Filter(PIDInstance *pid) +{ + pid->Dout = pid->Dout * pid->dt / (pid->Derivative_LPF_RC + pid->dt) + + pid->Last_Dout * pid->Derivative_LPF_RC / (pid->Derivative_LPF_RC + pid->dt); +} + +// 输出滤波 +static void f_Output_Filter(PIDInstance *pid) +{ + pid->Output = pid->Output * pid->dt / (pid->Output_LPF_RC + pid->dt) + + pid->Last_Output * pid->Output_LPF_RC / (pid->Output_LPF_RC + pid->dt); +} + +// 输出限幅 +static void f_Output_Limit(PIDInstance *pid) +{ + if (pid->Output > pid->MaxOut) + { + pid->Output = pid->MaxOut; + } + if (pid->Output < -(pid->MaxOut)) + { + pid->Output = -(pid->MaxOut); + } +} + +// 电机堵转检测 +static void f_PID_ErrorHandle(PIDInstance *pid) +{ + /*Motor Blocked Handle*/ + if (fabsf(pid->Output) < pid->MaxOut * 0.001f || fabsf(pid->Ref) < 0.0001f) + return; + + if ((fabsf(pid->Ref - pid->Measure) / fabsf(pid->Ref)) > 0.95f) + { + // Motor blocked counting + pid->ERRORHandler.ERRORCount++; + } + else + { + pid->ERRORHandler.ERRORCount = 0; + } + + if (pid->ERRORHandler.ERRORCount > 500) + { + // Motor blocked over 1000times + pid->ERRORHandler.ERRORType = PID_MOTOR_BLOCKED_ERROR; + } +} + +/* ---------------------------下面是PID的外部算法接口--------------------------- */ + +/** + * @brief 初始化PID,设置参数和启用的优化环节,将其他数据置零 + * + * @param pid PID实例 + * @param config PID初始化设置 + */ +void PIDInit(PIDInstance *pid, PID_Init_Config_s *config) +{ + // config的数据和pid的部分数据是连续且相同的的,所以可以直接用memcpy + // @todo: 不建议这样做,可扩展性差,不知道的开发者可能会误以为pid和config是同一个结构体 + // 后续修改为逐个赋值 + memset(pid, 0, sizeof(PIDInstance)); + // utilize the quality of struct that its memeory is continuous + memcpy(pid, config, sizeof(PID_Init_Config_s)); + // set rest of memory to 0 + DWT_GetDeltaT(&pid->DWT_CNT); +} + +/** + * @brief PID计算 + * @param[in] PID结构体 + * @param[in] 测量值 + * @param[in] 期望值 + * @retval 返回空 + */ +float PIDCalculate(PIDInstance *pid, float measure, float ref) +{ + // 堵转检测 + if (pid->Improve & PID_ErrorHandle) + f_PID_ErrorHandle(pid); + + pid->dt = DWT_GetDeltaT(&pid->DWT_CNT); // 获取两次pid计算的时间间隔,用于积分和微分 + + // 保存上次的测量值和误差,计算当前error + pid->Measure = measure; + pid->Ref = ref; + pid->Err = pid->Ref - pid->Measure; + + // 如果在死区外,则计算PID + if (abs(pid->Err) > pid->DeadBand) + { + // 基本的pid计算,使用位置式 + pid->Pout = pid->Kp * pid->Err; + pid->ITerm = pid->Ki * pid->Err * pid->dt; + pid->Dout = pid->Kd * (pid->Err - pid->Last_Err) / pid->dt; + + // 梯形积分 + if (pid->Improve & PID_Trapezoid_Intergral) + f_Trapezoid_Intergral(pid); + // 变速积分 + if (pid->Improve & PID_ChangingIntegrationRate) + f_Changing_Integration_Rate(pid); + // 微分先行 + if (pid->Improve & PID_Derivative_On_Measurement) + f_Derivative_On_Measurement(pid); + // 微分滤波器 + if (pid->Improve & PID_DerivativeFilter) + f_Derivative_Filter(pid); + // 积分限幅 + if (pid->Improve & PID_Integral_Limit) + f_Integral_Limit(pid); + + pid->Iout += pid->ITerm; // 累加积分 + pid->Output = pid->Pout + pid->Iout + pid->Dout; // 计算输出 + + // 输出滤波 + if (pid->Improve & PID_OutputFilter) + f_Output_Filter(pid); + + // 输出限幅 + f_Output_Limit(pid); + } + else // 进入死区, 则清空积分和输出 + { + pid->Output = 0; + pid->ITerm = 0; + } + + // 保存当前数据,用于下次计算 + pid->Last_Measure = pid->Measure; + pid->Last_Output = pid->Output; + pid->Last_Dout = pid->Dout; + pid->Last_Err = pid->Err; + pid->Last_ITerm = pid->ITerm; + + return pid->Output; +} \ No newline at end of file diff --git a/modules/algorithm/controller.h b/modules/algorithm/controller.h new file mode 100644 index 0000000..2a871ea --- /dev/null +++ b/modules/algorithm/controller.h @@ -0,0 +1,136 @@ +/** + ****************************************************************************** + * @file controller.h + * @author Wang Hongxi + * @version V1.1.3 + * @date 2021/7/3 + * @brief + ****************************************************************************** + * @attention + * + ****************************************************************************** + */ +#ifndef _CONTROLLER_H +#define _CONTROLLER_H + +#include "main.h" +#include "stdint.h" +#include "memory.h" +#include "stdlib.h" +#include "bsp_dwt.h" +#include "arm_math.h" +#include+ +#ifndef abs +#define abs(x) ((x > 0) ? x : -x) +#endif + +// PID 优化环节使能标志位,通过位与可以判断启用的优化环节;也可以改成位域的形式 +typedef enum +{ + PID_IMPROVE_NONE = 0b00000000, // 0000 0000 + PID_Integral_Limit = 0b00000001, // 0000 0001 + PID_Derivative_On_Measurement = 0b00000010, // 0000 0010 + PID_Trapezoid_Intergral = 0b00000100, // 0000 0100 + PID_Proportional_On_Measurement = 0b00001000, // 0000 1000 + PID_OutputFilter = 0b00010000, // 0001 0000 + PID_ChangingIntegrationRate = 0b00100000, // 0010 0000 + PID_DerivativeFilter = 0b01000000, // 0100 0000 + PID_ErrorHandle = 0b10000000, // 1000 0000 +} PID_Improvement_e; + +/* PID 报错类型枚举*/ +typedef enum errorType_e +{ + PID_ERROR_NONE = 0x00U, + PID_MOTOR_BLOCKED_ERROR = 0x01U +} ErrorType_e; + +typedef struct +{ + uint64_t ERRORCount; + ErrorType_e ERRORType; +} PID_ErrorHandler_t; + +/* PID结构体 */ +typedef struct +{ + //---------------------------------- init config block + // config parameter + float Kp; + float Ki; + float Kd; + float MaxOut; + float DeadBand; + + // improve parameter + PID_Improvement_e Improve; + float IntegralLimit; // 积分限幅 + float CoefA; // 变速积分 For Changing Integral + float CoefB; // 变速积分 ITerm = Err*((A-abs(err)+B)/A) when B<|err|> 8) ^ crc_tab16[(crc ^ (uint16_t)*ptr++) & 0x00FF]; + } + return crc; +} + +/* + * uint16_t crc_modbus( const unsigned char *input_str, size_t num_bytes ); + * + *函数crc_modbus()一次计算16位modbus循环冗余校验 + *一个字节字符串,其开头已被传递给函数。这 + *要检查的字节数也是一个参数。 + */ + +uint16_t crc_modbus(const uint8_t *input_str, uint16_t num_bytes) +{ + uint16_t crc; + const uint8_t *ptr; + uint16_t a; + + if (!crc_tab16_init) + init_crc16_tab(); + + crc = CRC_START_MODBUS; + ptr = input_str; + if (ptr != NULL) + for (a = 0; a < num_bytes; a++) + { + + crc = (crc >> 8) ^ crc_tab16[(crc ^ (uint16_t)*ptr++) & 0x00FF]; + } + return crc; +} + +/* + * uint16_t update_crc_16( uint16_t crc, unsigned char c ); + * + *函数update_crc_16()根据 + *前一个循环冗余校验值和下一个要检查的数据字节。 + */ +uint16_t update_crc_16(uint16_t crc, uint8_t c) +{ + if (!crc_tab16_init) + init_crc16_tab(); + return (crc >> 8) ^ crc_tab16[(crc ^ (uint16_t)c) & 0x00FF]; +} + +/* + * static void init_crc16_tab( void ); + * + *为了获得最佳性能,使用CRC16例程查找带有值的表 + *可以直接在异或算法中使用的算法。 + *查找表首次由init_crc16_tab()例程计算 + *调用循环冗余校验函数。 + */ +void init_crc16_tab(void) +{ + uint16_t i; + uint16_t j; + uint16_t crc; + uint16_t c; + for (i = 0; i < 256; i++) + { + crc = 0; + c = i; + for (j = 0; j < 8; j++) + { + if ((crc ^ c) & 0x0001) + crc = (crc >> 1) ^ CRC_POLY_16; + else + crc = crc >> 1; + c = c >> 1; + } + crc_tab16[i] = crc; + } + crc_tab16_init = 1; +} diff --git a/modules/algorithm/crc16.h b/modules/algorithm/crc16.h new file mode 100644 index 0000000..7baffd8 --- /dev/null +++ b/modules/algorithm/crc16.h @@ -0,0 +1,14 @@ +#ifndef __CRC16_H +#define __CRC16_H +#include "main.h" + +#define CRC_START_16 0xFFFF +#define CRC_START_MODBUS 0xFFFF +#define CRC_POLY_16 0xA001 + +uint16_t crc_16(const uint8_t *input_str, uint16_t num_bytes); +uint16_t crc_modbus(const uint8_t *input_str, uint16_t num_bytes); +uint16_t update_crc_16(uint16_t crc, uint8_t c); +void init_crc16_tab(void); + +#endif diff --git a/modules/algorithm/crc8.c b/modules/algorithm/crc8.c new file mode 100644 index 0000000..20fe5df --- /dev/null +++ b/modules/algorithm/crc8.c @@ -0,0 +1,61 @@ +#include "crc8.h" + +/* + * static uint8_t sht75_crc_table[]; + * + * The SHT75 humidity sensor is capable of calculating an 8 bit CRC checksum to + * ensure data integrity. The lookup table crc_table[] is used to recalculate + * the CRC. + */ +static uint8_t sht75_crc_table[] = + { + 0, 49, 98, 83, 196, 245, 166, 151, 185, 136, 219, 234, 125, 76, 31, 46, + 67, 114, 33, 16, 135, 182, 229, 212, 250, 203, 152, 169, 62, 15, 92, 109, + 134, 183, 228, 213, 66, 115, 32, 17, 63, 14, 93, 108, 251, 202, 153, 168, + 197, 244, 167, 150, 1, 48, 99, 82, 124, 77, 30, 47, 184, 137, 218, 235, + 61, 12, 95, 110, 249, 200, 155, 170, 132, 181, 230, 215, 64, 113, 34, 19, + 126, 79, 28, 45, 186, 139, 216, 233, 199, 246, 165, 148, 3, 50, 97, 80, + 187, 138, 217, 232, 127, 78, 29, 44, 2, 51, 96, 81, 198, 247, 164, 149, + 248, 201, 154, 171, 60, 13, 94, 111, 65, 112, 35, 18, 133, 180, 231, 214, + 122, 75, 24, 41, 190, 143, 220, 237, 195, 242, 161, 144, 7, 54, 101, 84, + 57, 8, 91, 106, 253, 204, 159, 174, 128, 177, 226, 211, 68, 117, 38, 23, + 252, 205, 158, 175, 56, 9, 90, 107, 69, 116, 39, 22, 129, 176, 227, 210, + 191, 142, 221, 236, 123, 74, 25, 40, 6, 55, 100, 85, 194, 243, 160, 145, + 71, 118, 37, 20, 131, 178, 225, 208, 254, 207, 156, 173, 58, 11, 88, 105, + 4, 53, 102, 87, 192, 241, 162, 147, 189, 140, 223, 238, 121, 72, 27, 42, + 193, 240, 163, 146, 5, 52, 103, 86, 120, 73, 26, 43, 188, 141, 222, 239, + 130, 179, 224, 209, 70, 119, 36, 21, 59, 10, 89, 104, 255, 206, 157, 172}; + +/* + * uint8_t crc_8( const unsigned char *input_str, size_t num_bytes ); + * + *函数crc_8()计算输入字符串的8位宽crc + *给定长度。 + */ +uint8_t crc_8(const uint8_t *input_str, uint16_t num_bytes) +{ + uint16_t a; + uint8_t crc; + const uint8_t *ptr; + + crc = CRC_START_8; + ptr = input_str; + if (ptr != NULL) + for (a = 0; a < num_bytes; a++) + { + crc = sht75_crc_table[(*ptr++) ^ crc]; + } + return crc; +} + +/* + * uint8_t update_crc_8( unsigned char crc, unsigned char val ); + * + *给定一个数据字节和循环冗余校验值的前一个值 + *update_crc_8()计算并返回数据的新的实际crc值 + */ + +uint8_t update_crc_8(uint8_t crc, uint8_t val) +{ + return sht75_crc_table[val ^ crc]; +} diff --git a/modules/algorithm/crc8.h b/modules/algorithm/crc8.h new file mode 100644 index 0000000..278c70f --- /dev/null +++ b/modules/algorithm/crc8.h @@ -0,0 +1,11 @@ +#ifndef __CRC8_H +#define __CRC8_H + +#include "main.h" + +#define CRC_START_8 0x00 + +uint8_t crc_8(const uint8_t *input_str, uint16_t num_bytes); +uint8_t update_crc_8(uint8_t crc, uint8_t val); + +#endif diff --git a/modules/algorithm/kalman_filter.c b/modules/algorithm/kalman_filter.c new file mode 100644 index 0000000..4f5460f --- /dev/null +++ b/modules/algorithm/kalman_filter.c @@ -0,0 +1,480 @@ +/** + ****************************************************************************** + * @file kalman filter.c + * @author Wang Hongxi + * @version V1.2.2 + * @date 2022/1/8 + * @brief C implementation of kalman filter + ****************************************************************************** + * @attention + * 该卡尔曼滤波器可以在传感器采样频率不同的情况下,动态调整矩阵H R和K的维数与数值。 + * This implementation of kalman filter can dynamically adjust dimension and + * value of matrix H R and K according to the measurement validity under any + * circumstance that the sampling rate of component sensors are different. + * + * 因此矩阵H和R的初始化会与矩阵P A和Q有所不同。另外的,在初始化量测向量z时需要额外写 + * 入传感器量测所对应的状态与这个量测的方式,详情请见例程 + * Therefore, the initialization of matrix P, F, and Q is sometimes different + * from that of matrices H R. when initialization. Additionally, the corresponding + * state and the method of the measurement should be provided when initializing + * measurement vector z. For more details, please see the example. + * + * 若不需要动态调整量测向量z,可简单将结构体中的Use_Auto_Adjustment初始化为0,并像初 + * 始化矩阵P那样用常规方式初始化z H R即可。 + * If automatic adjustment is not required, assign zero to the UseAutoAdjustment + * and initialize z H R in the normal way as matrix P. + * + * 要求量测向量z与控制向量u在传感器回调函数中更新。整数0意味着量测无效,即自上次卡尔曼 + * 滤波更新后无传感器数据更新。因此量测向量z与控制向量u会在卡尔曼滤波更新过程中被清零 + * MeasuredVector and ControlVector are required to be updated in the sensor + * callback function. Integer 0 in measurement vector z indicates the invalidity + * of current measurement, so MeasuredVector and ControlVector will be reset + * (to 0) during each update. + * + * 此外,矩阵P过度收敛后滤波器将难以再适应状态的缓慢变化,从而产生滤波估计偏差。该算法 + * 通过限制矩阵P最小值的方法,可有效抑制滤波器的过度收敛,详情请见例程。 + * Additionally, the excessive convergence of matrix P will make filter incapable + * of adopting the slowly changing state. This implementation can effectively + * suppress filter excessive convergence through boundary limiting for matrix P. + * For more details, please see the example. + * + * @example: + * x = + * | height | + * | velocity | + * |acceleration| + * + * KalmanFilter_t Height_KF; + * + * void INS_Task_Init(void) + * { + * static float P_Init[9] = + * { + * 10, 0, 0, + * 0, 30, 0, + * 0, 0, 10, + * }; + * static float F_Init[9] = + * { + * 1, dt, 0.5*dt*dt, + * 0, 1, dt, + * 0, 0, 1, + * }; + * static float Q_Init[9] = + * { + * 0.25*dt*dt*dt*dt, 0.5*dt*dt*dt, 0.5*dt*dt, + * 0.5*dt*dt*dt, dt*dt, dt, + * 0.5*dt*dt, dt, 1, + * }; + * + * // 设置最小方差 + * static float state_min_variance[3] = {0.03, 0.005, 0.1}; + * + * // 开启自动调整 + * Height_KF.UseAutoAdjustment = 1; + * + * // 气压测得高度 GPS测得高度 加速度计测得z轴运动加速度 + * static uint8_t measurement_reference[3] = {1, 1, 3} + * + * static float measurement_degree[3] = {1, 1, 1} + * // 根据measurement_reference与measurement_degree生成H矩阵如下(在当前周期全部测量数据有效情况下) + * |1 0 0| + * |1 0 0| + * |0 0 1| + * + * static float mat_R_diagonal_elements = {30, 25, 35} + * //根据mat_R_diagonal_elements生成R矩阵如下(在当前周期全部测量数据有效情况下) + * |30 0 0| + * | 0 25 0| + * | 0 0 35| + * + * Kalman_Filter_Init(&Height_KF, 3, 0, 3); + * + * // 设置矩阵值 + * memcpy(Height_KF.P_data, P_Init, sizeof(P_Init)); + * memcpy(Height_KF.F_data, F_Init, sizeof(F_Init)); + * memcpy(Height_KF.Q_data, Q_Init, sizeof(Q_Init)); + * memcpy(Height_KF.MeasurementMap, measurement_reference, sizeof(measurement_reference)); + * memcpy(Height_KF.MeasurementDegree, measurement_degree, sizeof(measurement_degree)); + * memcpy(Height_KF.MatR_DiagonalElements, mat_R_diagonal_elements, sizeof(mat_R_diagonal_elements)); + * memcpy(Height_KF.StateMinVariance, state_min_variance, sizeof(state_min_variance)); + * } + * + * void INS_Task(void const *pvParameters) + * { + * // 循环更新 + * Kalman_Filter_Update(&Height_KF); + * vTaskDelay(ts); + * } + * + * // 测量数据更新应按照以下形式 即向MeasuredVector赋值 + * void Barometer_Read_Over(void) + * { + * ...... + * INS_KF.MeasuredVector[0] = baro_height; + * } + * void GPS_Read_Over(void) + * { + * ...... + * INS_KF.MeasuredVector[1] = GPS_height; + * } + * void Acc_Data_Process(void) + * { + * ...... + * INS_KF.MeasuredVector[2] = acc.z; + * } + ****************************************************************************** + */ + +#include "kalman_filter.h" + +uint16_t sizeof_float, sizeof_double; + +static void H_K_R_Adjustment(KalmanFilter_t *kf); + +/** + * @brief 初始化矩阵维度信息并为矩阵分配空间 + * + * @param kf kf类型定义 + * @param xhatSize 状态变量维度 + * @param uSize 控制变量维度 + * @param zSize 观测量维度 + */ +void Kalman_Filter_Init(KalmanFilter_t *kf, uint8_t xhatSize, uint8_t uSize, uint8_t zSize) +{ + sizeof_float = sizeof(float); + sizeof_double = sizeof(double); + + kf->xhatSize = xhatSize; + kf->uSize = uSize; + kf->zSize = zSize; + + kf->MeasurementValidNum = 0; + + // measurement flags + kf->MeasurementMap = (uint8_t *)user_malloc(sizeof(uint8_t) * zSize); + memset(kf->MeasurementMap, 0, sizeof(uint8_t) * zSize); + kf->MeasurementDegree = (float *)user_malloc(sizeof_float * zSize); + memset(kf->MeasurementDegree, 0, sizeof_float * zSize); + kf->MatR_DiagonalElements = (float *)user_malloc(sizeof_float * zSize); + memset(kf->MatR_DiagonalElements, 0, sizeof_float * zSize); + kf->StateMinVariance = (float *)user_malloc(sizeof_float * xhatSize); + memset(kf->StateMinVariance, 0, sizeof_float * xhatSize); + kf->temp = (uint8_t *)user_malloc(sizeof(uint8_t) * zSize); + memset(kf->temp, 0, sizeof(uint8_t) * zSize); + + // filter data + kf->FilteredValue = (float *)user_malloc(sizeof_float * xhatSize); + memset(kf->FilteredValue, 0, sizeof_float * xhatSize); + kf->MeasuredVector = (float *)user_malloc(sizeof_float * zSize); + memset(kf->MeasuredVector, 0, sizeof_float * zSize); + kf->ControlVector = (float *)user_malloc(sizeof_float * uSize); + memset(kf->ControlVector, 0, sizeof_float * uSize); + + // xhat x(k|k) + kf->xhat_data = (float *)user_malloc(sizeof_float * xhatSize); + memset(kf->xhat_data, 0, sizeof_float * xhatSize); + Matrix_Init(&kf->xhat, kf->xhatSize, 1, (float *)kf->xhat_data); + + // xhatminus x(k|k-1) + kf->xhatminus_data = (float *)user_malloc(sizeof_float * xhatSize); + memset(kf->xhatminus_data, 0, sizeof_float * xhatSize); + Matrix_Init(&kf->xhatminus, kf->xhatSize, 1, (float *)kf->xhatminus_data); + + if (uSize != 0) + { + // control vector u + kf->u_data = (float *)user_malloc(sizeof_float * uSize); + memset(kf->u_data, 0, sizeof_float * uSize); + Matrix_Init(&kf->u, kf->uSize, 1, (float *)kf->u_data); + } + + // measurement vector z + kf->z_data = (float *)user_malloc(sizeof_float * zSize); + memset(kf->z_data, 0, sizeof_float * zSize); + Matrix_Init(&kf->z, kf->zSize, 1, (float *)kf->z_data); + + // covariance matrix P(k|k) + kf->P_data = (float *)user_malloc(sizeof_float * xhatSize * xhatSize); + memset(kf->P_data, 0, sizeof_float * xhatSize * xhatSize); + Matrix_Init(&kf->P, kf->xhatSize, kf->xhatSize, (float *)kf->P_data); + + // create covariance matrix P(k|k-1) + kf->Pminus_data = (float *)user_malloc(sizeof_float * xhatSize * xhatSize); + memset(kf->Pminus_data, 0, sizeof_float * xhatSize * xhatSize); + Matrix_Init(&kf->Pminus, kf->xhatSize, kf->xhatSize, (float *)kf->Pminus_data); + + // state transition matrix F FT + kf->F_data = (float *)user_malloc(sizeof_float * xhatSize * xhatSize); + kf->FT_data = (float *)user_malloc(sizeof_float * xhatSize * xhatSize); + memset(kf->F_data, 0, sizeof_float * xhatSize * xhatSize); + memset(kf->FT_data, 0, sizeof_float * xhatSize * xhatSize); + Matrix_Init(&kf->F, kf->xhatSize, kf->xhatSize, (float *)kf->F_data); + Matrix_Init(&kf->FT, kf->xhatSize, kf->xhatSize, (float *)kf->FT_data); + + if (uSize != 0) + { + // control matrix B + kf->B_data = (float *)user_malloc(sizeof_float * xhatSize * uSize); + memset(kf->B_data, 0, sizeof_float * xhatSize * uSize); + Matrix_Init(&kf->B, kf->xhatSize, kf->uSize, (float *)kf->B_data); + } + + // measurement matrix H + kf->H_data = (float *)user_malloc(sizeof_float * zSize * xhatSize); + kf->HT_data = (float *)user_malloc(sizeof_float * xhatSize * zSize); + memset(kf->H_data, 0, sizeof_float * zSize * xhatSize); + memset(kf->HT_data, 0, sizeof_float * xhatSize * zSize); + Matrix_Init(&kf->H, kf->zSize, kf->xhatSize, (float *)kf->H_data); + Matrix_Init(&kf->HT, kf->xhatSize, kf->zSize, (float *)kf->HT_data); + + // process noise covariance matrix Q + kf->Q_data = (float *)user_malloc(sizeof_float * xhatSize * xhatSize); + memset(kf->Q_data, 0, sizeof_float * xhatSize * xhatSize); + Matrix_Init(&kf->Q, kf->xhatSize, kf->xhatSize, (float *)kf->Q_data); + + // measurement noise covariance matrix R + kf->R_data = (float *)user_malloc(sizeof_float * zSize * zSize); + memset(kf->R_data, 0, sizeof_float * zSize * zSize); + Matrix_Init(&kf->R, kf->zSize, kf->zSize, (float *)kf->R_data); + + // kalman gain K + kf->K_data = (float *)user_malloc(sizeof_float * xhatSize * zSize); + memset(kf->K_data, 0, sizeof_float * xhatSize * zSize); + Matrix_Init(&kf->K, kf->xhatSize, kf->zSize, (float *)kf->K_data); + + kf->S_data = (float *)user_malloc(sizeof_float * kf->xhatSize * kf->xhatSize); + kf->temp_matrix_data = (float *)user_malloc(sizeof_float * kf->xhatSize * kf->xhatSize); + kf->temp_matrix_data1 = (float *)user_malloc(sizeof_float * kf->xhatSize * kf->xhatSize); + kf->temp_vector_data = (float *)user_malloc(sizeof_float * kf->xhatSize); + kf->temp_vector_data1 = (float *)user_malloc(sizeof_float * kf->xhatSize); + Matrix_Init(&kf->S, kf->xhatSize, kf->xhatSize, (float *)kf->S_data); + Matrix_Init(&kf->temp_matrix, kf->xhatSize, kf->xhatSize, (float *)kf->temp_matrix_data); + Matrix_Init(&kf->temp_matrix1, kf->xhatSize, kf->xhatSize, (float *)kf->temp_matrix_data1); + Matrix_Init(&kf->temp_vector, kf->xhatSize, 1, (float *)kf->temp_vector_data); + Matrix_Init(&kf->temp_vector1, kf->xhatSize, 1, (float *)kf->temp_vector_data1); + + kf->SkipEq1 = 0; + kf->SkipEq2 = 0; + kf->SkipEq3 = 0; + kf->SkipEq4 = 0; + kf->SkipEq5 = 0; +} + +void Kalman_Filter_Measure(KalmanFilter_t *kf) +{ + // 矩阵H K R根据量测情况自动调整 + // matrix H K R auto adjustment + if (kf->UseAutoAdjustment != 0) + H_K_R_Adjustment(kf); + else + { + memcpy(kf->z_data, kf->MeasuredVector, sizeof_float * kf->zSize); + memset(kf->MeasuredVector, 0, sizeof_float * kf->zSize); + } + + memcpy(kf->u_data, kf->ControlVector, sizeof_float * kf->uSize); +} + +void Kalman_Filter_xhatMinusUpdate(KalmanFilter_t *kf) +{ + if (!kf->SkipEq1) + { + if (kf->uSize > 0) + { + kf->temp_vector.numRows = kf->xhatSize; + kf->temp_vector.numCols = 1; + kf->MatStatus = Matrix_Multiply(&kf->F, &kf->xhat, &kf->temp_vector); + kf->temp_vector1.numRows = kf->xhatSize; + kf->temp_vector1.numCols = 1; + kf->MatStatus = Matrix_Multiply(&kf->B, &kf->u, &kf->temp_vector1); + kf->MatStatus = Matrix_Add(&kf->temp_vector, &kf->temp_vector1, &kf->xhatminus); + } + else + { + kf->MatStatus = Matrix_Multiply(&kf->F, &kf->xhat, &kf->xhatminus); + } + } +} + +void Kalman_Filter_PminusUpdate(KalmanFilter_t *kf) +{ + if (!kf->SkipEq2) + { + kf->MatStatus = Matrix_Transpose(&kf->F, &kf->FT); + kf->MatStatus = Matrix_Multiply(&kf->F, &kf->P, &kf->Pminus); + kf->temp_matrix.numRows = kf->Pminus.numRows; + kf->temp_matrix.numCols = kf->FT.numCols; + kf->MatStatus = Matrix_Multiply(&kf->Pminus, &kf->FT, &kf->temp_matrix); // temp_matrix = F P(k-1) FT + kf->MatStatus = Matrix_Add(&kf->temp_matrix, &kf->Q, &kf->Pminus); + } +} +void Kalman_Filter_SetK(KalmanFilter_t *kf) +{ + if (!kf->SkipEq3) + { + kf->MatStatus = Matrix_Transpose(&kf->H, &kf->HT); // z|x => x|z + kf->temp_matrix.numRows = kf->H.numRows; + kf->temp_matrix.numCols = kf->Pminus.numCols; + kf->MatStatus = Matrix_Multiply(&kf->H, &kf->Pminus, &kf->temp_matrix); // temp_matrix = H·P'(k) + kf->temp_matrix1.numRows = kf->temp_matrix.numRows; + kf->temp_matrix1.numCols = kf->HT.numCols; + kf->MatStatus = Matrix_Multiply(&kf->temp_matrix, &kf->HT, &kf->temp_matrix1); // temp_matrix1 = H·P'(k)·HT + kf->S.numRows = kf->R.numRows; + kf->S.numCols = kf->R.numCols; + kf->MatStatus = Matrix_Add(&kf->temp_matrix1, &kf->R, &kf->S); // S = H P'(k) HT + R + kf->MatStatus = Matrix_Inverse(&kf->S, &kf->temp_matrix1); // temp_matrix1 = inv(H·P'(k)·HT + R) + kf->temp_matrix.numRows = kf->Pminus.numRows; + kf->temp_matrix.numCols = kf->HT.numCols; + kf->MatStatus = Matrix_Multiply(&kf->Pminus, &kf->HT, &kf->temp_matrix); // temp_matrix = P'(k)·HT + kf->MatStatus = Matrix_Multiply(&kf->temp_matrix, &kf->temp_matrix1, &kf->K); + } +} +void Kalman_Filter_xhatUpdate(KalmanFilter_t *kf) +{ + if (!kf->SkipEq4) + { + kf->temp_vector.numRows = kf->H.numRows; + kf->temp_vector.numCols = 1; + kf->MatStatus = Matrix_Multiply(&kf->H, &kf->xhatminus, &kf->temp_vector); // temp_vector = H xhat'(k) + kf->temp_vector1.numRows = kf->z.numRows; + kf->temp_vector1.numCols = 1; + kf->MatStatus = Matrix_Subtract(&kf->z, &kf->temp_vector, &kf->temp_vector1); // temp_vector1 = z(k) - H·xhat'(k) + kf->temp_vector.numRows = kf->K.numRows; + kf->temp_vector.numCols = 1; + kf->MatStatus = Matrix_Multiply(&kf->K, &kf->temp_vector1, &kf->temp_vector); // temp_vector = K(k)·(z(k) - H·xhat'(k)) + kf->MatStatus = Matrix_Add(&kf->xhatminus, &kf->temp_vector, &kf->xhat); + } +} +void Kalman_Filter_P_Update(KalmanFilter_t *kf) +{ + if (!kf->SkipEq5) + { + kf->temp_matrix.numRows = kf->K.numRows; + kf->temp_matrix.numCols = kf->H.numCols; + kf->temp_matrix1.numRows = kf->temp_matrix.numRows; + kf->temp_matrix1.numCols = kf->Pminus.numCols; + kf->MatStatus = Matrix_Multiply(&kf->K, &kf->H, &kf->temp_matrix); // temp_matrix = K(k)·H + kf->MatStatus = Matrix_Multiply(&kf->temp_matrix, &kf->Pminus, &kf->temp_matrix1); // temp_matrix1 = K(k)·H·P'(k) + kf->MatStatus = Matrix_Subtract(&kf->Pminus, &kf->temp_matrix1, &kf->P); + } +} + +/** + * @brief 执行卡尔曼滤波黄金五式,提供了用户定义函数,可以替代五个中的任意一个环节,方便自行扩展为EKF/UKF/ESKF/AUKF等 + * + * @param kf kf类型定义 + * @return float* 返回滤波值 + */ +float *Kalman_Filter_Update(KalmanFilter_t *kf) +{ + // 0. 获取量测信息 + Kalman_Filter_Measure(kf); + if (kf->User_Func0_f != NULL) + kf->User_Func0_f(kf); + + // 先验估计 + // 1. xhat'(k)= A·xhat(k-1) + B·u + Kalman_Filter_xhatMinusUpdate(kf); + if (kf->User_Func1_f != NULL) + kf->User_Func1_f(kf); + + // 预测更新 + // 2. P'(k) = A·P(k-1)·AT + Q + Kalman_Filter_PminusUpdate(kf); + if (kf->User_Func2_f != NULL) + kf->User_Func2_f(kf); + + if (kf->MeasurementValidNum != 0 || kf->UseAutoAdjustment == 0) + { + // 量测更新 + // 3. K(k) = P'(k)·HT / (H·P'(k)·HT + R) + Kalman_Filter_SetK(kf); + + if (kf->User_Func3_f != NULL) + kf->User_Func3_f(kf); + + // 融合 + // 4. xhat(k) = xhat'(k) + K(k)·(z(k) - H·xhat'(k)) + Kalman_Filter_xhatUpdate(kf); + + if (kf->User_Func4_f != NULL) + kf->User_Func4_f(kf); + + // 修正方差 + // 5. P(k) = (1-K(k)·H)·P'(k) ==> P(k) = P'(k)-K(k)·H·P'(k) + Kalman_Filter_P_Update(kf); + } + else + { + // 无有效量测,仅预测 + // xhat(k) = xhat'(k) + // P(k) = P'(k) + memcpy(kf->xhat_data, kf->xhatminus_data, sizeof_float * kf->xhatSize); + memcpy(kf->P_data, kf->Pminus_data, sizeof_float * kf->xhatSize * kf->xhatSize); + } + + // 自定义函数,可以提供后处理等 + if (kf->User_Func5_f != NULL) + kf->User_Func5_f(kf); + + // 避免滤波器过度收敛 + // suppress filter excessive convergence + for (uint8_t i = 0; i < kf->xhatSize; ++i) + { + if (kf->P_data[i * kf->xhatSize + i] < kf->StateMinVariance[i]) + kf->P_data[i * kf->xhatSize + i] = kf->StateMinVariance[i]; + } + + memcpy(kf->FilteredValue, kf->xhat_data, sizeof_float * kf->xhatSize); + + if (kf->User_Func6_f != NULL) + kf->User_Func6_f(kf); + + return kf->FilteredValue; +} + +static void H_K_R_Adjustment(KalmanFilter_t *kf) +{ + kf->MeasurementValidNum = 0; + + memcpy(kf->z_data, kf->MeasuredVector, sizeof_float * kf->zSize); + memset(kf->MeasuredVector, 0, sizeof_float * kf->zSize); + + // 识别量测数据有效性并调整矩阵H R K + // recognize measurement validity and adjust matrices H R K + memset(kf->R_data, 0, sizeof_float * kf->zSize * kf->zSize); + memset(kf->H_data, 0, sizeof_float * kf->xhatSize * kf->zSize); + for (uint8_t i = 0; i < kf->zSize; ++i) + { + if (kf->z_data[i] != 0) + { + // 重构向量z + // rebuild vector z + kf->z_data[kf->MeasurementValidNum] = kf->z_data[i]; + kf->temp[kf->MeasurementValidNum] = i; + // 重构矩阵H + // rebuild matrix H + kf->H_data[kf->xhatSize * kf->MeasurementValidNum + kf->MeasurementMap[i] - 1] = kf->MeasurementDegree[i]; + kf->MeasurementValidNum++; + } + } + for (uint8_t i = 0; i < kf->MeasurementValidNum; ++i) + { + // 重构矩阵R + // rebuild matrix R + kf->R_data[i * kf->MeasurementValidNum + i] = kf->MatR_DiagonalElements[kf->temp[i]]; + } + + // 调整矩阵维数 + // adjust the dimensions of system matrices + kf->H.numRows = kf->MeasurementValidNum; + kf->H.numCols = kf->xhatSize; + kf->HT.numRows = kf->xhatSize; + kf->HT.numCols = kf->MeasurementValidNum; + kf->R.numRows = kf->MeasurementValidNum; + kf->R.numCols = kf->MeasurementValidNum; + kf->K.numRows = kf->xhatSize; + kf->K.numCols = kf->MeasurementValidNum; + kf->z.numRows = kf->MeasurementValidNum; +} diff --git a/modules/algorithm/kalman_filter.h b/modules/algorithm/kalman_filter.h new file mode 100644 index 0000000..dadf1ce --- /dev/null +++ b/modules/algorithm/kalman_filter.h @@ -0,0 +1,122 @@ +/** + ****************************************************************************** + * @file kalman filter.h + * @author Wang Hongxi + * @version V1.2.2 + * @date 2022/1/8 + * @brief + ****************************************************************************** + * @attention + * + ****************************************************************************** + */ +#ifndef __KALMAN_FILTER_H +#define __KALMAN_FILTER_H + +// cortex-m4 DSP lib +/* +#define __CC_ARM // Keil +#define ARM_MATH_CM4 +#define ARM_MATH_MATRIX_CHECK +#define ARM_MATH_ROUNDING +#define ARM_MATH_DSP // define in arm_math.h +*/ + +#include "stm32f407xx.h" +#include "arm_math.h" +//#include "dsp/matrix_functions.h" +#include "math.h" +#include "stdint.h" +#include "stdlib.h" + +#ifndef user_malloc +#ifdef _CMSIS_OS_H +#define user_malloc pvPortMalloc +#else +#define user_malloc malloc +#endif +#endif + +// 若运算速度不够,可以使用q31代替f32,但是精度会降低 +#define mat arm_matrix_instance_f32 +#define Matrix_Init arm_mat_init_f32 +#define Matrix_Add arm_mat_add_f32 +#define Matrix_Subtract arm_mat_sub_f32 +#define Matrix_Multiply arm_mat_mult_f32 +#define Matrix_Transpose arm_mat_trans_f32 +#define Matrix_Inverse arm_mat_inverse_f32 + +typedef struct kf_t +{ + float *FilteredValue; + float *MeasuredVector; + float *ControlVector; + + uint8_t xhatSize; + uint8_t uSize; + uint8_t zSize; + + uint8_t UseAutoAdjustment; + uint8_t MeasurementValidNum; + + uint8_t *MeasurementMap; // 量测与状态的关系 how measurement relates to the state + float *MeasurementDegree; // 测量值对应H矩阵元素值 elements of each measurement in H + float *MatR_DiagonalElements; // 量测方差 variance for each measurement + float *StateMinVariance; // 最小方差 避免方差过度收敛 suppress filter excessive convergence + uint8_t *temp; + + // 配合用户定义函数使用,作为标志位用于判断是否要跳过标准KF中五个环节中的任意一个 + uint8_t SkipEq1, SkipEq2, SkipEq3, SkipEq4, SkipEq5; + + // definiion of struct mat: rows & cols & pointer to vars + mat xhat; // x(k|k) + mat xhatminus; // x(k|k-1) + mat u; // control vector u + mat z; // measurement vector z + mat P; // covariance matrix P(k|k) + mat Pminus; // covariance matrix P(k|k-1) + mat F, FT; // state transition matrix F FT + mat B; // control matrix B + mat H, HT; // measurement matrix H + mat Q; // process noise covariance matrix Q + mat R; // measurement noise covariance matrix R + mat K; // kalman gain K + mat S, temp_matrix, temp_matrix1, temp_vector, temp_vector1; + + int8_t MatStatus; + + // 用户定义函数,可以替换或扩展基准KF的功能 + void (*User_Func0_f)(struct kf_t *kf); + void (*User_Func1_f)(struct kf_t *kf); + void (*User_Func2_f)(struct kf_t *kf); + void (*User_Func3_f)(struct kf_t *kf); + void (*User_Func4_f)(struct kf_t *kf); + void (*User_Func5_f)(struct kf_t *kf); + void (*User_Func6_f)(struct kf_t *kf); + + // 矩阵存储空间指针 + float *xhat_data, *xhatminus_data; + float *u_data; + float *z_data; + float *P_data, *Pminus_data; + float *F_data, *FT_data; + float *B_data; + float *H_data, *HT_data; + float *Q_data; + float *R_data; + float *K_data; + float *S_data, *temp_matrix_data, *temp_matrix_data1, *temp_vector_data, *temp_vector_data1; +} KalmanFilter_t; + +extern uint16_t sizeof_float, sizeof_double; + +void Kalman_Filter_Init(KalmanFilter_t *kf, uint8_t xhatSize, uint8_t uSize, uint8_t zSize); +void Kalman_Filter_Measure(KalmanFilter_t *kf); +void Kalman_Filter_xhatMinusUpdate(KalmanFilter_t *kf); +void Kalman_Filter_PminusUpdate(KalmanFilter_t *kf); +void Kalman_Filter_SetK(KalmanFilter_t *kf); +void Kalman_Filter_xhatUpdate(KalmanFilter_t *kf); +void Kalman_Filter_P_Update(KalmanFilter_t *kf); +float *Kalman_Filter_Update(KalmanFilter_t *kf); + +#endif //__KALMAN_FILTER_H diff --git a/modules/algorithm/user_lib.c b/modules/algorithm/user_lib.c new file mode 100644 index 0000000..5029109 --- /dev/null +++ b/modules/algorithm/user_lib.c @@ -0,0 +1,214 @@ +/** + ****************************************************************************** + * @file user_lib.c + * @author Wang Hongxi + * @author modified by neozng + * @version 0.2 beta + * @date 2021/2/18 + * @brief + ****************************************************************************** + * @attention + * + ****************************************************************************** + */ +#include "stdlib.h" +#include "memory.h" +#include "user_lib.h" +#include "math.h" +#include "main.h" + +#ifdef _CMSIS_OS_H +#define user_malloc pvPortMalloc +#else +#define user_malloc malloc +#endif + +void *zmalloc(size_t size) +{ + void *ptr = malloc(size); + memset(ptr, 0, size); + return ptr; +} + +// 快速开方 +float Sqrt(float x) +{ + float y; + float delta; + float maxError; + + if (x <= 0) + { + return 0; + } + + // initial guess + y = x / 2; + + // refine + maxError = x * 0.001f; + + do + { + delta = (y * y) - x; + y -= delta / (2 * y); + } while (delta > maxError || delta < -maxError); + + return y; +} + +// 绝对值限制 +float abs_limit(float num, float Limit) +{ + if (num > Limit) + { + num = Limit; + } + else if (num < -Limit) + { + num = -Limit; + } + return num; +} + +// 判断符号位 +float sign(float value) +{ + if (value >= 0.0f) + { + return 1.0f; + } + else + { + return -1.0f; + } +} + +// 浮点死区 +float float_deadband(float Value, float minValue, float maxValue) +{ + if (Value < maxValue && Value > minValue) + { + Value = 0.0f; + } + return Value; +} + +// 限幅函数 +float float_constrain(float Value, float minValue, float maxValue) +{ + if (Value < minValue) + return minValue; + else if (Value > maxValue) + return maxValue; + else + return Value; +} + +// 限幅函数 +int16_t int16_constrain(int16_t Value, int16_t minValue, int16_t maxValue) +{ + if (Value < minValue) + return minValue; + else if (Value > maxValue) + return maxValue; + else + return Value; +} + +// 循环限幅函数 +float loop_float_constrain(float Input, float minValue, float maxValue) +{ + if (maxValue < minValue) + { + return Input; + } + + if (Input > maxValue) + { + float len = maxValue - minValue; + while (Input > maxValue) + { + Input -= len; + } + } + else if (Input < minValue) + { + float len = maxValue - minValue; + while (Input < minValue) + { + Input += len; + } + } + return Input; +} + +// 弧度格式化为-PI~PI + +// 角度格式化为-180~180 +float theta_format(float Ang) +{ + return loop_float_constrain(Ang, -180.0f, 180.0f); +} + +int float_rounding(float raw) +{ + static int integer; + static float decimal; + integer = (int)raw; + decimal = raw - integer; + if (decimal > 0.5f) + integer++; + return integer; +} + +// 三维向量归一化 +float *Norm3d(float *v) +{ + float len = Sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); + v[0] /= len; + v[1] /= len; + v[2] /= len; + return v; +} + +// 计算模长 +float NormOf3d(float *v) +{ + return Sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]); +} + +// 三维向量叉乘v1 x v2 +void Cross3d(float *v1, float *v2, float *res) +{ + res[0] = v1[1] * v2[2] - v1[2] * v2[1]; + res[1] = v1[2] * v2[0] - v1[0] * v2[2]; + res[2] = v1[0] * v2[1] - v1[1] * v2[0]; +} + +// 三维向量点乘 +float Dot3d(float *v1, float *v2) +{ + return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; +} + +// 均值滤波,删除buffer中的最后一个元素,填入新的元素并求平均值 +float AverageFilter(float new_data, float *buf, uint8_t len) +{ + float sum = 0; + for (uint8_t i = 0; i < len - 1; i++) + { + buf[i] = buf[i + 1]; + sum += buf[i]; + } + buf[len - 1] = new_data; + sum += new_data; + return sum / len; +} + +void MatInit(mat *m, uint8_t row, uint8_t col) +{ + m->numCols = col; + m->numRows = row; + m->pData = (float *)zmalloc(row * col * sizeof(float)); +} diff --git a/modules/algorithm/user_lib.h b/modules/algorithm/user_lib.h new file mode 100644 index 0000000..0c62567 --- /dev/null +++ b/modules/algorithm/user_lib.h @@ -0,0 +1,138 @@ +/** + ****************************************************************************** + * @file user_lib.h + * @author Wang Hongxi + * @version V1.0.0 + * @date 2021/2/18 + * @brief + ****************************************************************************** + * @attention + * + ****************************************************************************** + */ +#ifndef _USER_LIB_H +#define _USER_LIB_H + +#include "stdint.h" +#include "main.h" +#include "cmsis_os.h" +#include "stm32f407xx.h" +#include "arm_math.h" + + +#ifndef user_malloc +#ifdef _CMSIS_OS_H +#define user_malloc pvPortMalloc +#else +#define user_malloc malloc +#endif +#endif + +#define msin(x) (arm_sin_f32(x)) +#define mcos(x) (arm_cos_f32(x)) + +typedef arm_matrix_instance_f32 mat; +// 若运算速度不够,可以使用q31代替f32,但是精度会降低 +#define MatAdd arm_mat_add_f32 +#define MatSubtract arm_mat_sub_f32 +#define MatMultiply arm_mat_mult_f32 +#define MatTranspose arm_mat_trans_f32 +#define MatInverse arm_mat_inverse_f32 +void MatInit(mat *m, uint8_t row, uint8_t col); + +/* boolean type definitions */ +#ifndef TRUE +#define TRUE 1 /**< boolean true */ +#endif + +#ifndef FALSE +#define FALSE 0 /**< boolean fails */ +#endif + +/* circumference ratio */ +#ifndef PI +#define PI 3.14159265354f +#endif + +#define VAL_LIMIT(val, min, max) \ + do \ + { \ + if ((val) <= (min)) \ + { \ + (val) = (min); \ + } \ + else if ((val) >= (max)) \ + { \ + (val) = (max); \ + } \ + } while (0) + +#define ANGLE_LIMIT_360(val, angle) \ + do \ + { \ + (val) = (angle) - (int)(angle); \ + (val) += (int)(angle) % 360; \ + } while (0) + +#define ANGLE_LIMIT_360_TO_180(val) \ + do \ + { \ + if ((val) > 180) \ + (val) -= 360; \ + } while (0) + +/** + * @brief 将±360以内的角度,限制角度在-180 ~ 180 + * + */ +#define ANGLE_LIMIT_360_TO_180_ABS(val) \ + do { \ + if ((val) > 180) \ + (val) -= 360; \ + if ((val) < -180) \ + (val) += 360; \ + } while (0) + +#define VAL_MIN(a, b) ((a) < (b) ? (a) : (b)) +#define VAL_MAX(a, b) ((a) > (b) ? (a) : (b)) + +/** + * @brief 返回一块干净的内�?,不过仍然需要强制转�?为你需要的类型 + * + * @param size 分配大小 + * @return void* + */ +void *zmalloc(size_t size); + +// ���ٿ��� +float Sqrt(float x); +// �������� +float abs_limit(float num, float Limit); +// �жϷ���λ +float sign(float value); +// �������� +float float_deadband(float Value, float minValue, float maxValue); +// ������ +float float_constrain(float Value, float minValue, float maxValue); +// ������ +int16_t int16_constrain(int16_t Value, int16_t minValue, int16_t maxValue); +// ѭ�������� +float loop_float_constrain(float Input, float minValue, float maxValue); +// �Ƕ� ���� 180 ~ -180 +float theta_format(float Ang); + +int float_rounding(float raw); + +float *Norm3d(float *v); + +float NormOf3d(float *v); + +void Cross3d(float *v1, float *v2, float *res); + +float Dot3d(float *v1, float *v2); + +float AverageFilter(float new_data, float *buf, uint8_t len); + +#define rad_format(Ang) loop_float_constrain((Ang), -PI, PI) + +#endif diff --git a/modules/can_comm/can_comm.c b/modules/can_comm/can_comm.c new file mode 100644 index 0000000..bb39c59 --- /dev/null +++ b/modules/can_comm/can_comm.c @@ -0,0 +1,134 @@ +#include "can_comm.h" +#include "memory.h" +#include "stdlib.h" +#include "crc8.h" +#include "bsp_dwt.h" +#include "bsp_log.h" + +/** + * @brief 重置CAN comm的接收状态和buffer + * + * @param ins 需要重置的实例 + */ +static void CANCommResetRx(CANCommInstance *ins) +{ + // 当前已经收到的buffer清零 + memset(ins->raw_recvbuf, 0, ins->cur_recv_len); + ins->recv_state = 0; // 接收状态重置 + ins->cur_recv_len = 0; // 当前已经收到的长度重置 +} + +/** + * @brief cancomm的接收回调函数 + * + * @param _instance + */ +static void CANCommRxCallback(CANInstance *_instance) +{ + CANCommInstance *comm = (CANCommInstance *)_instance->id; // 注意写法,将can instance的id强制转换为CANCommInstance*类型 + + /* 当前接收状态判断 */ + if (_instance->rx_buff[0] == CAN_COMM_HEADER && comm->recv_state == 0) // 之前尚未开始接收且此次包里第一个位置是帧头 + { + if (_instance->rx_buff[1] == comm->recv_data_len) // 如果这一包里的datalen也等于我们设定接收长度(这是因为暂时不支持动态包长) + { + comm->recv_state = 1; // 设置接收状态为1,说明已经开始接收 + } + else + return; // 直接跳过即可 + } + + if (comm->recv_state) // 已经收到过帧头 + { + // 如果已经接收到的长度加上当前一包的长度大于总buf len,说明接收错误 + if (comm->cur_recv_len + _instance->rx_len > comm->recv_buf_len) + { + CANCommResetRx(comm); + return; // 重置状态然后返回 + } + + // 直接把当前接收到的数据接到buffer后面 + memcpy(comm->raw_recvbuf + comm->cur_recv_len, _instance->rx_buff, _instance->rx_len); + comm->cur_recv_len += _instance->rx_len; + + // 收完这一包以后刚好等于总buf len,说明已经收完了 + if (comm->cur_recv_len == comm->recv_buf_len) + { + // 如果buff里本tail的位置等于CAN_COMM_TAIL + if (comm->raw_recvbuf[comm->recv_buf_len - 1] == CAN_COMM_TAIL) + { // 通过校验,复制数据到unpack_data中 + if (comm->raw_recvbuf[comm->recv_buf_len - 2] == crc_8(comm->raw_recvbuf + 2, comm->recv_data_len)) + { // 数据量大的话考虑使用DMA + memcpy(comm->unpacked_recv_data, comm->raw_recvbuf + 2, comm->recv_data_len); + comm->update_flag = 1; // 数据更新flag置为1 + DaemonReload(comm->comm_daemon); // 重载daemon,避免数据更新后一直不被读取而导致数据更新不及时 + } + } + CANCommResetRx(comm); + return; // 重置状态然后返回 + } + } +} + +static void CANCommLostCallback(void *cancomm) +{ + CANCommInstance *comm = (CANCommInstance *)cancomm; + CANCommResetRx(comm); + LOGWARNING("[can_comm] can comm rx[%d] lost, reset rx state.", &comm->can_ins->rx_id); +} + +CANCommInstance *CANCommInit(CANComm_Init_Config_s *comm_config) +{ + CANCommInstance *ins = (CANCommInstance *)malloc(sizeof(CANCommInstance)); + memset(ins, 0, sizeof(CANCommInstance)); + + ins->recv_data_len = comm_config->recv_data_len; + ins->recv_buf_len = comm_config->recv_data_len + CAN_COMM_OFFSET_BYTES; // head + datalen + crc8 + tail + ins->send_data_len = comm_config->send_data_len; + ins->send_buf_len = comm_config->send_data_len + CAN_COMM_OFFSET_BYTES; + ins->raw_sendbuf[0] = CAN_COMM_HEADER; // head,直接设置避免每次发送都要重新赋值,下面的tail同理 + ins->raw_sendbuf[1] = comm_config->send_data_len; // datalen + ins->raw_sendbuf[comm_config->send_data_len + CAN_COMM_OFFSET_BYTES - 1] = CAN_COMM_TAIL; + // can instance的设置 + comm_config->can_config.id = ins; // CANComm的实例指针作为CANInstance的id,回调函数中会用到 + comm_config->can_config.can_module_callback = CANCommRxCallback; + ins->can_ins = CANRegister(&comm_config->can_config); + + Daemon_Init_Config_s daemon_config = { + .callback = CANCommLostCallback, + .owner_id = (void *)ins, + .reload_count = comm_config->daemon_count, + }; + ins->comm_daemon = DaemonRegister(&daemon_config); + return ins; +} + +void CANCommSend(CANCommInstance *instance, uint8_t *data) +{ + static uint8_t crc8; + static uint8_t send_len; + // 将data copy到raw_sendbuf中,计算crc8 + memcpy(instance->raw_sendbuf + 2, data, instance->send_data_len); + crc8 = crc_8(data, instance->send_data_len); + instance->raw_sendbuf[2 + instance->send_data_len] = crc8; + + // CAN单次发送最大为8字节,如果超过8字节,需要分包发送 + for (size_t i = 0; i < instance->send_buf_len; i += 8) + { // 如果是最后一包,send len将会小于8,要修改CAN的txconf中的DLC位,调用bsp_can提供的接口即可 + send_len = instance->send_buf_len - i >= 8 ? 8 : instance->send_buf_len - i; + CANSetDLC(instance->can_ins, send_len); + memcpy(instance->can_ins->tx_buff, instance->raw_sendbuf + i, send_len); + CANTransmit(instance->can_ins, 1); + } +} + +void *CANCommGet(CANCommInstance *instance) +{ + instance->update_flag = 0; // 读取后将更新flag置为0 + return instance->unpacked_recv_data; +} + +uint8_t CANCommIsOnline(CANCommInstance *instance) +{ + return DaemonIsOnline(instance->comm_daemon); +} diff --git a/modules/can_comm/can_comm.h b/modules/can_comm/can_comm.h new file mode 100644 index 0000000..398bcb5 --- /dev/null +++ b/modules/can_comm/can_comm.h @@ -0,0 +1,92 @@ +/** + * @file can_comm.h + * @author Neo neozng1@hnu.edu.cn + * @brief 用于多机CAN通信的收发模块 + * @version 0.1 + * @date 2022-11-27 + * + * @copyright Copyright (c) 2022 HNUYueLu EC all rights reserved + * + */ +#ifndef CAN_COMM_H +#define CAN_COMM_H + +#include "bsp_can.h" +#include "daemon.h" + +#define MX_CAN_COMM_COUNT 4 // 注意均衡负载,一条总线上不要挂载过多的外设 + +#define CAN_COMM_MAX_BUFFSIZE 60 // 最大发送/接收字节数,如果不够可以增加此数值 +#define CAN_COMM_HEADER 's' // 帧头 +#define CAN_COMM_TAIL 'e' // 帧尾 +#define CAN_COMM_OFFSET_BYTES 4 // 's'+ datalen + 'e' + crc8 + +#pragma pack(1) +/* CAN comm 结构体, 拥有CAN comm的app应该包含一个CAN comm指针 */ +typedef struct +{ + CANInstance *can_ins; + /* 发送部分 */ + uint8_t send_data_len; // 发送数据长度 + uint8_t send_buf_len; // 发送缓冲区长度,为发送数据长度+帧头单包数据长度帧尾以及校验和(4) + uint8_t raw_sendbuf[CAN_COMM_MAX_BUFFSIZE + CAN_COMM_OFFSET_BYTES]; // 额外4个bytes保存帧头帧尾和校验和 + /* 接收部分 */ + uint8_t recv_data_len; // 接收数据长度 + uint8_t recv_buf_len; // 接收缓冲区长度,为接收数据长度+帧头单包数据长度帧尾以及校验和(4) + uint8_t raw_recvbuf[CAN_COMM_MAX_BUFFSIZE + CAN_COMM_OFFSET_BYTES]; // 额外4个bytes保存帧头帧尾和校验和 + uint8_t unpacked_recv_data[CAN_COMM_MAX_BUFFSIZE]; // 解包后的数据,调用CANCommGet()后cast成对应的类型通过指针读取即可 + /* 接收和更新标志位*/ + uint8_t recv_state; // 接收状态, + uint8_t cur_recv_len; // 当前已经接收到的数据长度(包括帧头帧尾datalen和校验和) + uint8_t update_flag; // 数据更新标志位,当接收到新数据时,会将此标志位置1,调用CANCommGet()后会将此标志位置0 + + DaemonInstance* comm_daemon; +} CANCommInstance; +#pragma pack() + +/* CAN comm 初始化结构体 */ +typedef struct +{ + CAN_Init_Config_s can_config; // CAN初始化结构体 + uint8_t send_data_len; // 发送数据长度 + uint8_t recv_data_len; // 接收数据长度 + + uint16_t daemon_count; // 守护进程计数,用于初始化守护进程 +} CANComm_Init_Config_s; + +/** + * @brief 初始化CANComm + * + * @param config CANComm初始化结构体 + * @return CANCommInstance* + */ +CANCommInstance *CANCommInit(CANComm_Init_Config_s *comm_config); + +/** + * @brief 通过CANComm发送数据 + * + * @param instance cancomm实例 + * @param data 注意此地址的有效数据长度需要和初始化时传入的datalen相同 + */ +void CANCommSend(CANCommInstance *instance, uint8_t *data); + +/** + * @brief 获取CANComm接收的数据,需要自己使用强制类型转换将返回的void指针转换成指定类型 + * + * @return void* 返回的数据指针 + * @attention 注意如果希望直接通过转换指针访问数据,如果数据是union或struct,要检查是否使用了pack(n) + * CANComm接收到的数据可以看作是pack(1)之后的,是连续存放的. + * 如果使用了pack(n)可能会导致数据错乱,并且无法使用强制类型转换通过memcpy直接访问,转而需要手动解包. + * 强烈建议通过CANComm传输的数据使用pack(1) + */ +void *CANCommGet(CANCommInstance *instance); + +/** + * @brief 检查CANComm是否在线 + * + * @param instance + * @return uint8_t + */ +uint8_t CANCommIsOnline(CANCommInstance *instance); + +#endif // !CAN_COMM_H \ No newline at end of file diff --git a/modules/can_comm/can_comm.md b/modules/can_comm/can_comm.md new file mode 100644 index 0000000..5ebe50e --- /dev/null +++ b/modules/can_comm/can_comm.md @@ -0,0 +1,140 @@ +# can_comm + + neozng1@hnu.edu.cn
+ +> TODO: +> +> 1. 对`CANCommGet()`进行修改,使得其可以返回数据是否更新的相关信息。 + +## 重要提醒 + +如果传输过程中出现多次丢包或长度校验不通过,尤其是传输长度较大的时候,请开启CAN的Auto Retransmission,并尝试修改CANComm实例的发送和接受ID(以提高在总线仲裁中的优先级)。 + +## 总览和封装说明 + +CAN comm是用于CAN多机通信的模块。你不需要关心实现的协议,**只需要传入你想发送/接收的结构体的长度**(通过`sizeof()`获取)即可。单帧发送长度目前限制为60字节,如果需要加长可以在`can_comm.h`中修改`CAN_COMM_MAX_BUFFSIZE`的定义值。注意CAN的负载以及使用此模块的发送频率,否则可能造成堵塞。 + +## 代码结构 + +.h中放置的是数据定义和外部接口,以及协议的定义和宏,.c中包含一些私有函数。 + +## 外部接口 + +```c +CANCommInstance *CANCommInit(CANComm_Init_Config_s* comm_config); +void CANCommSend(CANCommInstance *instance, uint8_t *data); +void *CANCommGet(CANCommInstance *instance); +uint8_t CANCommIsOnline(CANCommInstance *instance); +``` + +第一个函数将会初始化一个CANComm实例,返回其指针。使用CANComm进行通信的应用应该保存返回的指针。初始化需要传入一个初始化结构体。请在应用初始化的时候调用该函数。推荐的结构体配置方式如下: + +```c +/* 初始化结构体的定义 */ +typedef struct +{ + can_instance_config_s can_config; + uint8_t send_data_len; //发送数据长度 + uint8_t recv_data_len; //接收数据长度,两者请用sizeof获取 +} CANComm_Init_Config_s; + +CANComm_Init_Config_s cconfig = { + .can_config = { + .can_handle=&hcan1, + .tx_id=0x02, + .rx_id=0x03}, + .send_data_len = sizeof(your_data_structure), + .recv_data_len = sizeof(recv_data_structure) +}; +``` + +第二个函数将会通过CAN发送一帧数据。这里的“帧”不是CAN的一帧报文,而是你使用的数据。在CANComm初始化的时候,使用sizeof获得你要发送的数据的长度。调用此函数时,将你的数据结构或数据cast成`u8`类型的指针传入即可。==**特别注意,你的结构体需要使用预编译指令`#pragma pack(1)`以及`#pragma pack()`包裹**==,从而进行字节压缩而不进行字节对齐,如: + +```c +#pragma pack(1) +typedef struct +{ + uint8_t aa; + float bb; + double cc; + uint16_t dd; +} some_struct; +#pragma pack() +``` + +只有这样,这个结构体才不会进行padding扩充字节实现字节对齐。你可以尝试一下,如果不使用pack处理,上面的结构体将会占据18个字节以上的空间;开启pack后,会降低至15。更多关于字节对齐的内容,自行查询。 + +> 后期可能更新字节对齐和内存访问相关的教程。 + +`CANCommGet()`是获取来自CANComm接收到的数据的接口,返回值为一个void类型指针,你需要通过**强制类型转换**将其变为你设定的接收类型指针,然后就可以访问其数据了。 + +## 私有函数和变量 + +```c +static CANCommInstance *can_comm_instance[MX_CAN_COMM_COUNT] = {NULL}; +static uint8_t idx; +static void CANCommResetRx(CANCommInstance *ins); +static void CANCommRxCallback(can_instance *_instance); +``` + +第一个指针数组保存所有的can comm实例,从而在callback中区分不同实例。idx是初始化使用的索引,用于确定每个can comm实例指针存放的位置。 + +`CANCommResetRx()`在`CANCommRxCallback()`中多次被调用,用于清空接收缓冲区。 + +`CANCommRxCallback()`是CAN comm初始化can实例时的回调函数,用于can接收中断,进行协议解析。 + +## 使用范例 + +例如,这里要发送的数据是一个float,接收的数据是如下的`struct`,**==注意要使用pack==**: + +```c +#pragma pack(1) +struct test +{ + float aa; + float bb; + float cc; + uint16_t dd; +}; +#pragma pack() +``` + +初始化时设置如下: + +```c +CANComm_Init_Config_s cconfig = { + .can_config = { + .can_handle=&hcan1, + .tx_id=0x02, + .rx_id=0x03}, + .send_data_len = sizeof(float), + .recv_data_len = sizeof(struct test) +}; +CANCommInstance* ins = CANCommInit(&cconfig); +``` + +通过`CANCommGet()`并使用强制类型转换获得接收到的数据指针: + +```c +struct test* data_ptr=(struct test*)CANCommGet(ins) +``` + +发送通过`CANCommSend()`,建议使用强制类型转换: + +```c +float tx=114.514; +CANCommSend(ins, (uint8_t*)&tx); +``` + +## 接收解析流程 + +CAN comm的通信协议如下: + +| 帧头 | 数据长度 | 数据 | crc8校验 | 帧尾 | +| ----------- | -------- | ---------------- | -------- | ----------- | +| 's'(0x73) | 0~255 | 最大60(可修改) | 校验码 | 'e'(0x65) | +| 1-byte | 1-byte | n-byte | 1-byte | 1-byte | + +接收的流程见代码注释。 + +流程图如下: diff --git a/modules/daemon/daemon.c b/modules/daemon/daemon.c new file mode 100644 index 0000000..03021f8 --- /dev/null +++ b/modules/daemon/daemon.c @@ -0,0 +1,56 @@ +#include "daemon.h" +#include "bsp_dwt.h" // 后续通过定时器来计时? +#include "stdlib.h" +#include "memory.h" +#include "buzzer.h" + +// 用于保存所有的daemon instance +static DaemonInstance *daemon_instances[DAEMON_MX_CNT] = {NULL}; +static uint8_t idx; // 用于记录当前的daemon instance数量,配合回调使用 + +DaemonInstance *DaemonRegister(Daemon_Init_Config_s *config) +{ + DaemonInstance *instance = (DaemonInstance *)malloc(sizeof(DaemonInstance)); + memset(instance, 0, sizeof(DaemonInstance)); + + instance->owner_id = config->owner_id; + instance->reload_count = config->reload_count == 0 ? 100 : config->reload_count; // 默认值为100 + instance->callback = config->callback; + instance->temp_count = config->init_count == 0 ? 100 : config->init_count; // 默认值为100,初始计数 + + instance->temp_count = config->reload_count; + daemon_instances[idx++] = instance; + return instance; +} + +/* "喂狗"函数 */ +void DaemonReload(DaemonInstance *instance) +{ + instance->temp_count = instance->reload_count; +} + +uint8_t DaemonIsOnline(DaemonInstance *instance) +{ + return instance->temp_count > 0; +} + +void DaemonTask() +{ + DaemonInstance *dins; // 提高可读性同时降低访存开销 + for (size_t i = 0; i < idx; ++i) + { + + dins = daemon_instances[i]; + if (dins->temp_count > 0) // 如果计数器还有值,说明上一次喂狗后还没有超时,则计数器减一 + dins->temp_count--; + else if (dins->callback) // 等于零说明超时了,调用回调函数(如果有的话) + { + dins->callback(dins->owner_id); // module内可以将owner_id强制类型转换成自身类型从而调用特定module的offline callback + // @todo 为蜂鸣器/led等增加离线报警的功能,非常关键! + } + } +} +// (需要id的原因是什么?) 下面是copilot的回答! +// 需要id的原因是因为有些module可能有多个实例,而我们需要知道具体是哪个实例offline +// 如果只有一个实例,则可以不用id,直接调用callback即可 +// 比如: 有一个module叫做"电机",它有两个实例,分别是"电机1"和"电机2",那么我们调用电机的离线处理函数时就需要知道是哪个电机offline diff --git a/modules/daemon/daemon.h b/modules/daemon/daemon.h new file mode 100644 index 0000000..b4856d9 --- /dev/null +++ b/modules/daemon/daemon.h @@ -0,0 +1,62 @@ +#ifndef MONITOR_H +#define MONITOR_H + +#include "stdint.h" +#include "string.h" + +#define DAEMON_MX_CNT 64 + +/* 模块离线处理函数指针 */ +typedef void (*offline_callback)(void *); + +/* daemon结构体定义 */ +typedef struct daemon_ins +{ + uint16_t reload_count; // 重载值 + offline_callback callback; // 异常处理函数,当模块发生异常时会被调用 + + uint16_t temp_count; // 当前值,减为零说明模块离线或异常 + void *owner_id; // daemon实例的地址,初始化的时候填入 +} DaemonInstance; + +/* daemon初始化配置 */ +typedef struct +{ + uint16_t reload_count; // 实际上这是app唯一需要设置的值? + uint16_t init_count; // 上线等待时间,有些模块需要收到主控的指令才会反馈报文,或pc等需要开机时间 + offline_callback callback; // 异常处理函数,当模块发生异常时会被调用 + + void *owner_id; // id取拥有daemon的实例的地址,如DJIMotorInstance*,cast成void*类型 +} Daemon_Init_Config_s; + +/** + * @brief 注册一个daemon实例 + * + * @param config 初始化配置 + * @return DaemonInstance* 返回实例指针 + */ +DaemonInstance *DaemonRegister(Daemon_Init_Config_s *config); + +/** + * @brief 当模块收到新的数据或进行其他动作时,调用该函数重载temp_count,相当于"喂狗" + * + * @param instance daemon实例指针 + */ +void DaemonReload(DaemonInstance *instance); + +/** + * @brief 确认模块是否离线 + * + * @param instance daemon实例指针 + * @return uint8_t 若在线且工作正常,返回1;否则返回零. 后续根据异常类型和离线状态等进行优化. + */ +uint8_t DaemonIsOnline(DaemonInstance *instance); + +/** + * @brief 放入rtos中,会给每个daemon实例的temp_count按频率进行递减操作. + * 模块成功接受数据或成功操作则会重载temp_count的值为reload_count. + * + */ +void DaemonTask(); + +#endif // !MONITOR_H \ No newline at end of file diff --git a/modules/daemon/daemon.md b/modules/daemon/daemon.md new file mode 100644 index 0000000..103f77d --- /dev/null +++ b/modules/daemon/daemon.md @@ -0,0 +1,36 @@ +# daemon + +neozng1@hnu.edu.cn
+ +用于监测模块和应用运行情况的module(和官方代码中的deteck task作用相同) + +## 使用范例 + +要使用该module,则包含`daemon.h`的头文件,并在使用daemon的文件中保留一个daemon的指针。 + +初始化的时候,要传入以下参数: + +```c +typedef struct +{ + uint16_t reload_count; // 实际上这是app唯一需要设置的值? + offline_callback callback; // 异常处理函数,当模块发生异常时会被调用 + void *owner_id; // id取拥有daemon的实例的地址,如DJIMotorInstance*,cast成void*类型 +} Daemon_Init_Config_s; +``` + +`reload_count`是”喂狗“时的重载值,一般根据你希望的离线容许时间和模块接收数据/访问数据的频率确定。daemonTask递减计数器的频率是100hz(在HAL_N_Middlewares/Src/freertos.c中查看任务),你可以据此以及模块收到数据/操作的频率设置reload_count。 + +`daemon_task()`会在实时系统中以1kHz的频率运行,每次运行该任务,都会将所有daemon实例当前的count进行自减操作,当count减为零,则说明模块已经很久没有上线(处于deactivated状态,即没有收到数据,也没有进行其他读写操作)。 + +`offline_callback`是模块离线的回调函数,即当包含daemon的模块发生离线情况时,该函数会被调用以应对离线情况,如重启模块,重新初始化等。如果没有则传入`NULL`即可。 + +`owner_id`即模块取自身地址并通过强制类型转换化为`void*`类型,用于拥有多个实例的模块在`offline_callback`中区分自身。如多个电机都使用一个相同的`offline_callback`,那么在调用回调函数的时候就可以通过该指针来访问某个特定的电机。 + +> 这种方法也称作“parent pointer”,即**保存拥有指向自身的指针对象的地址**。这样就可以在特定的情况下通过自身来访问自己的父对象。 + + + +## 具体实现 + +即`DaemonTask()`,在操作系统中以1kHz运行。注释详细,请参见`daemon.c`。 \ No newline at end of file diff --git a/modules/encoder/encoder.md b/modules/encoder/encoder.md new file mode 100644 index 0000000..65a08e8 --- /dev/null +++ b/modules/encoder/encoder.md @@ -0,0 +1,6 @@ +# encoder + +提供对光电和霍尔磁编码器的支持. + +可能需要新增bsp_tim以提供period lapse和tim编码器计数的功能. + diff --git a/modules/general_def.h b/modules/general_def.h new file mode 100644 index 0000000..725e645 --- /dev/null +++ b/modules/general_def.h @@ -0,0 +1,17 @@ +#ifndef GENERAL_DEF_H +#define GENERAL_DEF_H + +// 一些module的通用数值型定义,注意条件macro兼容,一些宏可能在math.h中已经定义过了 + +#ifndef PI +#define PI 3.1415926535f +#endif +#define PI2 (PI * 2.0f) // 2 pi + +#define RAD_2_DEGREE 57.2957795f // 180/pi +#define DEGREE_2_RAD 0.01745329252f // pi/180 + +#define RPM_2_ANGLE_PER_SEC 6.0f // ×360°/60sec +#define RPM_2_RAD_PER_SEC 0.104719755f // ×2pi/60sec + +#endif // !GENERAL_DEF_H \ No newline at end of file diff --git a/modules/imu/BMI088Middleware.c b/modules/imu/BMI088Middleware.c new file mode 100644 index 0000000..b942e34 --- /dev/null +++ b/modules/imu/BMI088Middleware.c @@ -0,0 +1,29 @@ +#include "BMI088Middleware.h" +#include "main.h" + +SPI_HandleTypeDef *BMI088_SPI; + +void BMI088_ACCEL_NS_L(void) +{ + HAL_GPIO_WritePin(CS1_ACCEL_GPIO_Port, CS1_ACCEL_Pin, GPIO_PIN_RESET); +} +void BMI088_ACCEL_NS_H(void) +{ + HAL_GPIO_WritePin(CS1_ACCEL_GPIO_Port, CS1_ACCEL_Pin, GPIO_PIN_SET); +} + +void BMI088_GYRO_NS_L(void) +{ + HAL_GPIO_WritePin(CS1_GYRO_GPIO_Port, CS1_GYRO_Pin, GPIO_PIN_RESET); +} +void BMI088_GYRO_NS_H(void) +{ + HAL_GPIO_WritePin(CS1_GYRO_GPIO_Port, CS1_GYRO_Pin, GPIO_PIN_SET); +} + +uint8_t BMI088_read_write_byte(uint8_t txdata) +{ + uint8_t rx_data; + HAL_SPI_TransmitReceive(BMI088_SPI, &txdata, &rx_data, 1, 1000); + return rx_data; +} diff --git a/modules/imu/BMI088Middleware.h b/modules/imu/BMI088Middleware.h new file mode 100644 index 0000000..0866143 --- /dev/null +++ b/modules/imu/BMI088Middleware.h @@ -0,0 +1,32 @@ +#ifndef BMI088MIDDLEWARE_H +#define BMI088MIDDLEWARE_H + +#include "main.h" + +#define BMI088_USE_SPI +//#define BMI088_USE_IIC + +/* +#define CS1_ACCEL_GPIO_Port ACCEL_NSS_GPIO_Port +#define CS1_ACCEL_Pin ACCEL_NSS_Pin +#define CS1_GYRO_GPIO_Port GYRO_NSS_GPIO_Port +#define CS1_GYRO_Pin GYRO_NSS_Pin +*/ + + +#if defined(BMI088_USE_SPI) +extern void BMI088_ACCEL_NS_L(void); +extern void BMI088_ACCEL_NS_H(void); + +extern void BMI088_GYRO_NS_L(void); +extern void BMI088_GYRO_NS_H(void); + +extern uint8_t BMI088_read_write_byte(uint8_t reg); + +extern SPI_HandleTypeDef *BMI088_SPI; + +#elif defined(BMI088_USE_IIC) + +#endif + +#endif diff --git a/modules/imu/BMI088driver.c b/modules/imu/BMI088driver.c new file mode 100644 index 0000000..e681428 --- /dev/null +++ b/modules/imu/BMI088driver.c @@ -0,0 +1,405 @@ +#include "BMI088driver.h" +#include "BMI088reg.h" +#include "BMI088Middleware.h" +#include "bsp_dwt.h" +#include "bsp_log.h" +#include+ +#pragma message "this is a legacy support. test the new BMI088 module as soon as possible." + +float BMI088_ACCEL_SEN = BMI088_ACCEL_6G_SEN; +float BMI088_GYRO_SEN = BMI088_GYRO_2000_SEN; + +static uint8_t res = 0; +static uint8_t write_reg_num = 0; +static uint8_t error = BMI088_NO_ERROR; +float gyroDiff[3], gNormDiff; + +uint8_t caliOffset = 1; +int16_t caliCount = 0; + +IMU_Data_t BMI088; + +#if defined(BMI088_USE_SPI) + +#define BMI088_accel_write_single_reg(reg, data) \ + { \ + BMI088_ACCEL_NS_L(); \ + BMI088_write_single_reg((reg), (data)); \ + BMI088_ACCEL_NS_H(); \ + } +#define BMI088_accel_read_single_reg(reg, data) \ + { \ + BMI088_ACCEL_NS_L(); \ + BMI088_read_write_byte((reg) | 0x80); \ + BMI088_read_write_byte(0x55); \ + (data) = BMI088_read_write_byte(0x55); \ + BMI088_ACCEL_NS_H(); \ + } +#define BMI088_accel_read_muli_reg(reg, data, len) \ + { \ + BMI088_ACCEL_NS_L(); \ + BMI088_read_write_byte((reg) | 0x80); \ + BMI088_read_muli_reg(reg, data, len); \ + BMI088_ACCEL_NS_H(); \ + } + +#define BMI088_gyro_write_single_reg(reg, data) \ + { \ + BMI088_GYRO_NS_L(); \ + BMI088_write_single_reg((reg), (data)); \ + BMI088_GYRO_NS_H(); \ + } +#define BMI088_gyro_read_single_reg(reg, data) \ + { \ + BMI088_GYRO_NS_L(); \ + BMI088_read_single_reg((reg), &(data)); \ + BMI088_GYRO_NS_H(); \ + } +#define BMI088_gyro_read_muli_reg(reg, data, len) \ + { \ + BMI088_GYRO_NS_L(); \ + BMI088_read_muli_reg((reg), (data), (len)); \ + BMI088_GYRO_NS_H(); \ + } + +static void BMI088_write_single_reg(uint8_t reg, uint8_t data); +static void BMI088_read_single_reg(uint8_t reg, uint8_t *return_data); +static void BMI088_read_muli_reg(uint8_t reg, uint8_t *buf, uint8_t len); + +#elif defined(BMI088_USE_IIC) +#endif + +static uint8_t BMI088_Accel_Init_Table[BMI088_WRITE_ACCEL_REG_NUM][3] = + { + {BMI088_ACC_PWR_CTRL, BMI088_ACC_ENABLE_ACC_ON, BMI088_ACC_PWR_CTRL_ERROR}, + {BMI088_ACC_PWR_CONF, BMI088_ACC_PWR_ACTIVE_MODE, BMI088_ACC_PWR_CONF_ERROR}, + {BMI088_ACC_CONF, BMI088_ACC_NORMAL | BMI088_ACC_800_HZ | BMI088_ACC_CONF_MUST_Set, BMI088_ACC_CONF_ERROR}, + {BMI088_ACC_RANGE, BMI088_ACC_RANGE_6G, BMI088_ACC_RANGE_ERROR}, + {BMI088_INT1_IO_CTRL, BMI088_ACC_INT1_IO_ENABLE | BMI088_ACC_INT1_GPIO_PP | BMI088_ACC_INT1_GPIO_LOW, BMI088_INT1_IO_CTRL_ERROR}, + {BMI088_INT_MAP_DATA, BMI088_ACC_INT1_DRDY_INTERRUPT, BMI088_INT_MAP_DATA_ERROR} + +}; + +static uint8_t BMI088_Gyro_Init_Table[BMI088_WRITE_GYRO_REG_NUM][3] = + { + {BMI088_GYRO_RANGE, BMI088_GYRO_2000, BMI088_GYRO_RANGE_ERROR}, + {BMI088_GYRO_BANDWIDTH, BMI088_GYRO_2000_230_HZ | BMI088_GYRO_BANDWIDTH_MUST_Set, BMI088_GYRO_BANDWIDTH_ERROR}, + {BMI088_GYRO_LPM1, BMI088_GYRO_NORMAL_MODE, BMI088_GYRO_LPM1_ERROR}, + {BMI088_GYRO_CTRL, BMI088_DRDY_ON, BMI088_GYRO_CTRL_ERROR}, + {BMI088_GYRO_INT3_INT4_IO_CONF, BMI088_GYRO_INT3_GPIO_PP | BMI088_GYRO_INT3_GPIO_LOW, BMI088_GYRO_INT3_INT4_IO_CONF_ERROR}, + {BMI088_GYRO_INT3_INT4_IO_MAP, BMI088_GYRO_DRDY_IO_INT3, BMI088_GYRO_INT3_INT4_IO_MAP_ERROR} + +}; + +static void Calibrate_MPU_Offset(IMU_Data_t *bmi088); + +uint8_t BMI088Init(SPI_HandleTypeDef *bmi088_SPI, uint8_t calibrate) +{ + BMI088_SPI = bmi088_SPI; + error = BMI088_NO_ERROR; + + error |= bmi088_accel_init(); + error |= bmi088_gyro_init(); + if (calibrate) + Calibrate_MPU_Offset(&BMI088); + else + { + BMI088.GyroOffset[0] = GxOFFSET; + BMI088.GyroOffset[1] = GyOFFSET; + BMI088.GyroOffset[2] = GzOFFSET; + BMI088.gNorm = gNORM; + BMI088.AccelScale = 9.81f / BMI088.gNorm; + BMI088.TempWhenCali = 40; + } + + return error; +} + +void Calibrate_MPU_Offset(IMU_Data_t *bmi088) +{ + static float startTime; + static uint16_t CaliTimes = 6000; + uint8_t buf[8] = {0, 0, 0, 0, 0, 0}; + int16_t bmi088_raw_temp; + float gyroMax[3], gyroMin[3]; + float gNormTemp, gNormMax, gNormMin; + + startTime = DWT_GetTimeline_s(); + do + { + if (DWT_GetTimeline_s() - startTime > 12) + { + // ��???? + bmi088->GyroOffset[0] = GxOFFSET; + bmi088->GyroOffset[1] = GyOFFSET; + bmi088->GyroOffset[2] = GzOFFSET; + bmi088->gNorm = gNORM; + bmi088->TempWhenCali = 40; + LOGERROR("[BMI088] Calibrate Failed! Use offline params"); + break; + } + + DWT_Delay(0.005); + bmi088->gNorm = 0; + bmi088->GyroOffset[0] = 0; + bmi088->GyroOffset[1] = 0; + bmi088->GyroOffset[2] = 0; + + for (uint16_t i = 0; i < CaliTimes; ++i) + { + BMI088_accel_read_muli_reg(BMI088_ACCEL_XOUT_L, buf, 6); + bmi088_raw_temp = (int16_t)((buf[1]) << 8) | buf[0]; + bmi088->Accel[0] = bmi088_raw_temp * BMI088_ACCEL_SEN; + bmi088_raw_temp = (int16_t)((buf[3]) << 8) | buf[2]; + bmi088->Accel[1] = bmi088_raw_temp * BMI088_ACCEL_SEN; + bmi088_raw_temp = (int16_t)((buf[5]) << 8) | buf[4]; + bmi088->Accel[2] = bmi088_raw_temp * BMI088_ACCEL_SEN; + gNormTemp = sqrtf(bmi088->Accel[0] * bmi088->Accel[0] + + bmi088->Accel[1] * bmi088->Accel[1] + + bmi088->Accel[2] * bmi088->Accel[2]); + bmi088->gNorm += gNormTemp; + + BMI088_gyro_read_muli_reg(BMI088_GYRO_CHIP_ID, buf, 8); + if (buf[0] == BMI088_GYRO_CHIP_ID_VALUE) + { + bmi088_raw_temp = (int16_t)((buf[3]) << 8) | buf[2]; + bmi088->Gyro[0] = bmi088_raw_temp * BMI088_GYRO_SEN; + bmi088->GyroOffset[0] += bmi088->Gyro[0]; + bmi088_raw_temp = (int16_t)((buf[5]) << 8) | buf[4]; + bmi088->Gyro[1] = bmi088_raw_temp * BMI088_GYRO_SEN; + bmi088->GyroOffset[1] += bmi088->Gyro[1]; + bmi088_raw_temp = (int16_t)((buf[7]) << 8) | buf[6]; + bmi088->Gyro[2] = bmi088_raw_temp * BMI088_GYRO_SEN; + bmi088->GyroOffset[2] += bmi088->Gyro[2]; + } + + if (i == 0) + { + gNormMax = gNormTemp; + gNormMin = gNormTemp; + for (uint8_t j = 0; j < 3; ++j) + { + gyroMax[j] = bmi088->Gyro[j]; + gyroMin[j] = bmi088->Gyro[j]; + } + } + else + { + if (gNormTemp > gNormMax) + gNormMax = gNormTemp; + if (gNormTemp < gNormMin) + gNormMin = gNormTemp; + for (uint8_t j = 0; j < 3; ++j) + { + if (bmi088->Gyro[j] > gyroMax[j]) + gyroMax[j] = bmi088->Gyro[j]; + if (bmi088->Gyro[j] < gyroMin[j]) + gyroMin[j] = bmi088->Gyro[j]; + } + } + + gNormDiff = gNormMax - gNormMin; + for (uint8_t j = 0; j < 3; ++j) + gyroDiff[j] = gyroMax[j] - gyroMin[j]; + if (gNormDiff > 0.5f || + gyroDiff[0] > 0.15f || + gyroDiff[1] > 0.15f || + gyroDiff[2] > 0.15f) + { + LOGWARNING("[bmi088] calibration was interrupted\n"); + break; + } + + DWT_Delay(0.0005); + } + + bmi088->gNorm /= (float)CaliTimes; + for (uint8_t i = 0; i < 3; ++i) + bmi088->GyroOffset[i] /= (float)CaliTimes; + + BMI088_accel_read_muli_reg(BMI088_TEMP_M, buf, 2); + bmi088_raw_temp = (int16_t)((buf[0] << 3) | (buf[1] >> 5)); + if (bmi088_raw_temp > 1023) + bmi088_raw_temp -= 2048; + bmi088->TempWhenCali = bmi088_raw_temp * BMI088_TEMP_FACTOR + BMI088_TEMP_OFFSET; + + caliCount++; + } while (gNormDiff > 0.5f || + fabsf(bmi088->gNorm - 9.8f) > 0.5f || + gyroDiff[0] > 0.15f || + gyroDiff[1] > 0.15f || + gyroDiff[2] > 0.15f || + fabsf(bmi088->GyroOffset[0]) > 0.01f || + fabsf(bmi088->GyroOffset[1]) > 0.01f || + fabsf(bmi088->GyroOffset[2]) > 0.01f); + + bmi088->AccelScale = 9.81f / bmi088->gNorm; +} + +uint8_t bmi088_accel_init(void) +{ + // check commiunication + BMI088_accel_read_single_reg(BMI088_ACC_CHIP_ID, res); + DWT_Delay(0.001); + BMI088_accel_read_single_reg(BMI088_ACC_CHIP_ID, res); + DWT_Delay(0.001); + // accel software reset + BMI088_accel_write_single_reg(BMI088_ACC_SOFTRESET, BMI088_ACC_SOFTRESET_VALUE); + // HAL_Delay(BMI088_LONG_DELAY_TIME); + DWT_Delay(0.08); + // check commiunication is normal after reset + BMI088_accel_read_single_reg(BMI088_ACC_CHIP_ID, res); + DWT_Delay(0.001); + BMI088_accel_read_single_reg(BMI088_ACC_CHIP_ID, res); + DWT_Delay(0.001); + + // check the "who am I" + if (res != BMI088_ACC_CHIP_ID_VALUE) + { + LOGERROR("[bmi088] Can not read bmi088 acc chip id"); + return BMI088_NO_SENSOR; + } + + // set accel sonsor config and check + for (write_reg_num = 0; write_reg_num < BMI088_WRITE_ACCEL_REG_NUM; write_reg_num++) + { + + BMI088_accel_write_single_reg(BMI088_Accel_Init_Table[write_reg_num][0], BMI088_Accel_Init_Table[write_reg_num][1]); + DWT_Delay(0.001); + + BMI088_accel_read_single_reg(BMI088_Accel_Init_Table[write_reg_num][0], res); + DWT_Delay(0.001); + + if (res != BMI088_Accel_Init_Table[write_reg_num][1]) + { + // write_reg_num--; + // return BMI088_Accel_Init_Table[write_reg_num][2]; + error |= BMI088_Accel_Init_Table[write_reg_num][2]; + } + } + return BMI088_NO_ERROR; +} + +uint8_t bmi088_gyro_init(void) +{ + // check commiunication + BMI088_gyro_read_single_reg(BMI088_GYRO_CHIP_ID, res); + DWT_Delay(0.001); + BMI088_gyro_read_single_reg(BMI088_GYRO_CHIP_ID, res); + DWT_Delay(0.001); + + // reset the gyro sensor + BMI088_gyro_write_single_reg(BMI088_GYRO_SOFTRESET, BMI088_GYRO_SOFTRESET_VALUE); + // HAL_Delay(BMI088_LONG_DELAY_TIME); + DWT_Delay(0.08); + // check commiunication is normal after reset + BMI088_gyro_read_single_reg(BMI088_GYRO_CHIP_ID, res); + DWT_Delay(0.001); + BMI088_gyro_read_single_reg(BMI088_GYRO_CHIP_ID, res); + DWT_Delay(0.001); + + // check the "who am I" + if (res != BMI088_GYRO_CHIP_ID_VALUE) + { + LOGERROR("[bmi088] Can not read bmi088 gyro chip id"); + return BMI088_NO_SENSOR; + } + + // set gyro sonsor config and check + for (write_reg_num = 0; write_reg_num < BMI088_WRITE_GYRO_REG_NUM; write_reg_num++) + { + + BMI088_gyro_write_single_reg(BMI088_Gyro_Init_Table[write_reg_num][0], BMI088_Gyro_Init_Table[write_reg_num][1]); + DWT_Delay(0.001); + + BMI088_gyro_read_single_reg(BMI088_Gyro_Init_Table[write_reg_num][0], res); + DWT_Delay(0.001); + + if (res != BMI088_Gyro_Init_Table[write_reg_num][1]) + { + write_reg_num--; + // return BMI088_Gyro_Init_Table[write_reg_num][2]; + error |= BMI088_Accel_Init_Table[write_reg_num][2]; + } + } + + return BMI088_NO_ERROR; +} + +void BMI088_Read(IMU_Data_t *bmi088) +{ + static uint8_t buf[8] = {0}; + static int16_t bmi088_raw_temp; + + BMI088_accel_read_muli_reg(BMI088_ACCEL_XOUT_L, buf, 6); + + bmi088_raw_temp = (int16_t)((buf[1]) << 8) | buf[0]; + bmi088->Accel[0] = bmi088_raw_temp * BMI088_ACCEL_SEN * bmi088->AccelScale; + bmi088_raw_temp = (int16_t)((buf[3]) << 8) | buf[2]; + bmi088->Accel[1] = bmi088_raw_temp * BMI088_ACCEL_SEN * bmi088->AccelScale; + bmi088_raw_temp = (int16_t)((buf[5]) << 8) | buf[4]; + bmi088->Accel[2] = bmi088_raw_temp * BMI088_ACCEL_SEN * bmi088->AccelScale; + + BMI088_gyro_read_muli_reg(BMI088_GYRO_CHIP_ID, buf, 8); + if (buf[0] == BMI088_GYRO_CHIP_ID_VALUE) + { + if (caliOffset) + { + bmi088_raw_temp = (int16_t)((buf[3]) << 8) | buf[2]; + bmi088->Gyro[0] = bmi088_raw_temp * BMI088_GYRO_SEN - bmi088->GyroOffset[0]; + bmi088_raw_temp = (int16_t)((buf[5]) << 8) | buf[4]; + bmi088->Gyro[1] = bmi088_raw_temp * BMI088_GYRO_SEN - bmi088->GyroOffset[1]; + bmi088_raw_temp = (int16_t)((buf[7]) << 8) | buf[6]; + bmi088->Gyro[2] = bmi088_raw_temp * BMI088_GYRO_SEN - bmi088->GyroOffset[2]; + } + else + { + bmi088_raw_temp = (int16_t)((buf[3]) << 8) | buf[2]; + bmi088->Gyro[0] = bmi088_raw_temp * BMI088_GYRO_SEN; + bmi088_raw_temp = (int16_t)((buf[5]) << 8) | buf[4]; + bmi088->Gyro[1] = bmi088_raw_temp * BMI088_GYRO_SEN; + bmi088_raw_temp = (int16_t)((buf[7]) << 8) | buf[6]; + bmi088->Gyro[2] = bmi088_raw_temp * BMI088_GYRO_SEN; + } + } + BMI088_accel_read_muli_reg(BMI088_TEMP_M, buf, 2); + + bmi088_raw_temp = (int16_t)((buf[0] << 3) | (buf[1] >> 5)); + + if (bmi088_raw_temp > 1023) + { + bmi088_raw_temp -= 2048; + } + + bmi088->Temperature = bmi088_raw_temp * BMI088_TEMP_FACTOR + BMI088_TEMP_OFFSET; +} + +#if defined(BMI088_USE_SPI) + +static void BMI088_write_single_reg(uint8_t reg, uint8_t data) +{ + BMI088_read_write_byte(reg); + BMI088_read_write_byte(data); +} + +static void BMI088_read_single_reg(uint8_t reg, uint8_t *return_data) +{ + BMI088_read_write_byte(reg | 0x80); + *return_data = BMI088_read_write_byte(0x55); +} + +static void BMI088_read_muli_reg(uint8_t reg, uint8_t *buf, uint8_t len) +{ + BMI088_read_write_byte(reg | 0x80); + + while (len != 0) + { + *buf = BMI088_read_write_byte(0x55); + buf++; + len--; + } +} +#elif defined(BMI088_USE_IIC) + +#endif diff --git a/modules/imu/BMI088driver.h b/modules/imu/BMI088driver.h new file mode 100644 index 0000000..2fd30fb --- /dev/null +++ b/modules/imu/BMI088driver.h @@ -0,0 +1,133 @@ +#ifndef BMI088DRIVER_H +#define BMI088DRIVER_H + +#include "stdint.h" +#include "main.h" + +#define BMI088_TEMP_FACTOR 0.125f +#define BMI088_TEMP_OFFSET 23.0f + +#define BMI088_WRITE_ACCEL_REG_NUM 6 +#define BMI088_WRITE_GYRO_REG_NUM 6 + +#define BMI088_GYRO_DATA_READY_BIT 0 +#define BMI088_ACCEL_DATA_READY_BIT 1 +#define BMI088_ACCEL_TEMP_DATA_READY_BIT 2 + +#define BMI088_LONG_DELAY_TIME 80 +#define BMI088_COM_WAIT_SENSOR_TIME 150 + +#define BMI088_ACCEL_IIC_ADDRESSE (0x18 << 1) +#define BMI088_GYRO_IIC_ADDRESSE (0x68 << 1) + +#define BMI088_ACCEL_3G_SEN 0.0008974358974f +#define BMI088_ACCEL_6G_SEN 0.00179443359375f +#define BMI088_ACCEL_12G_SEN 0.0035888671875f +#define BMI088_ACCEL_24G_SEN 0.007177734375f + +#define BMI088_GYRO_2000_SEN 0.00106526443603169529841533860381f +#define BMI088_GYRO_1000_SEN 0.00053263221801584764920766930190693f +#define BMI088_GYRO_500_SEN 0.00026631610900792382460383465095346f +#define BMI088_GYRO_250_SEN 0.00013315805450396191230191732547673f +#define BMI088_GYRO_125_SEN 0.000066579027251980956150958662738366f + +// ���ֶ��� +#if INFANTRY_ID == 0 +#define GxOFFSET 0.00247530174f +#define GyOFFSET 0.000393082853f +#define GzOFFSET 0.000393082853f +#define gNORM 9.69293118f +#elif INFANTRY_ID == 1 +#define GxOFFSET 0.0007222f +#define GyOFFSET -0.001786f +#define GzOFFSET 0.0004346f +#define gNORM 9.876785f +#elif INFANTRY_ID == 2 +#define GxOFFSET 0.0007222f +#define GyOFFSET -0.001786f +#define GzOFFSET 0.0004346f +#define gNORM 9.876785f +#elif INFANTRY_ID == 3 +#define GxOFFSET 0.00270364084f +#define GyOFFSET -0.000532632112f +#define GzOFFSET 0.00478090625f +#define gNORM 9.73574924f +#elif INFANTRY_ID == 4 +#define GxOFFSET 0.0007222f +#define GyOFFSET -0.001786f +#define GzOFFSET 0.0004346f +#define gNORM 9.876785f +#endif + +/* IMU数据结构体 */ +typedef struct +{ + float Accel[3]; + + float Gyro[3]; + + float TempWhenCali; + float Temperature; + + float AccelScale; + float GyroOffset[3]; + + float gNorm; +} IMU_Data_t; + +/* BMI088错误码枚举 */ +enum +{ + BMI088_NO_ERROR = 0x00, + BMI088_ACC_PWR_CTRL_ERROR = 0x01, + BMI088_ACC_PWR_CONF_ERROR = 0x02, + BMI088_ACC_CONF_ERROR = 0x03, + BMI088_ACC_SELF_TEST_ERROR = 0x04, + BMI088_ACC_RANGE_ERROR = 0x05, + BMI088_INT1_IO_CTRL_ERROR = 0x06, + BMI088_INT_MAP_DATA_ERROR = 0x07, + BMI088_GYRO_RANGE_ERROR = 0x08, + BMI088_GYRO_BANDWIDTH_ERROR = 0x09, + BMI088_GYRO_LPM1_ERROR = 0x0A, + BMI088_GYRO_CTRL_ERROR = 0x0B, + BMI088_GYRO_INT3_INT4_IO_CONF_ERROR = 0x0C, + BMI088_GYRO_INT3_INT4_IO_MAP_ERROR = 0x0D, + + BMI088_SELF_TEST_ACCEL_ERROR = 0x80, + BMI088_SELF_TEST_GYRO_ERROR = 0x40, + BMI088_NO_SENSOR = 0xFF, +}; + +extern IMU_Data_t BMI088; + +/** + * @brief 初始化BMI088,传入连接的SPI总线handle,以及是否进行在线标定 + * + * @param bmi088_SPI handle + * @param calibrate 1为进行在线标定,0使用离线数据 + * @return uint8_t 成功则返回BMI088_NO_ERROR + */ +extern uint8_t BMI088Init(SPI_HandleTypeDef *bmi088_SPI, uint8_t calibrate); + +/** + * @brief 加速计初始化 + * + * @return uint8_t + */ +extern uint8_t bmi088_accel_init(void); + +/** + * @brief 陀螺仪初始化 + * + * @return uint8_t + */ +extern uint8_t bmi088_gyro_init(void); + +/** + * @brief 读取一次BMI088的数据,包括gyro和accel + * + * @param bmi088 传入BMI088实例(结构体) + */ +extern void BMI088_Read(IMU_Data_t *bmi088); + +#endif diff --git a/modules/imu/BMI088reg.h b/modules/imu/BMI088reg.h new file mode 100644 index 0000000..f571f7e --- /dev/null +++ b/modules/imu/BMI088reg.h @@ -0,0 +1,180 @@ +#ifndef BMI088REG_H +#define BMI088REG_H + +#define BMI088_ACC_CHIP_ID 0x00 // the register is " Who am I " +#define BMI088_ACC_CHIP_ID_VALUE 0x1E + +#define BMI088_ACC_ERR_REG 0x02 +#define BMI088_ACCEL_CONGIF_ERROR_SHFITS 0x2 +#define BMI088_ACCEL_CONGIF_ERROR (1 << BMI088_ACCEL_CONGIF_ERROR_SHFITS) +#define BMI088_FATAL_ERROR_SHFITS 0x0 +#define BMI088_FATAL_ERROR (1 << BMI088_FATAL_ERROR) + +#define BMI088_ACC_STATUS 0x03 +#define BMI088_ACCEL_DRDY_SHFITS 0x7 +#define BMI088_ACCEL_DRDY (1 << BMI088_ACCEL_DRDY_SHFITS) + +#define BMI088_ACCEL_XOUT_L 0x12 +#define BMI088_ACCEL_XOUT_M 0x13 +#define BMI088_ACCEL_YOUT_L 0x14 +#define BMI088_ACCEL_YOUT_M 0x15 +#define BMI088_ACCEL_ZOUT_L 0x16 +#define BMI088_ACCEL_ZOUT_M 0x17 + +#define BMI088_SENSORTIME_DATA_L 0x18 +#define BMI088_SENSORTIME_DATA_M 0x19 +#define BMI088_SENSORTIME_DATA_H 0x1A + +#define BMI088_ACC_INT_STAT_1 0x1D +#define BMI088_ACCEL_DRDY_INTERRUPT_SHFITS 0x7 +#define BMI088_ACCEL_DRDY_INTERRUPT (1 << BMI088_ACCEL_DRDY_INTERRUPT_SHFITS) + +#define BMI088_TEMP_M 0x22 + +#define BMI088_TEMP_L 0x23 + +#define BMI088_ACC_CONF 0x40 +#define BMI088_ACC_CONF_MUST_Set 0x80 +#define BMI088_ACC_BWP_SHFITS 0x4 +#define BMI088_ACC_OSR4 (0x0 << BMI088_ACC_BWP_SHFITS) +#define BMI088_ACC_OSR2 (0x1 << BMI088_ACC_BWP_SHFITS) +#define BMI088_ACC_NORMAL (0x2 << BMI088_ACC_BWP_SHFITS) + +#define BMI088_ACC_ODR_SHFITS 0x0 +#define BMI088_ACC_12_5_HZ (0x5 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_25_HZ (0x6 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_50_HZ (0x7 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_100_HZ (0x8 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_200_HZ (0x9 << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_400_HZ (0xA << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_800_HZ (0xB << BMI088_ACC_ODR_SHFITS) +#define BMI088_ACC_1600_HZ (0xC << BMI088_ACC_ODR_SHFITS) + +#define BMI088_ACC_RANGE 0x41 + +#define BMI088_ACC_RANGE_SHFITS 0x0 +#define BMI088_ACC_RANGE_3G (0x0 << BMI088_ACC_RANGE_SHFITS) +#define BMI088_ACC_RANGE_6G (0x1 << BMI088_ACC_RANGE_SHFITS) +#define BMI088_ACC_RANGE_12G (0x2 << BMI088_ACC_RANGE_SHFITS) +#define BMI088_ACC_RANGE_24G (0x3 << BMI088_ACC_RANGE_SHFITS) + +#define BMI088_INT1_IO_CTRL 0x53 +#define BMI088_ACC_INT1_IO_ENABLE_SHFITS 0x3 +#define BMI088_ACC_INT1_IO_ENABLE (0x1 << BMI088_ACC_INT1_IO_ENABLE_SHFITS) +#define BMI088_ACC_INT1_GPIO_MODE_SHFITS 0x2 +#define BMI088_ACC_INT1_GPIO_PP (0x0 << BMI088_ACC_INT1_GPIO_MODE_SHFITS) +#define BMI088_ACC_INT1_GPIO_OD (0x1 << BMI088_ACC_INT1_GPIO_MODE_SHFITS) +#define BMI088_ACC_INT1_GPIO_LVL_SHFITS 0x1 +#define BMI088_ACC_INT1_GPIO_LOW (0x0 << BMI088_ACC_INT1_GPIO_LVL_SHFITS) +#define BMI088_ACC_INT1_GPIO_HIGH (0x1 << BMI088_ACC_INT1_GPIO_LVL_SHFITS) + +#define BMI088_INT2_IO_CTRL 0x54 +#define BMI088_ACC_INT2_IO_ENABLE_SHFITS 0x3 +#define BMI088_ACC_INT2_IO_ENABLE (0x1 << BMI088_ACC_INT2_IO_ENABLE_SHFITS) +#define BMI088_ACC_INT2_GPIO_MODE_SHFITS 0x2 +#define BMI088_ACC_INT2_GPIO_PP (0x0 << BMI088_ACC_INT2_GPIO_MODE_SHFITS) +#define BMI088_ACC_INT2_GPIO_OD (0x1 << BMI088_ACC_INT2_GPIO_MODE_SHFITS) +#define BMI088_ACC_INT2_GPIO_LVL_SHFITS 0x1 +#define BMI088_ACC_INT2_GPIO_LOW (0x0 << BMI088_ACC_INT2_GPIO_LVL_SHFITS) +#define BMI088_ACC_INT2_GPIO_HIGH (0x1 << BMI088_ACC_INT2_GPIO_LVL_SHFITS) + +#define BMI088_INT_MAP_DATA 0x58 +#define BMI088_ACC_INT2_DRDY_INTERRUPT_SHFITS 0x6 +#define BMI088_ACC_INT2_DRDY_INTERRUPT (0x1 << BMI088_ACC_INT2_DRDY_INTERRUPT_SHFITS) +#define BMI088_ACC_INT1_DRDY_INTERRUPT_SHFITS 0x2 +#define BMI088_ACC_INT1_DRDY_INTERRUPT (0x1 << BMI088_ACC_INT1_DRDY_INTERRUPT_SHFITS) + +#define BMI088_ACC_SELF_TEST 0x6D +#define BMI088_ACC_SELF_TEST_OFF 0x00 +#define BMI088_ACC_SELF_TEST_POSITIVE_SIGNAL 0x0D +#define BMI088_ACC_SELF_TEST_NEGATIVE_SIGNAL 0x09 + +#define BMI088_ACC_PWR_CONF 0x7C +#define BMI088_ACC_PWR_SUSPEND_MODE 0x03 +#define BMI088_ACC_PWR_ACTIVE_MODE 0x00 + +#define BMI088_ACC_PWR_CTRL 0x7D +#define BMI088_ACC_ENABLE_ACC_OFF 0x00 +#define BMI088_ACC_ENABLE_ACC_ON 0x04 + +#define BMI088_ACC_SOFTRESET 0x7E +#define BMI088_ACC_SOFTRESET_VALUE 0xB6 + +#define BMI088_GYRO_CHIP_ID 0x00 +#define BMI088_GYRO_CHIP_ID_VALUE 0x0F + +#define BMI088_GYRO_X_L 0x02 +#define BMI088_GYRO_X_H 0x03 +#define BMI088_GYRO_Y_L 0x04 +#define BMI088_GYRO_Y_H 0x05 +#define BMI088_GYRO_Z_L 0x06 +#define BMI088_GYRO_Z_H 0x07 + +#define BMI088_GYRO_INT_STAT_1 0x0A +#define BMI088_GYRO_DYDR_SHFITS 0x7 +#define BMI088_GYRO_DYDR (0x1 << BMI088_GYRO_DYDR_SHFITS) + +#define BMI088_GYRO_RANGE 0x0F +#define BMI088_GYRO_RANGE_SHFITS 0x0 +#define BMI088_GYRO_2000 (0x0 << BMI088_GYRO_RANGE_SHFITS) +#define BMI088_GYRO_1000 (0x1 << BMI088_GYRO_RANGE_SHFITS) +#define BMI088_GYRO_500 (0x2 << BMI088_GYRO_RANGE_SHFITS) +#define BMI088_GYRO_250 (0x3 << BMI088_GYRO_RANGE_SHFITS) +#define BMI088_GYRO_125 (0x4 << BMI088_GYRO_RANGE_SHFITS) + +#define BMI088_GYRO_BANDWIDTH 0x10 +// the first num means Output data rate, the second num means bandwidth +#define BMI088_GYRO_BANDWIDTH_MUST_Set 0x80 +#define BMI088_GYRO_2000_532_HZ 0x00 +#define BMI088_GYRO_2000_230_HZ 0x01 +#define BMI088_GYRO_1000_116_HZ 0x02 +#define BMI088_GYRO_400_47_HZ 0x03 +#define BMI088_GYRO_200_23_HZ 0x04 +#define BMI088_GYRO_100_12_HZ 0x05 +#define BMI088_GYRO_200_64_HZ 0x06 +#define BMI088_GYRO_100_32_HZ 0x07 + +#define BMI088_GYRO_LPM1 0x11 +#define BMI088_GYRO_NORMAL_MODE 0x00 +#define BMI088_GYRO_SUSPEND_MODE 0x80 +#define BMI088_GYRO_DEEP_SUSPEND_MODE 0x20 + +#define BMI088_GYRO_SOFTRESET 0x14 +#define BMI088_GYRO_SOFTRESET_VALUE 0xB6 + +#define BMI088_GYRO_CTRL 0x15 +#define BMI088_DRDY_OFF 0x00 +#define BMI088_DRDY_ON 0x80 + +#define BMI088_GYRO_INT3_INT4_IO_CONF 0x16 +#define BMI088_GYRO_INT4_GPIO_MODE_SHFITS 0x3 +#define BMI088_GYRO_INT4_GPIO_PP (0x0 << BMI088_GYRO_INT4_GPIO_MODE_SHFITS) +#define BMI088_GYRO_INT4_GPIO_OD (0x1 << BMI088_GYRO_INT4_GPIO_MODE_SHFITS) +#define BMI088_GYRO_INT4_GPIO_LVL_SHFITS 0x2 +#define BMI088_GYRO_INT4_GPIO_LOW (0x0 << BMI088_GYRO_INT4_GPIO_LVL_SHFITS) +#define BMI088_GYRO_INT4_GPIO_HIGH (0x1 << BMI088_GYRO_INT4_GPIO_LVL_SHFITS) +#define BMI088_GYRO_INT3_GPIO_MODE_SHFITS 0x1 +#define BMI088_GYRO_INT3_GPIO_PP (0x0 << BMI088_GYRO_INT3_GPIO_MODE_SHFITS) +#define BMI088_GYRO_INT3_GPIO_OD (0x1 << BMI088_GYRO_INT3_GPIO_MODE_SHFITS) +#define BMI088_GYRO_INT3_GPIO_LVL_SHFITS 0x0 +#define BMI088_GYRO_INT3_GPIO_LOW (0x0 << BMI088_GYRO_INT3_GPIO_LVL_SHFITS) +#define BMI088_GYRO_INT3_GPIO_HIGH (0x1 << BMI088_GYRO_INT3_GPIO_LVL_SHFITS) + +#define BMI088_GYRO_INT3_INT4_IO_MAP 0x18 + +#define BMI088_GYRO_DRDY_IO_OFF 0x00 +#define BMI088_GYRO_DRDY_IO_INT3 0x01 +#define BMI088_GYRO_DRDY_IO_INT4 0x80 +#define BMI088_GYRO_DRDY_IO_BOTH (BMI088_GYRO_DRDY_IO_INT3 | BMI088_GYRO_DRDY_IO_INT4) + +#define BMI088_GYRO_SELF_TEST 0x3C +#define BMI088_GYRO_RATE_OK_SHFITS 0x4 +#define BMI088_GYRO_RATE_OK (0x1 << BMI088_GYRO_RATE_OK_SHFITS) +#define BMI088_GYRO_BIST_FAIL_SHFITS 0x2 +#define BMI088_GYRO_BIST_FAIL (0x1 << BMI088_GYRO_BIST_FAIL_SHFITS) +#define BMI088_GYRO_BIST_RDY_SHFITS 0x1 +#define BMI088_GYRO_BIST_RDY (0x1 << BMI088_GYRO_BIST_RDY_SHFITS) +#define BMI088_GYRO_TRIG_BIST_SHFITS 0x0 +#define BMI088_GYRO_TRIG_BIST (0x1 << BMI088_GYRO_TRIG_BIST_SHFITS) + +#endif diff --git a/modules/imu/ins_task.c b/modules/imu/ins_task.c new file mode 100644 index 0000000..ec084b6 --- /dev/null +++ b/modules/imu/ins_task.c @@ -0,0 +1,350 @@ +/** + ****************************************************************************** + * @file ins_task.c + * @author Wang Hongxi + * @author annotation and modificaiton by neozng + * @version V2.0.0 + * @date 2022/2/23 + * @brief + ****************************************************************************** + * @attention + * + ****************************************************************************** + */ +#include "ins_task.h" +#include "controller.h" +#include "QuaternionEKF.h" +#include "spi.h" +#include "tim.h" +#include "user_lib.h" +#include "general_def.h" +#include "master_process.h" + +static INS_t INS; +static IMU_Param_t IMU_Param; +static PIDInstance TempCtrl = {0}; + +const float xb[3] = {1, 0, 0}; +const float yb[3] = {0, 1, 0}; +const float zb[3] = {0, 0, 1}; + +// 用于获取两次采样之间的时间间隔 +static uint32_t INS_DWT_Count = 0; +static float dt = 0, t = 0; +static float RefTemp = 40; // 恒温设定温度 + +static void IMU_Param_Correction(IMU_Param_t *param, float gyro[3], float accel[3]); + +static void IMUPWMSet(uint16_t pwm) +{ + __HAL_TIM_SetCompare(&htim10, TIM_CHANNEL_1, pwm); +} + +/** + * @brief 温度控制 + * + */ +static void IMU_Temperature_Ctrl(void) +{ + PIDCalculate(&TempCtrl, BMI088.Temperature, RefTemp); + IMUPWMSet(float_constrain(float_rounding(TempCtrl.Output), 0, UINT32_MAX)); +} + +// 使用加速度计的数据初始化Roll和Pitch,而Yaw置0,这样可以避免在初始时候的姿态估计误差 +static void InitQuaternion(float *init_q4) +{ + float acc_init[3] = {0}; + float gravity_norm[3] = {0, 0, 1}; // 导航系重力加速度矢量,归一化后为(0,0,1) + float axis_rot[3] = {0}; // 旋转轴 + // 读取100次加速度计数据,取平均值作为初始值 + for (uint8_t i = 0; i < 100; ++i) + { + BMI088_Read(&BMI088); + acc_init[X] += BMI088.Accel[X]; + acc_init[Y] += BMI088.Accel[Y]; + acc_init[Z] += BMI088.Accel[Z]; + DWT_Delay(0.001); + } + for (uint8_t i = 0; i < 3; ++i) + acc_init[i] /= 100; + Norm3d(acc_init); + // 计算原始加速度矢量和导航系重力加速度矢量的夹角 + float angle = acosf(Dot3d(acc_init, gravity_norm)); + Cross3d(acc_init, gravity_norm, axis_rot); + Norm3d(axis_rot); + init_q4[0] = cosf(angle / 2.0f); + for (uint8_t i = 0; i < 2; ++i) + init_q4[i + 1] = axis_rot[i] * sinf(angle / 2.0f); // 轴角公式,第三轴为0(没有z轴分量) +} + +attitude_t *INS_Init(void) +{ + if (!INS.init) + INS.init = 1; + else + return (attitude_t *)&INS.Gyro; + + HAL_TIM_PWM_Start(&htim10, TIM_CHANNEL_1); + + while (BMI088Init(&hspi1, 1) != BMI088_NO_ERROR) + ; + IMU_Param.scale[X] = 1; + IMU_Param.scale[Y] = 1; + IMU_Param.scale[Z] = 1; + IMU_Param.Yaw = 0; + IMU_Param.Pitch = 0; + IMU_Param.Roll = 0; + IMU_Param.flag = 1; + + float init_quaternion[4] = {0}; + InitQuaternion(init_quaternion); + IMU_QuaternionEKF_Init(init_quaternion, 10, 0.001, 1000000, 1, 0); + // imu heat init + PID_Init_Config_s config = {.MaxOut = 2000, + .IntegralLimit = 300, + .DeadBand = 0, + .Kp = 1000, + .Ki = 20, + .Kd = 0, + .Improve = 0x01}; // enable integratiaon limit + PIDInit(&TempCtrl, &config); + + // noise of accel is relatively big and of high freq,thus lpf is used + INS.AccelLPF = 0.0085; + DWT_GetDeltaT(&INS_DWT_Count); + return (attitude_t *)&INS.Gyro; // @todo: 这里偷懒了,不要这样做! 修改INT_t结构体可能会导致异常,待修复. +} + +/* 注意以1kHz的频率运行此任务 */ +void INS_Task(void) +{ + static uint32_t count = 0; + const float gravity[3] = {0, 0, 9.81f}; + + dt = DWT_GetDeltaT(&INS_DWT_Count); + t += dt; + + // ins update + if ((count % 1) == 0) + { + BMI088_Read(&BMI088); + + INS.Accel[X] = BMI088.Accel[X]; + INS.Accel[Y] = BMI088.Accel[Y]; + INS.Accel[Z] = BMI088.Accel[Z]; + INS.Gyro[X] = BMI088.Gyro[X]; + INS.Gyro[Y] = BMI088.Gyro[Y]; + INS.Gyro[Z] = BMI088.Gyro[Z]; + + // demo function,用于修正安装误差,可以不管,本demo暂时没用 + IMU_Param_Correction(&IMU_Param, INS.Gyro, INS.Accel); + + // 计算重力加速度矢量和b系的XY两轴的夹角,可用作功能扩展,本demo暂时没用 + // INS.atanxz = -atan2f(INS.Accel[X], INS.Accel[Z]) * 180 / PI; + // INS.atanyz = atan2f(INS.Accel[Y], INS.Accel[Z]) * 180 / PI; + + // 核心函数,EKF更新四元数 + IMU_QuaternionEKF_Update(INS.Gyro[X], INS.Gyro[Y], INS.Gyro[Z], INS.Accel[X], INS.Accel[Y], INS.Accel[Z], dt); + + memcpy(INS.q, QEKF_INS.q, sizeof(QEKF_INS.q)); + + // 机体系基向量转换到导航坐标系,本例选取惯性系为导航系 + BodyFrameToEarthFrame(xb, INS.xn, INS.q); + BodyFrameToEarthFrame(yb, INS.yn, INS.q); + BodyFrameToEarthFrame(zb, INS.zn, INS.q); + + // 将重力从导航坐标系n转换到机体系b,随后根据加速度计数据计算运动加速度 + float gravity_b[3]; + EarthFrameToBodyFrame(gravity, gravity_b, INS.q); + for (uint8_t i = 0; i < 3; ++i) // 同样过一个低通滤波 + { + INS.MotionAccel_b[i] = (INS.Accel[i] - gravity_b[i]) * dt / (INS.AccelLPF + dt) + INS.MotionAccel_b[i] * INS.AccelLPF / (INS.AccelLPF + dt); + } + BodyFrameToEarthFrame(INS.MotionAccel_b, INS.MotionAccel_n, INS.q); // 转换回导航系n + + INS.Yaw = QEKF_INS.Yaw; + INS.Pitch = QEKF_INS.Pitch; + INS.Roll = QEKF_INS.Roll; + INS.YawTotalAngle = QEKF_INS.YawTotalAngle; + + VisionSetAltitude(INS.Yaw, INS.Pitch, INS.Roll); + } + + // temperature control + if ((count % 2) == 0) + { + // 500hz + IMU_Temperature_Ctrl(); + } + + if ((count++ % 1000) == 0) + { + // 1Hz 可以加入monitor函数,检查IMU是否正常运行/离线 + } +} + +/** + * @brief Transform 3dvector from BodyFrame to EarthFrame + * @param[1] vector in BodyFrame + * @param[2] vector in EarthFrame + * @param[3] quaternion + */ +void BodyFrameToEarthFrame(const float *vecBF, float *vecEF, float *q) +{ + vecEF[0] = 2.0f * ((0.5f - q[2] * q[2] - q[3] * q[3]) * vecBF[0] + + (q[1] * q[2] - q[0] * q[3]) * vecBF[1] + + (q[1] * q[3] + q[0] * q[2]) * vecBF[2]); + + vecEF[1] = 2.0f * ((q[1] * q[2] + q[0] * q[3]) * vecBF[0] + + (0.5f - q[1] * q[1] - q[3] * q[3]) * vecBF[1] + + (q[2] * q[3] - q[0] * q[1]) * vecBF[2]); + + vecEF[2] = 2.0f * ((q[1] * q[3] - q[0] * q[2]) * vecBF[0] + + (q[2] * q[3] + q[0] * q[1]) * vecBF[1] + + (0.5f - q[1] * q[1] - q[2] * q[2]) * vecBF[2]); +} + +/** + * @brief Transform 3dvector from EarthFrame to BodyFrame + * @param[1] vector in EarthFrame + * @param[2] vector in BodyFrame + * @param[3] quaternion + */ +void EarthFrameToBodyFrame(const float *vecEF, float *vecBF, float *q) +{ + vecBF[0] = 2.0f * ((0.5f - q[2] * q[2] - q[3] * q[3]) * vecEF[0] + + (q[1] * q[2] + q[0] * q[3]) * vecEF[1] + + (q[1] * q[3] - q[0] * q[2]) * vecEF[2]); + + vecBF[1] = 2.0f * ((q[1] * q[2] - q[0] * q[3]) * vecEF[0] + + (0.5f - q[1] * q[1] - q[3] * q[3]) * vecEF[1] + + (q[2] * q[3] + q[0] * q[1]) * vecEF[2]); + + vecBF[2] = 2.0f * ((q[1] * q[3] + q[0] * q[2]) * vecEF[0] + + (q[2] * q[3] - q[0] * q[1]) * vecEF[1] + + (0.5f - q[1] * q[1] - q[2] * q[2]) * vecEF[2]); +} + +/** + * @brief reserved.用于修正IMU安装误差与标度因数误差,即陀螺仪轴和云台轴的安装偏移 + * + * + * @param param IMU参数 + * @param gyro 角速度 + * @param accel 加速度 + */ +static void IMU_Param_Correction(IMU_Param_t *param, float gyro[3], float accel[3]) +{ + static float lastYawOffset, lastPitchOffset, lastRollOffset; + static float c_11, c_12, c_13, c_21, c_22, c_23, c_31, c_32, c_33; + float cosPitch, cosYaw, cosRoll, sinPitch, sinYaw, sinRoll; + + if (fabsf(param->Yaw - lastYawOffset) > 0.001f || + fabsf(param->Pitch - lastPitchOffset) > 0.001f || + fabsf(param->Roll - lastRollOffset) > 0.001f || param->flag) + { + cosYaw = arm_cos_f32(param->Yaw / 57.295779513f); + cosPitch = arm_cos_f32(param->Pitch / 57.295779513f); + cosRoll = arm_cos_f32(param->Roll / 57.295779513f); + sinYaw = arm_sin_f32(param->Yaw / 57.295779513f); + sinPitch = arm_sin_f32(param->Pitch / 57.295779513f); + sinRoll = arm_sin_f32(param->Roll / 57.295779513f); + + // 1.yaw(alpha) 2.pitch(beta) 3.roll(gamma) + c_11 = cosYaw * cosRoll + sinYaw * sinPitch * sinRoll; + c_12 = cosPitch * sinYaw; + c_13 = cosYaw * sinRoll - cosRoll * sinYaw * sinPitch; + c_21 = cosYaw * sinPitch * sinRoll - cosRoll * sinYaw; + c_22 = cosYaw * cosPitch; + c_23 = -sinYaw * sinRoll - cosYaw * cosRoll * sinPitch; + c_31 = -cosPitch * sinRoll; + c_32 = sinPitch; + c_33 = cosPitch * cosRoll; + param->flag = 0; + } + float gyro_temp[3]; + for (uint8_t i = 0; i < 3; ++i) + gyro_temp[i] = gyro[i] * param->scale[i]; + + gyro[X] = c_11 * gyro_temp[X] + + c_12 * gyro_temp[Y] + + c_13 * gyro_temp[Z]; + gyro[Y] = c_21 * gyro_temp[X] + + c_22 * gyro_temp[Y] + + c_23 * gyro_temp[Z]; + gyro[Z] = c_31 * gyro_temp[X] + + c_32 * gyro_temp[Y] + + c_33 * gyro_temp[Z]; + + float accel_temp[3]; + for (uint8_t i = 0; i < 3; ++i) + accel_temp[i] = accel[i]; + + accel[X] = c_11 * accel_temp[X] + + c_12 * accel_temp[Y] + + c_13 * accel_temp[Z]; + accel[Y] = c_21 * accel_temp[X] + + c_22 * accel_temp[Y] + + c_23 * accel_temp[Z]; + accel[Z] = c_31 * accel_temp[X] + + c_32 * accel_temp[Y] + + c_33 * accel_temp[Z]; + + lastYawOffset = param->Yaw; + lastPitchOffset = param->Pitch; + lastRollOffset = param->Roll; +} + +//------------------------------------functions below are not used in this demo------------------------------------------------- +//----------------------------------you can read them for learning or programming----------------------------------------------- +//----------------------------------they could also be helpful for further design----------------------------------------------- + +/** + * @brief Update quaternion + */ +void QuaternionUpdate(float *q, float gx, float gy, float gz, float dt) +{ + float qa, qb, qc; + + gx *= 0.5f * dt; + gy *= 0.5f * dt; + gz *= 0.5f * dt; + qa = q[0]; + qb = q[1]; + qc = q[2]; + q[0] += (-qb * gx - qc * gy - q[3] * gz); + q[1] += (qa * gx + qc * gz - q[3] * gy); + q[2] += (qa * gy - qb * gz + q[3] * gx); + q[3] += (qa * gz + qb * gy - qc * gx); +} + +/** + * @brief Convert quaternion to eular angle + */ +void QuaternionToEularAngle(float *q, float *Yaw, float *Pitch, float *Roll) +{ + *Yaw = atan2f(2.0f * (q[0] * q[3] + q[1] * q[2]), 2.0f * (q[0] * q[0] + q[1] * q[1]) - 1.0f) * 57.295779513f; + *Pitch = atan2f(2.0f * (q[0] * q[1] + q[2] * q[3]), 2.0f * (q[0] * q[0] + q[3] * q[3]) - 1.0f) * 57.295779513f; + *Roll = asinf(2.0f * (q[0] * q[2] - q[1] * q[3])) * 57.295779513f; +} + +/** + * @brief Convert eular angle to quaternion + */ +void EularAngleToQuaternion(float Yaw, float Pitch, float Roll, float *q) +{ + float cosPitch, cosYaw, cosRoll, sinPitch, sinYaw, sinRoll; + Yaw /= 57.295779513f; + Pitch /= 57.295779513f; + Roll /= 57.295779513f; + cosPitch = arm_cos_f32(Pitch / 2); + cosYaw = arm_cos_f32(Yaw / 2); + cosRoll = arm_cos_f32(Roll / 2); + sinPitch = arm_sin_f32(Pitch / 2); + sinYaw = arm_sin_f32(Yaw / 2); + sinRoll = arm_sin_f32(Roll / 2); + q[0] = cosPitch * cosRoll * cosYaw + sinPitch * sinRoll * sinYaw; + q[1] = sinPitch * cosRoll * cosYaw - cosPitch * sinRoll * sinYaw; + q[2] = sinPitch * cosRoll * sinYaw + cosPitch * sinRoll * cosYaw; + q[3] = cosPitch * cosRoll * sinYaw - sinPitch * sinRoll * cosYaw; +} diff --git a/modules/imu/ins_task.h b/modules/imu/ins_task.h new file mode 100644 index 0000000..4acac19 --- /dev/null +++ b/modules/imu/ins_task.h @@ -0,0 +1,143 @@ +/** + ****************************************************************************** + * @file ins_task.h + * @author Wang Hongxi + * @author annotation and modification by NeoZeng + * @version V2.0.0 + * @date 2022/2/23 + * @brief + ****************************************************************************** + * @attention INS任务的初始化不要放入实时系统!应该由application拥有实例,随后在 + * 应用层调用初始化函数. + * + ****************************************************************************** + */ +#ifndef __INS_TASK_H +#define __INS_TASK_H + +#include "stdint.h" +#include "BMI088driver.h" +#include "QuaternionEKF.h" + +#define X 0 +#define Y 1 +#define Z 2 + +#define INS_TASK_PERIOD 1 + +typedef struct +{ + float Gyro[3]; // 角速度 + float Accel[3]; // 加速度 + // 还需要增加角速度数据 + float Roll; + float Pitch; + float Yaw; + float YawTotalAngle; +} attitude_t; // 最终解算得到的角度,以及yaw转动的总角度(方便多圈控制) + +typedef struct +{ + float q[4]; // 四元数估计值 + + float MotionAccel_b[3]; // 机体坐标加速度 + float MotionAccel_n[3]; // 绝对系加速度 + + float AccelLPF; // 加速度低通滤波系数 + + // bodyframe在绝对系的向量表示 + float xn[3]; + float yn[3]; + float zn[3]; + + // 加速度在机体系和XY两轴的夹角 + // float atanxz; + // float atanyz; + + // IMU量测值 + float Gyro[3]; // 角速度 + float Accel[3]; // 加速度 + // 位姿 + float Roll; + float Pitch; + float Yaw; + float YawTotalAngle; + + uint8_t init; +} INS_t; + +/* 用于修正安装误差的参数 */ +typedef struct +{ + uint8_t flag; + + float scale[3]; + + float Yaw; + float Pitch; + float Roll; +} IMU_Param_t; + +/** + * @brief 初始化惯导解算系统 + * + */ +attitude_t *INS_Init(void); + +/** + * @brief 此函数放入实时系统中,以1kHz频率运行 + * p.s. osDelay(1); + * + */ +void INS_Task(void); + +/** + * @brief 四元数更新函数,即实现dq/dt=0.5Ωq + * + * @param q 四元数 + * @param gx + * @param gy + * @param gz + * @param dt 距离上次调用的时间间隔 + */ +void QuaternionUpdate(float *q, float gx, float gy, float gz, float dt); + +/** + * @brief 四元数转换成欧拉角 ZYX + * + * @param q + * @param Yaw + * @param Pitch + * @param Roll + */ +void QuaternionToEularAngle(float *q, float *Yaw, float *Pitch, float *Roll); + +/** + * @brief ZYX欧拉角转换为四元数 + * + * @param Yaw + * @param Pitch + * @param Roll + * @param q + */ +void EularAngleToQuaternion(float Yaw, float Pitch, float Roll, float *q); + +/** + * @brief 机体系到惯性系的变换函数 + * + * @param vecBF body frame + * @param vecEF earth frame + * @param q + */ +void BodyFrameToEarthFrame(const float *vecBF, float *vecEF, float *q); + +/** + * @brief 惯性系转换到机体系 + * + * @param vecEF + * @param vecBF + * @param q + */ +void EarthFrameToBodyFrame(const float *vecEF, float *vecBF, float *q); + +#endif diff --git a/modules/imu/ins_task.md b/modules/imu/ins_task.md new file mode 100644 index 0000000..5462027 --- /dev/null +++ b/modules/imu/ins_task.md @@ -0,0 +1,18 @@ +# ins_task + + neozng1@hnu.edu.cn
+ +## 硬触发流程 + + + +`times%10` 是固定相机的采集频率为100hz,请根据视觉算法实际能达到的最大帧率调整。 + +## 算法解析 + +介绍EKF四元数姿态解算的教程在:[四元数EKF姿态更新算法](https://zhuanlan.zhihu.com/p/454155643) + +## 模块移植 + +由于历史遗留问题,IMU模块耦合程度高.后续实现BSP_SPI,将bmi088 middleware删除.仅保留BMI088读取的协议和寄存器定义等,单独实现IMU模块. +> 移植已经完成,请转而使用module/BMI088的模块. 当前文件夹将在beta1.2停止支持, 1.5之后删除. INS_Task届时会被放到algorithm中,以提供对不同IMU的兼容. diff --git a/modules/ist8310/ist8310.c b/modules/ist8310/ist8310.c new file mode 100644 index 0000000..64abee2 --- /dev/null +++ b/modules/ist8310/ist8310.c @@ -0,0 +1,100 @@ +#include "bsp_dwt.h" +#include "ist8310.h" +#include "bsp_log.h" +#include+#include + +// 一般这个模块只有一个实例,所以直接保存在这里,实际上不保存也可以,application可以自己保存 +static IST8310Instance *ist8310_instance = NULL; // 用于存储IST8310实例的指针 + +#define IST8310_WRITE_REG_NUM 4 // 方便阅读 +#define IST8310_DATA_REG 0x03 // ist8310的数据寄存器 +#define IST8310_WHO_AM_I 0x00 // ist8310 id 寄存器值 +#define IST8310_WHO_AM_I_VALUE 0x10 // 用于检测是否连接成功,读取ist8310的whoami会返回该值 + +// -------------------初始化写入数组,只使用一次,详见datasheet------------------------- +// the first column:the registers of IST8310. 第一列:IST8310的寄存器 +// the second column: the value to be writed to the registers.第二列:需要写入的寄存器值 +// the third column: return error value.第三列:返回的错误码 +static uint8_t ist8310_write_reg_data_error[IST8310_WRITE_REG_NUM][3] = { + {0x0B, 0x08, 0x01}, // enalbe interrupt and low pin polarity.开启中断,并且设置低电平 + {0x41, 0x09, 0x02}, // average 2 times.平均采样两次 + {0x42, 0xC0, 0x03}, // must be 0xC0. 必须是0xC0 + {0x0A, 0x0B, 0x04}}; // 200Hz output rate.200Hz输出频率 + +/** + * @brief IST8310解码函数,EXTI中断来临时被调用,将数据放到ist.mag中 + * @note 如果使用IT或DMA方式传输IIC,则传输完成后也会进入此函数 + * + * @param ist 发生中断的IST8310实例 + */ +static void IST8310Decode(IICInstance *iic) +{ + int16_t temp[3]; // 用于存储解码后的数据 + IST8310Instance *ist = (IST8310Instance *)(iic->id); // iic的id保存了IST8310实例的指针(父指针) + + memcpy(temp, ist->iic_buffer, 6 * sizeof(uint8_t)); // 不要强制转换,直接cpy + for (uint8_t i = 0; i < 3; i++) + ist->mag[i] = (float)temp[i] * MAG_SEN; // 乘以灵敏度转换成uT(微特斯拉) +} + +/** + * @brief EXTI中断回调函数,说明DRDY拉低.主机启动传输并在结束后调用IST8310Decode进行数据解析 + * @note 注意IICAccessMem是阻塞的 + * + * @param gpio 发生中断的GPIO实例 + */ +static void IST8310StartTransfer(GPIOInstance *gpio) +{ + // 先获取IST8310实例的指针(通过gpio实例的父指针id) + IST8310Instance *ist_for_transfer = (IST8310Instance *)gpio->id; + // 中断说明ist已经准备好读取数据寄存器;6个字节,读取后会进入IST8310Decode函数 + IICAccessMem(ist_for_transfer->iic, IST8310_DATA_REG, ist_for_transfer->iic_buffer, 6, IIC_READ_MEM, 1); + // 传输完成后会进入IST8310Decode函数进行数据解析 + IST8310Decode(ist_for_transfer->iic); +} + +IST8310Instance *IST8310Init(IST8310_Init_Config_s *config) +{ + static const uint8_t sleepTime = 50; // 50ms,ist8310的复位时间 + uint8_t check_who_i_am = 0; // 用于检测ist8310是否连接成功 + // 这个变量只会用到一次,出了这个函数就没用了,所以不用分配空间,直接定义在栈上(因为多看一眼就会爆炸) + + // 分配空间,清除flash防止已经填充的垃圾值 + IST8310Instance *ist = (IST8310Instance *)malloc(sizeof(IST8310Instance)); + memset(ist, 0, sizeof(IST8310Instance)); + + // c语言赋值从右到左,全部指向同一个地址(这些bspinstnace的父节点都是ist,即ist拥有这些instances) + config->iic_config.id = config->gpio_conf_exti.id = config->gpio_conf_rst.id = ist; + // 传入回调函数 + config->iic_config.callback = IST8310Decode; + config->gpio_conf_exti.gpio_model_callback = IST8310StartTransfer; + // 分别注册两个GPIO和IIC + ist->iic = IICRegister(&config->iic_config); + ist->gpio_exti = GPIORegister(&config->gpio_conf_exti); + ist->gpio_rst = GPIORegister(&config->gpio_conf_rst); + + // 重置IST8310,需要HAL_Delay()等待传感器完成Reset + GPIOReset(ist->gpio_rst); + HAL_Delay(sleepTime); + GPIOSet(ist->gpio_rst); + HAL_Delay(sleepTime); + + // 读取IST8310的ID,如果不是0x10(whoami macro的值),则返回错误 + IICAccessMem(ist->iic, IST8310_WHO_AM_I, &check_who_i_am, 1, IIC_READ_MEM, 1); + if (check_who_i_am != IST8310_WHO_AM_I_VALUE) + return NULL; // while(1) + + // 进行初始化配置写入并检查是否写入成功,这里用循环把最上面初始化数组的东西都写进去 + for (uint8_t i = 0; i < IST8310_WRITE_REG_NUM; i++) + { // 写入配置,写一句就读一下看看ist8310是否仍然在线 + IICAccessMem(ist->iic, ist8310_write_reg_data_error[i][0], &ist8310_write_reg_data_error[i][1], 1, IIC_WRITE_MEM, 1); + IICAccessMem(ist->iic, ist8310_write_reg_data_error[i][0], &check_who_i_am, 1, IIC_READ_MEM, 1); // 读回自身id + if (check_who_i_am != ist8310_write_reg_data_error[i][1]) + while (1) + LOGERROR("[ist8310] init error, code %d", ist8310_write_reg_data_error[i][2]); // 掉线/写入失败/未知错误,会返回对应的错误码 + } + + ist8310_instance = ist; // 保存ist8310实例的指针 + return ist; +} diff --git a/modules/ist8310/ist8310.h b/modules/ist8310/ist8310.h new file mode 100644 index 0000000..30ab6b6 --- /dev/null +++ b/modules/ist8310/ist8310.h @@ -0,0 +1,50 @@ +#pragma once // 防止头文件重复包含,也可以用header guard + +#include "bsp_iic.h" +#include "bsp_gpio.h" +#include "stdint.h" + +// 传感器灵敏度系数 +#define MAG_SEN 0.3f // raw int16 data change to uT unit. 原始整型数据变成 单位ut + +// IST8310 ret ERROR CODE +#define IST8310_NO_ERROR 0x00 // seldom used. 一般不会用到 +#define IST8310_NO_SENSOR 0x40 // seldom used. 一般不会用到 +#define IST8310_IIC_ADDRESS 0x0E // the I2C slave address of IST8310 + +/** + * @brief IST8310 实例定义 + * @attention 配置GPIO Pin的时候注意使用GPIO_PIN_x(1,2,3,...,这是一个宏),而不是1,2,3的整形! + * + */ +typedef struct tempist8310 +{ + IICInstance *iic; // iic实例 + GPIOInstance *gpio_rst; // gpio实例,用于复位 + GPIOInstance *gpio_exti; // gpio实例,用于获取MAG_DRDY引脚状态,判断数据是否准备好(EXTI外部中断) + uint8_t iic_buffer[8]; // iic接收缓冲区 + float mag[3]; // 三轴磁力计数据,[x,y,z] + + void (*ist_module_callback)(IICInstance *); // 模块回调函数 + // 后续有需要再添加 + // ... +} IST8310Instance; + +/** + * @brief IST8310 初始化配置结构体 + * @attention 配置GPIO Pin的时候注意使用GPIO_PIN_x(1,2,3,...,这是一个宏),而不是1,2,3的整形! + * + */ +typedef struct +{ + IIC_Init_Config_s iic_config; // iic初始化配置 + GPIO_Init_Config_s gpio_conf_rst; // gpio初始化配置,用于复位ist8310,看数据手册 + GPIO_Init_Config_s gpio_conf_exti; // gpio初始化配置,用于获取MAG_DRDY引脚状态,判断数据是否准备好(EXTI外部中断) +} IST8310_Init_Config_s; + +/** + * @brief IST8310 初始化. + * @note 注意一条i2c总线只能挂载一个IST8310,他们的地址是固定的,不能改变. + * + */ +IST8310Instance *IST8310Init(IST8310_Init_Config_s *config); diff --git a/modules/ist8310/ist8310.md b/modules/ist8310/ist8310.md new file mode 100644 index 0000000..7ae5662 --- /dev/null +++ b/modules/ist8310/ist8310.md @@ -0,0 +1,30 @@ + +# ist8310 + +## 使用示例 + +```c +IST8310_Init_Config_s ist8310_conf = { + .gpio_conf_exti = { + .exti_mode = GPIO_EXTI_MODE_RISING, + .GPIO_Pin = GPIO_PIN_3, + .GPIOx = GPIOG, + .gpio_model_callback = NULL, + }, + .gpio_conf_rst = { + .exti_mode = GPIO_EXTI_MODE_NONE, + .GPIO_Pin = GPIO_PIN_6, + .GPIOx = GPIOG, + .gpio_model_callback = NULL, + }, + .iic_config = { + .handle = &hi2c3, + .dev_address = IST8310_IIC_ADDRESS, + .work_mode = IIC_BLOCK_MODE, + }, +}; + +IST8310Instance *asdf = IST8310Init(&ist8310_conf); + +// 随后数据会被放到asdf.mag[i]中,每次数据准备好了就会触发int_ist引脚中断,继而启动iic通信读取数据并解析 +``` diff --git a/modules/led/led.c b/modules/led/led.c new file mode 100644 index 0000000..276d86f --- /dev/null +++ b/modules/led/led.c @@ -0,0 +1,46 @@ +#include "led.h" +#include "stdlib.h" +#include "memory.h" +#include "user_lib.h" + +static uint8_t idx; +static LEDInstance *bsp_led_ins[LED_MAX_NUM] = {NULL}; + +LEDInstance *LEDRegister(LED_Init_Config_s *led_config) +{ + LEDInstance *led_ins = (LEDInstance *)zmalloc(sizeof(LEDInstance)); + // 剩下的值暂时都被置零 + led_ins->led_pwm = PWMRegister(&led_config->pwm_config); + led_ins->led_switch = led_config->init_swtich; + + bsp_led_ins[idx++] = led_ins; + return led_ins; +} + +void LEDSet(LEDInstance *_led, uint8_t alpha, uint8_t color_value, uint8_t brightness) +{ +} + +void LEDSwitch(LEDInstance *_led, uint8_t led_switch) +{ + if (led_switch == 1) + { + _led->led_switch = 1; + } + else + { + _led->led_switch = 0; + // PWMSetPeriod(_led,0); + } +} + +void LEDShow(uint32_t aRGB) +{ + // static uint8_t alpha; + // static uint16_t red, green, blue; + + // alpha = (aRGB & 0xFF000000) >> 24; + // red = ((aRGB & 0x00FF0000) >> 16) * alpha; + // green = ((aRGB & 0x0000FF00) >> 8) * alpha; + // blue = ((aRGB & 0x000000FF) >> 0) * alpha; +} diff --git a/modules/led/led.h b/modules/led/led.h new file mode 100644 index 0000000..0741315 --- /dev/null +++ b/modules/led/led.h @@ -0,0 +1,33 @@ +#ifndef _LED_H_ +#define _LED_H_ + +#include "stdint.h" +#include "bsp_pwm.h" + +#define LED_MAX_NUM 3 + +typedef struct +{ + PWMInstance* led_pwm; + uint8_t led_alpha; // 透明度,通过pwm频率改变 + uint8_t led_brightness; // 亮度,通过电压改变(如果可以,使用dac) + uint8_t led_color; // rgb value,0-255 + uint8_t led_switch; // 开关,on1 off0 + // void (*action_callback)(void); // led动作回调函数 +} LEDInstance; + +typedef struct +{ + PWM_Init_Config_s pwm_config; + uint8_t init_swtich; // 初始化开关 +} LED_Init_Config_s; + +LEDInstance* LEDRegister(LED_Init_Config_s* led_config); + +void LEDSet(LEDInstance *_led,uint8_t alpha,uint8_t color_value,uint8_t brightness); + +void LEDSwitch(LEDInstance *_led,uint8_t led_switch); + +void LEDShow(); + +#endif // !_LED_H_ diff --git a/modules/led/led.md b/modules/led/led.md new file mode 100644 index 0000000..e5b1e17 --- /dev/null +++ b/modules/led/led.md @@ -0,0 +1,3 @@ +TO BE DONE + +请勿使用 \ No newline at end of file diff --git a/modules/master_machine/master_process.c b/modules/master_machine/master_process.c new file mode 100644 index 0000000..057c8fd --- /dev/null +++ b/modules/master_machine/master_process.c @@ -0,0 +1,155 @@ +/** + * @file master_process.c + * @author neozng + * @brief module for recv&send vision data + * @version beta + * @date 2022-11-03 + * @todo 增加对串口调试助手协议的支持,包括vofa和serial debug + * @copyright Copyright (c) 2022 + * + */ +#include "master_process.h" +#include "seasky_protocol.h" +#include "daemon.h" +#include "bsp_log.h" +#include "robot_def.h" + +static Vision_Recv_s recv_data; +static Vision_Send_s send_data; +static DaemonInstance *vision_daemon_instance; + +void VisionSetFlag(Enemy_Color_e enemy_color, Work_Mode_e work_mode, Bullet_Speed_e bullet_speed) +{ + send_data.enemy_color = enemy_color; + send_data.work_mode = work_mode; + send_data.bullet_speed = bullet_speed; +} + +void VisionSetAltitude(float yaw, float pitch, float roll) +{ + send_data.yaw = yaw; + send_data.pitch = pitch; + send_data.roll = roll; +} + +/** + * @brief 离线回调函数,将在daemon.c中被daemon task调用 + * @attention 由于HAL库的设计问题,串口开启DMA接收之后同时发送有概率出现__HAL_LOCK()导致的死锁,使得无法 + * 进入接收中断.通过daemon判断数据更新,重新调用服务启动函数以解决此问题. + * + * @param id vision_usart_instance的地址,此处没用. + */ +static void VisionOfflineCallback(void *id) +{ +#ifdef VISION_USE_UART + USARTServiceInit(vision_usart_instance); +#endif // !VISION_USE_UART + LOGWARNING("[vision] vision offline, restart communication."); +} + +#ifdef VISION_USE_UART + +#include "bsp_usart.h" + +static USARTInstance *vision_usart_instance; + +/** + * @brief 接收解包回调函数,将在bsp_usart.c中被usart rx callback调用 + * @todo 1.提高可读性,将get_protocol_info的第四个参数增加一个float类型buffer + * 2.添加标志位解码 + */ +static void DecodeVision() +{ + uint16_t flag_register; + DaemonReload(vision_daemon_instance); // 喂狗 + get_protocol_info(vision_usart_instance->recv_buff, &flag_register, (uint8_t *)&recv_data.pitch); + // TODO: code to resolve flag_register; +} + +Vision_Recv_s *VisionInit(UART_HandleTypeDef *_handle) +{ + USART_Init_Config_s conf; + conf.module_callback = DecodeVision; + conf.recv_buff_size = VISION_RECV_SIZE; + conf.usart_handle = _handle; + vision_usart_instance = USARTRegister(&conf); + + // 为master process注册daemon,用于判断视觉通信是否离线 + Daemon_Init_Config_s daemon_conf = { + .callback = VisionOfflineCallback, // 离线时调用的回调函数,会重启串口接收 + .owner_id = vision_usart_instance, + .reload_count = 10, + }; + vision_daemon_instance = DaemonRegister(&daemon_conf); + + return &recv_data; +} + +/** + * @brief 发送函数 + * + * @param send 待发送数据 + * + */ +void VisionSend() +{ + // buff和txlen必须为static,才能保证在函数退出后不被释放,使得DMA正确完成发送 + // 析构后的陷阱需要特别注意! + static uint16_t flag_register; + static uint8_t send_buff[VISION_SEND_SIZE]; + static uint16_t tx_len; + // TODO: code to set flag_register + flag_register = 30 << 8 | 0b00000001; + // 将数据转化为seasky协议的数据包 + get_protocol_send_data(0x02, flag_register, &send_data.yaw, 3, send_buff, &tx_len); + USARTSend(vision_usart_instance, send_buff, tx_len, USART_TRANSFER_DMA); // 和视觉通信使用IT,防止和接收使用的DMA冲突 + // 此处为HAL设计的缺陷,DMASTOP会停止发送和接收,导致再也无法进入接收中断. + // 也可在发送完成中断中重新启动DMA接收,但较为复杂.因此,此处使用IT发送. + // 若使用了daemon,则也可以使用DMA发送. +} + +#endif // VISION_USE_UART + +#ifdef VISION_USE_VCP + +#include "bsp_usb.h" +static uint8_t *vis_recv_buff; + +static void DecodeVision(uint16_t recv_len) +{ + uint16_t flag_register; + get_protocol_info(vis_recv_buff, &flag_register, (uint8_t *)&recv_data.pitch); + // TODO: code to resolve flag_register; +} + +/* 视觉通信初始化 */ +Vision_Recv_s *VisionInit(UART_HandleTypeDef *_handle) +{ + UNUSED(_handle); // 仅为了消除警告 + USB_Init_Config_s conf = {.rx_cbk = DecodeVision}; + vis_recv_buff = USBInit(conf); + + // 为master process注册daemon,用于判断视觉通信是否离线 + Daemon_Init_Config_s daemon_conf = { + .callback = VisionOfflineCallback, // 离线时调用的回调函数,会重启串口接收 + .owner_id = NULL, + .reload_count = 5, // 50ms + }; + vision_daemon_instance = DaemonRegister(&daemon_conf); + + return &recv_data; +} + +void VisionSend() +{ + static uint16_t flag_register; + static uint8_t send_buff[VISION_SEND_SIZE]; + static uint16_t tx_len; + // TODO: code to set flag_register + flag_register = 30 << 8 | 0b00000001; + // 将数据转化为seasky协议的数据包 + get_protocol_send_data(0x02, flag_register, &send_data.yaw, 3, send_buff, &tx_len); + USBTransmit(send_buff, tx_len); +} + +#endif // VISION_USE_VCP diff --git a/modules/master_machine/master_process.h b/modules/master_machine/master_process.h new file mode 100644 index 0000000..e8668be --- /dev/null +++ b/modules/master_machine/master_process.h @@ -0,0 +1,114 @@ +#ifndef MASTER_PROCESS_H +#define MASTER_PROCESS_H + +#include "bsp_usart.h" +#include "seasky_protocol.h" + +#define VISION_RECV_SIZE 18u // 当前为固定值,36字节 +#define VISION_SEND_SIZE 36u + +#pragma pack(1) +typedef enum +{ + NO_FIRE = 0, + AUTO_FIRE = 1, + AUTO_AIM = 2 +} Fire_Mode_e; + +typedef enum +{ + NO_TARGET = 0, + TARGET_CONVERGING = 1, + READY_TO_FIRE = 2 +} Target_State_e; + +typedef enum +{ + NO_TARGET_NUM = 0, + HERO1 = 1, + ENGINEER2 = 2, + INFANTRY3 = 3, + INFANTRY4 = 4, + INFANTRY5 = 5, + OUTPOST = 6, + SENTRY = 7, + BASE = 8 +} Target_Type_e; + +typedef struct +{ + Fire_Mode_e fire_mode; + Target_State_e target_state; + Target_Type_e target_type; + + float pitch; + float yaw; +} Vision_Recv_s; + +typedef enum +{ + COLOR_NONE = 0, + COLOR_BLUE = 1, + COLOR_RED = 2, +} Enemy_Color_e; + +typedef enum +{ + VISION_MODE_AIM = 0, + VISION_MODE_SMALL_BUFF = 1, + VISION_MODE_BIG_BUFF = 2 +} Work_Mode_e; + +typedef enum +{ + BULLET_SPEED_NONE = 0, + BIG_AMU_10 = 10, + SMALL_AMU_15 = 15, + BIG_AMU_16 = 16, + SMALL_AMU_18 = 18, + SMALL_AMU_30 = 30, +} Bullet_Speed_e; + +typedef struct +{ + Enemy_Color_e enemy_color; + Work_Mode_e work_mode; + Bullet_Speed_e bullet_speed; + + float yaw; + float pitch; + float roll; +} Vision_Send_s; +#pragma pack() + +/** + * @brief 调用此函数初始化和视觉的串口通信 + * + * @param handle 用于和视觉通信的串口handle(C板上一般为USART1,丝印为USART2,4pin) + */ +Vision_Recv_s *VisionInit(UART_HandleTypeDef *_handle); + +/** + * @brief 发送视觉数据 + * + */ +void VisionSend(); + +/** + * @brief 设置视觉发送标志位 + * + * @param enemy_color + * @param work_mode + * @param bullet_speed + */ +void VisionSetFlag(Enemy_Color_e enemy_color, Work_Mode_e work_mode, Bullet_Speed_e bullet_speed); + +/** + * @brief 设置发送数据的姿态部分 + * + * @param yaw + * @param pitch + */ +void VisionSetAltitude(float yaw, float pitch, float roll); + +#endif // !MASTER_PROCESS_H \ No newline at end of file diff --git a/modules/master_machine/master_process.md b/modules/master_machine/master_process.md new file mode 100644 index 0000000..e81e949 --- /dev/null +++ b/modules/master_machine/master_process.md @@ -0,0 +1,133 @@ +# master_process + + + + neozng1@hnu.edu.cn
+ +> TODO: +> +> 1. 补全标志位解析和发送设置的代码 +> 2. 增加发送给视觉数据的时间戳用于数据对齐 + + + +## 总览和封装说明 + +模块包含了和视觉通信的初始化、向上位机发送信息的接口和模块的串口的回调处理。接口的定义统一,可以方便的替换成其他通信方式,如CAN。 + +## 代码结构 + +.h文件内包括了外部接口和与**视觉上位机通信的数据结构定义**,以及模块对应的宏。c文件内为私有函数和外部接口的定义。 + +本模块主要是对协议解析的处理和协议发送的封装,实际内容不多。协议相关内容都在`seasky_protocol.h`中。 + +## 类型定义 + +和视觉通信所必须的标志位和数据。包括开火模式,目标状态,目标类型,接收/发送数据结构体。 + +```c +typedef enum +{ + NO_FIRE = 0, + AUTO_FIRE = 1, + AUTO_AIM = 2 +} Fire_Mode_e; + +typedef enum +{ + NO_TARGET = 0, + TARGET_CONVERGING = 1, + READY_TO_FIRE = 2 +} Target_State_e; + +typedef enum +{ + NO_TARGET_NUM = 0, + HERO1 = 1, + ENGINEER2 = 2, + INFANTRY3 = 3, + INFANTRY4 = 4, + INFANTRY5 = 5, + OUTPOST = 6, + SENTRY = 7, + BASE = 8 +} Target_Type_e; + +typedef struct +{ + Fire_Mode_e fire_mode; + Target_State_e target_state; + Target_Type_e target_type; + + float pitch; + float yaw; +} Vision_Recv_s; + +typedef enum +{ + BLUE = 0, + RED = 1 +} Enemy_Color_e; + +typedef enum +{ + MODE_AIM = 0, + MODE_SMALL_BUFF = 1, + MODE_BIG_BUFF = 2 +} Work_Mode_e; + +typedef enum +{ + BIG_AMU_10 = 10, + SMALL_AMU_15 = 15, + BIG_AMU_16 = 16, + SMALL_AMU_18 = 18, + SMALL_AMU_30 = 30, +} Bullet_Speed_e; + +typedef struct +{ + Enemy_Color_e enemy_color; + Work_Mode_e work_mode; + Bullet_Speed_e bullet_speed; + + float yaw; + float pitch; + float roll; +} Vision_Send_s; +``` + +## 外部接口 + +```c +Vision_Recv_s *VisionInit(UART_HandleTypeDef *_handle); + +void VisionSend(Vision_Send_s *send); +``` + +给`VisionInit()`传入串口handle,将初始化一个视觉通信模块,返回值是接收数据的结构体指针。拥有视觉模块的应用应该在初始化中调用此函数,并保存返回值的指针。 + +调用`VisionSend`并传入填好发送数据的结构体,会通过底层的通信模块向视觉发送一帧报文。 + +## 私有函数和变量 + +```c +static Vision_Recv_s recv_data; + +static usart_instance *vision_usart_instance; + +static void DecodeVision() +{ + static uint16_t flag_register; + get_protocol_info(vision_usart_instance->recv_buff, &flag_register, (uint8_t*)&recv_data.pitch); + // TODO: code to resolve flag_register; +} +``` + +第一个是保存接收数据的结构体,其指针将会在初始化的时候返回给拥有者。目前最多只能配置一个视觉模块。 + +第二个是该模块拥有的串口实例指针,用于调度其底层的发送和接收。如果要换成CAN/SPI等,替换成对应实例,并修改初始化和发送的实现即可。 + +`DecodeVision()`是解析视觉接收数据的回调函数,会在串口接收回调中被调用。如果修改通信协议,只需要更改 + +`get_protocol_info()`。 \ No newline at end of file diff --git a/modules/master_machine/seasky_protocol.c b/modules/master_machine/seasky_protocol.c new file mode 100644 index 0000000..85304dd --- /dev/null +++ b/modules/master_machine/seasky_protocol.c @@ -0,0 +1,133 @@ +/** + * @file seasky_protocol.c + * @author Liu Wei + * @author modified by Neozng + * @brief 湖南大学RoBoMatster串口通信协议 + * @version 0.1 + * @date 2022-11-03 + * + * @copyright Copyright (c) 2022 + * + */ + +#include "seasky_protocol.h" +#include "crc8.h" +#include "crc16.h" +#include "memory.h" + +/*获取CRC8校验码*/ +uint8_t Get_CRC8_Check(uint8_t *pchMessage,uint16_t dwLength) +{ + return crc_8(pchMessage,dwLength); +} +/*检验CRC8数据段*/ +static uint8_t CRC8_Check_Sum(uint8_t *pchMessage, uint16_t dwLength) +{ + uint8_t ucExpected = 0; + if ((pchMessage == 0) || (dwLength <= 2)) + return 0; + ucExpected = crc_8(pchMessage, dwLength - 1); + return (ucExpected == pchMessage[dwLength - 1]); +} + +/*获取CRC16校验码*/ +uint16_t Get_CRC16_Check(uint8_t *pchMessage,uint32_t dwLength) +{ + return crc_16(pchMessage,dwLength); +} + +/*检验CRC16数据段*/ +static uint16_t CRC16_Check_Sum(uint8_t *pchMessage, uint32_t dwLength) +{ + uint16_t wExpected = 0; + if ((pchMessage == 0) || (dwLength <= 2)) + { + return 0; + } + wExpected = crc_16(pchMessage, dwLength - 2); + return (((wExpected & 0xff) == pchMessage[dwLength - 2]) && (((wExpected >> 8) & 0xff) == pchMessage[dwLength - 1])); +} + +/*检验数据帧头*/ +static uint8_t protocol_heade_Check(protocol_rm_struct *pro, uint8_t *rx_buf) +{ + if (rx_buf[0] == PROTOCOL_CMD_ID) + { + pro->header.sof = rx_buf[0]; + if (CRC8_Check_Sum(&rx_buf[0], 4)) + { + pro->header.data_length = (rx_buf[2] << 8) | rx_buf[1]; + pro->header.crc_check = rx_buf[3]; + pro->cmd_id = (rx_buf[5] << 8) | rx_buf[4]; + return 1; + } + } + return 0; +} + +/* + 此函数根据待发送的数据更新数据帧格式以及内容,实现数据的打包操作 + 后续调用通信接口的发送函数发送tx_buf中的对应数据 +*/ +void get_protocol_send_data(uint16_t send_id, // 信号id + uint16_t flags_register, // 16位寄存器 + float *tx_data, // 待发送的float数据 + uint8_t float_length, // float的数据长度 + uint8_t *tx_buf, // 待发送的数据帧 + uint16_t *tx_buf_len) // 待发送的数据帧长度 +{ + static uint16_t crc16; + static uint16_t data_len; + + data_len = float_length * 4 + 2; + /*帧头部分*/ + tx_buf[0] = PROTOCOL_CMD_ID; + tx_buf[1] = data_len & 0xff; // 低位在前 + tx_buf[2] = (data_len >> 8) & 0xff; // 低位在前 + tx_buf[3] = crc_8(&tx_buf[0], 3); // 获取CRC8校验位 + + /*数据的信号id*/ + tx_buf[4] = send_id & 0xff; + tx_buf[5] = (send_id >> 8) & 0xff; + + /*建立16位寄存器*/ + tx_buf[6] = flags_register & 0xff; + tx_buf[7] = (flags_register >> 8) & 0xff; + + /*float数据段*/ + for (int i = 0; i < 4 * float_length; i++) + { + tx_buf[i + 8] = ((uint8_t *)(&tx_data[i / 4]))[i % 4]; + } + + /*整包校验*/ + crc16 = crc_16(&tx_buf[0], data_len + 6); + tx_buf[data_len + 6] = crc16 & 0xff; + tx_buf[data_len + 7] = (crc16 >> 8) & 0xff; + + *tx_buf_len = data_len + 8; +} +/* + 此函数用于处理接收数据, + 返回数据内容的id +*/ +uint16_t get_protocol_info(uint8_t *rx_buf, // 接收到的原始数据 + uint16_t *flags_register, // 接收数据的16位寄存器地址 + uint8_t *rx_data) // 接收的float数据存储地址 +{ + // 放在静态区,避免反复申请栈上空间 + static protocol_rm_struct pro; + static uint16_t date_length; + + if (protocol_heade_Check(&pro, rx_buf)) + { + date_length = OFFSET_BYTE + pro.header.data_length; + if (CRC16_Check_Sum(&rx_buf[0], date_length)) + { + *flags_register = (rx_buf[7] << 8) | rx_buf[6]; + memcpy(rx_data, rx_buf + 8, pro.header.data_length - 2); + return pro.cmd_id; + } + } + return 0; +} diff --git a/modules/master_machine/seasky_protocol.h b/modules/master_machine/seasky_protocol.h new file mode 100644 index 0000000..5c24c43 --- /dev/null +++ b/modules/master_machine/seasky_protocol.h @@ -0,0 +1,36 @@ +#ifndef __SEASKY_PROTOCOL_H +#define __SEASKY_PROTOCOL_H + +#include+#include + +#define PROTOCOL_CMD_ID 0XA5 +#define OFFSET_BYTE 8 // 出数据段外,其他部分所占字节数 + +typedef struct +{ + struct + { + uint8_t sof; + uint16_t data_length; + uint8_t crc_check; // 帧头CRC校验 + } header; // 数据帧头 + uint16_t cmd_id; // 数据ID + uint16_t frame_tail; // 帧尾CRC校验 +} protocol_rm_struct; + + +/*更新发送数据帧,并计算发送数据帧长度*/ +void get_protocol_send_data(uint16_t send_id, // 信号id + uint16_t flags_register, // 16位寄存器 + float *tx_data, // 待发送的float数据 + uint8_t float_length, // float的数据长度 + uint8_t *tx_buf, // 待发送的数据帧 + uint16_t *tx_buf_len); // 待发送的数据帧长度 + +/*接收数据处理*/ +uint16_t get_protocol_info(uint8_t *rx_buf, // 接收到的原始数据 + uint16_t *flags_register, // 接收数据的16位寄存器地址 + uint8_t *rx_data); // 接收的float数据存储地址 + +#endif diff --git a/modules/master_machine/湖南大学RoboMaster电控组通信协议.md b/modules/master_machine/湖南大学RoboMaster电控组通信协议.md new file mode 100644 index 0000000..6cb3b38 --- /dev/null +++ b/modules/master_machine/湖南大学RoboMaster电控组通信协议.md @@ -0,0 +1,73 @@ +# 湖南大学RoboMaster电控组通信协议 + + Seasky LIUWei
+ +modified by neozng1@hnu.edu.cn
+ +可用于视觉,以及其他自研模块(仅限串口通信) + +> TODO: +> +> 1. 利用F4自带的硬件CRC模块计算校验码,提高速度 +> 2. 增加更多的数据类型支持,使得数据类型也为可配置的 + +## 一、串口配置 + +通信方式是串口,配置为波特率 921600,8 位数据位,1 位停止位,无硬件流控,无校验位。 + +## 二、数据帧说明 + +以下所有低位在前发送,数据长度可变。 + +1. 通信协议格式 + + | 帧头 | 数据ID | 数据 | 帧尾 | + | ----------------------- | -------------- | ------------- | :---------------------------------- | + | protocol_header(4-byte) | cmd_id(2-byte) | data (n-byte) | frame_tail(2-byte,CRC16,整包校验) | + +2. 帧头详细定义 + + | 帧头 | 偏移位置 | 字节大小 | 内容 | + | ----------- | -------- | -------- | ----------------------------- | + | sof(CMD) | 0 | 1 | 数据帧起始字节,固定值为 0xA5 | + | data_length | 1 | 2 | 数据帧中 data 的长度 | + | crc_check | 3 | 1 | 帧头CRC校验 | + +3. cmd_id 命令码 ID 说明 **(字节偏移 4,字节大小 2)** + + | 命令码 | 数据段长度 | 功能说明 | + | -------------- | --------------- | -------- | + | 0x0001(可修改) | 2 byte (16-bit) | 视觉数据 | + | ....... | | | + +4. 数据段data (n-byte) + + | 数据 | 偏移位置 | 字节大小 | 内容 | + | -------------- | -------- | --------------- | ------------------------------------- | + | flags_register | 6 | 2 | 16位标志置位寄存器 | + | float_data | 8 | 4 * data_length | float数据内容(4 * data_length-byte) | + +5. frame_tail(CRC16,整包校验) + +## 三、协议接口说明 + +```c +/*更新发送数据帧,并计算发送数据帧长度*/ +void get_protocol_send_data(uint16_t send_id, //信号id + uint16_t flags_register, // 16位寄存器 + float *tx_data, //待发送的float数据 + uint8_t float_length, // float的数据长度 + uint8_t *tx_buf, //待发送的数据帧 + uint16_t *tx_buf_len); //待发送的数据帧长度 +``` + +将float_data字段准备好放入`tx_data[]`并设置好标志位`flags_register`之后,调用此函数。它将计算循环冗余校验码,并把数据转换成串口发送的格式,放在`tx_buf[]`中。 + +```c +/*接收数据处理*/ +uint16_t get_protocol_info(uint8_t *rx_buf, //接收到的原始数据 + uint16_t *flags_register, //接收数据的16位寄存器地址 + float *rx_data); //接收的float数据存储地址 +``` + +将收到的一包原始数据buff地址传入,若校验通过,会把收到的标志位和float数据解析出来,保存在`flags_register*`和 `rx_data[]`中。 \ No newline at end of file diff --git a/modules/message_center/message_center.c b/modules/message_center/message_center.c new file mode 100644 index 0000000..2509f59 --- /dev/null +++ b/modules/message_center/message_center.c @@ -0,0 +1,117 @@ +#include "message_center.h" +#include "stdlib.h" +#include "string.h" +#include "bsp_log.h" + +/* message_center是fake head node,是方便链表编写的技巧,这样就不需要处理链表头的特殊情况 */ +static Publisher_t message_center = { + .topic_name = "Message_Manager", + .first_subs = NULL, + .next_topic_node = NULL}; + +static void CheckName(char *name) +{ + if (strnlen(name, MAX_TOPIC_NAME_LEN + 1) >= MAX_TOPIC_NAME_LEN) + { + LOGERROR("EVENT NAME TOO LONG:%s", name); + while (1) + ; // 进入这里说明话题名超出长度限制 + } +} + +static void CheckLen(uint8_t len1, uint8_t len2) +{ + if (len1 != len2) + { + LOGERROR("EVENT LEN NOT SAME:%d,%d", len1, len2); + while (1) + ; // 进入这里说明相同话题的消息长度却不同 + } +} + +Publisher_t *PubRegister(char *name, uint8_t data_len) +{ + CheckName(name); + Publisher_t *node = &message_center; + while (node->next_topic_node) // message_center会直接跳过,不需要特殊处理,这被称作dumb_head(编程技巧) + { + node = node->next_topic_node; // 切换到下一个发布者(话题)结点 + if (strcmp(node->topic_name, name) == 0) // 如果已经注册了相同的话题,直接返回结点指针 + { + CheckLen(data_len, node->data_len); + node->pub_registered_flag = 1; + return node; + } + } // 遍历完发现尚未创建name对应的话题 + // 在链表尾部创建新的话题并初始化 + node->next_topic_node = (Publisher_t *)malloc(sizeof(Publisher_t)); + memset(node->next_topic_node, 0, sizeof(Publisher_t)); + node->next_topic_node->data_len = data_len; + strcpy(node->next_topic_node->topic_name, name); + node->pub_registered_flag = 1; + return node->next_topic_node; +} + +Subscriber_t *SubRegister(char *name, uint8_t data_len) +{ + Publisher_t *pub = PubRegister(name, data_len); // 查找或创建该话题的发布者 + // 创建新的订阅者结点,申请内存,注意要memset因为新空间不一定是空的,可能有之前留存的垃圾值 + Subscriber_t *ret = (Subscriber_t *)malloc(sizeof(Subscriber_t)); + memset(ret, 0, sizeof(Subscriber_t)); + // 对新建的Subscriber进行初始化 + ret->data_len = data_len; // 设定数据长度 + for (size_t i = 0; i < QUEUE_SIZE; ++i) + { // 给消息队列的每一个元素分配空间,queue里保存的实际上是数据执指针,这样可以兼容不同的数据长度 + ret->queue[i] = malloc(data_len); + } + // 如果是第一个订阅者,特殊处理一下,将first_subs指针指向新建的订阅者(详见文档) + if (pub->first_subs == NULL) + { + pub->first_subs = ret; + return ret; + } + // 若该话题已经有订阅者, 遍历订阅者链表,直到到达尾部 + Subscriber_t *sub = pub->first_subs; // 作为iterator + while (sub->next_subs_queue) // 遍历订阅了该话题的订阅者链表 + { + sub = sub->next_subs_queue; // 移动到下一个订阅者,遇到空指针停下,说明到了链表尾部 + } + sub->next_subs_queue = ret; // 把刚刚创建的订阅者接上 + return ret; +} + +/* 如果队列为空,会返回0;成功获取数据,返回1;后续可以做更多的修改,比如剩余消息数目等 */ +uint8_t SubGetMessage(Subscriber_t *sub, void *data_ptr) +{ + if (sub->temp_size == 0) + { + return 0; + } + memcpy(data_ptr, sub->queue[sub->front_idx], sub->data_len); + sub->front_idx = (sub->front_idx++) % QUEUE_SIZE; // 队列头索引增加 + sub->temp_size--; // pop一个数据,长度减1 + return 1; +} + +uint8_t PubPushMessage(Publisher_t *pub, void *data_ptr) +{ + static Subscriber_t *iter; + iter = pub->first_subs; // iter作为订阅者指针,遍历订阅该话题的所有订阅者;如果为空说明遍历结束 + // 遍历订阅了当前话题的所有订阅者,依次填入最新消息 + while (iter) + { + if (iter->temp_size == QUEUE_SIZE) // 如果队列已满,则需要删除最老的数据(头部),再填入 + { + // 队列头索引前移动,相当于抛弃前一个位置的数据,被抛弃的位置稍后会被写入新的数据 + iter->front_idx = (iter->front_idx + 1) % QUEUE_SIZE; + iter->temp_size--; // 相当于出队,size-1 + } + // 将Pub的数据复制到队列的尾部(最新) + memcpy(iter->queue[iter->back_idx], data_ptr, pub->data_len); + iter->back_idx = (iter->back_idx + 1) % QUEUE_SIZE; // 队列尾部前移 + iter->temp_size++; // 入队,size+1 + + iter = iter->next_subs_queue; // 访问下一个订阅者 + } + return 1; +} \ No newline at end of file diff --git a/modules/message_center/message_center.h b/modules/message_center/message_center.h new file mode 100644 index 0000000..f9e89e7 --- /dev/null +++ b/modules/message_center/message_center.h @@ -0,0 +1,85 @@ +/** + * @file message_center.h + * @author NeoZeng neozng1@hnu.edu.cn + * @brief 这是一个伪pubsub机制,仅对应用之间的通信进行了隔离 + * @version 0.1 + * @date 2022-11-30 + * + * @copyright Copyright (c) 2022 + * + */ + +#ifndef PUBSUB_H +#define PUBSUB_H + +#include "stdint.h" + +#define MAX_TOPIC_NAME_LEN 32 // 最大的话题名长度,每个话题都有字符串来命名 +#define MAX_TOPIC_COUNT 12 // 最多支持的话题数量 +#define QUEUE_SIZE 1 + +typedef struct mqt +{ + /* 用数组模拟FIFO队列 */ + void *queue[QUEUE_SIZE]; + uint8_t data_len; + uint8_t front_idx; + uint8_t back_idx; + uint8_t temp_size; // 当前队列长度 + + /* 指向下一个订阅了相同的话题的订阅者的指针 */ + struct mqt *next_subs_queue; // 使得发布者可以通过链表访问所有订阅了相同话题的订阅者 +} Subscriber_t; + +/** + * @brief 发布者类型.每个发布者拥有发布者实例,并且可以通过链表访问所有订阅了自己发布的话题的订阅者 + * + */ +typedef struct ent +{ + /* 话题名称 */ + char topic_name[MAX_TOPIC_NAME_LEN + 1]; // 1个字节用于存放字符串结束符 '\0' + uint8_t data_len; // 该话题的数据长度 + /* 指向第一个订阅了该话题的订阅者,通过链表访问所有订阅者 */ + Subscriber_t *first_subs; + /* 指向下一个Publisher的指针 */ + struct ent *next_topic_node; + uint8_t pub_registered_flag; // 用于标记该发布者是否已经注册 +} Publisher_t; + +/** + * @brief 订阅name的话题消息 + * + * @param name 话题名称 + * @param data_len 消息长度,通过sizeof()获取 + * @return Subscriber_t* 返回订阅者实例 + */ +Subscriber_t *SubRegister(char *name, uint8_t data_len); + +/** + * @brief 注册成为消息发布者 + * + * @param name 发布者发布的话题名称(话题) + * @return Publisher_t* 返回发布者实例 + */ +Publisher_t *PubRegister(char *name, uint8_t data_len); + +/** + * @brief 获取消息 + * + * @param sub 订阅者实例指针 + * @param data_ptr 数据指针,接收的消息将会放到此处 + * @return uint8_t 返回值为0说明没有新的消息(消息队列为空),为1说明获取到了新的消息 + */ +uint8_t SubGetMessage(Subscriber_t *sub, void *data_ptr); + +/** + * @brief 发布者给所有订阅了话题的订阅者推送消息 + * + * @param pub 发布者实例指针 + * @param data_ptr 指向要发布的数据的指针 + * @return uint8_t 新消息成功推送给几个订阅者 + */ +uint8_t PubPushMessage(Publisher_t *pub, void *data_ptr); + +#endif // !PUBSUB_H \ No newline at end of file diff --git a/modules/message_center/message_center.md b/modules/message_center/message_center.md new file mode 100644 index 0000000..ceed509 --- /dev/null +++ b/modules/message_center/message_center.md @@ -0,0 +1,180 @@ +# message_center + +neozng1@hnu.edu.cn
+ +> TODO: +> +> 支持自定义队列长度,使得订阅者可以自行确定需要的队列长度,适应不同的需求 + +## 总览和封装说明 + +**重要定义:** + +- 发布者:发布消息的对象。发布者会将自己的消息推送给所有订阅了某个特定**话题**的订阅者。 +- 订阅者:获取消息的对象。订阅者在订阅了某个话题之后,可以通过接口获得该话题的消息。 +- 话题(topic):用于区分消息来源的对象。可以将一个话题看作一刊杂志,不同的发布者会将文章汇集到杂志上,而订阅者选择订阅一种杂志,然后就可以获取所有写在杂志上的文章。 + +Message Center不同应用间进行消息传递的中介,它的存在可以在相当大的程度上解耦不同的app,使得不同的应用之间**不存在包含关系**,让代码的自由度更大,将不同模块之间的关系降为**松耦合**。在以往,如果一个.c文件中的数据需要被其他任务/源文件共享,那么其他模块应该要包含前者的头文件,且头文件中应当存在获取该模块数据的接口(即函数,一般是返回数据指针或直接返回数据,**强烈建议不要使用全局变量**);但现在,不同的应用之间完全隔离,他们不需要了解彼此的存在,而是只能看见一个**消息中心**以及一些**话题**。 + +需要被共享的消息,将会被**发布者**(publisher)发送到消息中心;要获取消息,则由**订阅者**(subscriber)从消息中心根据订阅的话题获取。在这之前,发布者要在消息中心完成**注册**,将自己要发布的消息类型和话题名称提交到消息中心;订阅者同样要先在消息中心完成订阅,将自己要接收的消息类型和话题名称提交到订阅中心。消息中心会根据**话题名称**,把订阅者绑定到发布相同名称的发布者上。 + +> 为了节省空间,数据结构上采用了链表+循环数组模拟队列的方式。C没有哈希表,因此让发布者保存所有订阅者的地址(实际上只保存首地址,然后通过链表访问所有订阅者)。 + +Message Center对外提供了四个接口,所有原本要进行信息交互的应用都应该包含`message_center.h`,并在初始化的时候进行注册。 + +## 代码结构 + +.h 文件中包含了外部接口和类型定义,.c中包含了各个接口的具体实现。 + +## 外部接口 + +**在代码实现上,话题名实际上就是通过一个字符串体现的。** + +```c +Subscriber_t* SubRegister(char* name,uint8_t data_len); + +Publisher_t* PubRegister(char* name,uint8_t data_len); + +uint8_t SubGetMessage(Subscriber_t* sub,void* data_ptr); + +void PubPushMessage(Publisher_t* pub,void* data_ptr); +``` + +### 订阅者 + +订阅者应该保存一个订阅者类型的指针`Subscriber_t*`,在初始化的时候调用`SubRegister()`并传入要订阅的话题名和该话题对应消息的长度,可以直接输入字符串,示例如下,将从event_name订阅float数据: + +```c +Subscriber_t* my_sub; +my_sub=SubRegister("event_name",sizeof(float)); +``` + +订阅完毕后,在应用中通过`SubGetMessage()`获取消息,调用时传入订阅时获得的指针,以及要存放数据的指针。在使用的时候,建议使用强制类型转换将`data_ptr` cast成void*类型(好习惯)。 + +如果消息队列中有消息,返回值为1;否则,返回值为0,说明没有新的消息可用。 + +### 发布者 + +发布者应该保存一个发布者类型的指针,在初始化的时候传入要发布的话题名和该话题对应的消息长度。 + +完成注册后,通过`PubPushMessage()`发布新的消息。所有订阅了该话题的订阅者都会收到新的消息推送。 + +### 可修改的宏 + +```c +#define MAX_EVENT_NAME_LEN 32 //最大的话题名长度,每个话题都由字符串来命名 +#define QUEUE_SIZE 1 //消息队列的长度 +``` + +修改第一个可以扩大话题名长度,第二个确定消息队列的长度,数量越大可以保存的消息越多。 + +## 私有函数和定义 + +```c +static Publisher_t message_center = { + .event_name = "Message_Manager", + .first_subs = NULL, + .next_event_node = NULL}; + +static void CheckName(char* name) +{ + if(strnlen(name,MAX_EVENT_NAME_LEN+1)>=MAX_EVENT_NAME_LEN) + { + while (1); // 进入这里说明话题名超出长度限制 + } +} +``` + +`message_center`内部保存了指向第一个发布者的指针,可以看作整个消息中心的抽象。通过这个变量,可以访问所有发布者和订阅者。它将会在各个函数中作为dumb_head(哑结点)以简化逻辑,这样不需要对链表头进行特殊处理。 + +`CheckName()`在发布者/订阅者注册的时候被调用,用于检查话题名是否超过长度限制。超长后会进入死循环,方便开发者检查。 + +> 四个外部接口的实现都有详细的注释,有兴趣的同学可以自行阅读。下方也提供了流程图。 + +## 注册、发布、获取消息流程 + +包含一个结构图和四个流程图。 + +### Message Center的结构 + +建议打开原图查看 + +**多个publisher可以绑定同一个话题,往该话题推送消息。但一个subscriber只能订阅一个话题,如果应用需要订阅多个话题,则要创建对应数量的订阅者。** + +> 对于电控程序目前的情况,不存在多个publisher向同一个话题推送消息的情况。 + +**对于相同话题,其消息长度必须相同**。发布者和订阅者在注册时都会传入消息长度,用`sizof(your_data)`获取。应当保证不同的模块在进行交互式,使用相同的数据长度。 + +### 发布者和订阅者注册的流程 + +- **发布者:** + + 遍历发布者的话题结点,如果发现相同的话题,直接返回指针即可;遍历完成后发现尚未创建则创建新的话题。 + ++ +- **订阅者:** + + 需要注意,由于不同应用/模块的初始化顺序不同,可能出现订阅者先于发布者订阅某一消息的情况,所以要进行发布者链表的遍历,判断是否已经存在相同话题名的发布者,不存在则要先创建发布者结点再将新建订阅者结点并挂载到前者上。 + +
+ +### 推送/获取消息的流程 + +- **数组+头尾索引模拟队列** + +
+ +front指向队列头,即最早入队的数据;back指向队列尾,即最新的数据。队列是first in first out(FIFO,先进先出)的结构。back指向的位置是入队数据被写入的位置,front指向的是读取时会出队的位置。当有数据入队,back++;出队则front++。若碰到数组边界,则返回数组头,可以通过取模实现: + +```C +idx=(idx+1)%SIZE_OF_ARRAY; //SIZE_OF_ARRAY是数组大小 +``` + +我们还需要一个变量用于保存当前队列的元素个数,如果在写入时,队列长度等于上限,应该先将最老的数据出队,再写入新的数据,即: + +```c +back=(back+1)%SIZE_OF_ARRAY; +size--; +queue[front]=new_data; +front=(front+1)%SIZE_OF_ARRAY; +``` + +- **发布者推送消息到指定话题** + +通过发布者指针,将订阅了该话题的所有订阅者遍历,将新数据入队。 + +- **订阅者获取消息** + +从订阅者指针访问消息队列,取出最先进入队列的数据。注意判断队列是否为空,如果为空则返回0。 + +## 示例代码 + +```c +typedef struct +{ + float a; + uint8_t b; + uint32_t c; +}good; + +good g1; +good g2; +good pub_data={.a=1,.b=2,.c=3}; +// 一个发布者,两个订阅者 +Subscriber_t* s=SubRegister("test",sizeof(good)); +Subscriber_t* ss=SubRegister("test",sizeof(good)); +Publisher_t* p=PubRegister("test",sizeof(good)); +// 推送消息 +PubPushMessage(p,&pub_data); +pub_data.a=4; +pub_data.b=5; +pub_data.c=6; +// 推送新消息 +PubPushMessage(p,&pub_data); +volatile uint8_t d= 0; // 确定收到的消息是否有效,可以根据d的值进一步处理 +d=SubGetMessage(s,&g1); +d=SubGetMessage(s,&g1); +d=SubGetMessage(s,&g1); // 此时d等于0 +d=SubGetMessage(ss,&g2); +``` diff --git a/modules/module.md b/modules/module.md new file mode 100644 index 0000000..a761182 --- /dev/null +++ b/modules/module.md @@ -0,0 +1,3 @@ +# module + +这是module层的说明。 \ No newline at end of file diff --git a/modules/motor/DJImotor/dji_motor.c b/modules/motor/DJImotor/dji_motor.c new file mode 100644 index 0000000..2568faa --- /dev/null +++ b/modules/motor/DJImotor/dji_motor.c @@ -0,0 +1,315 @@ +#include "dji_motor.h" +#include "general_def.h" +#include "bsp_dwt.h" +#include "bsp_log.h" + +static uint8_t idx = 0; // register idx,是该文件的全局电机索引,在注册时使用 +/* DJI电机的实例,此处仅保存指针,内存的分配将通过电机实例初始化时通过malloc()进行 */ +static DJIMotorInstance *dji_motor_instance[DJI_MOTOR_CNT] = {NULL}; // 会在control任务中遍历该指针数组进行pid计算 + +/** + * @brief 由于DJI电机发送以四个一组的形式进行,故对其进行特殊处理,用6个(2can*3group)can_instance专门负责发送 + * 该变量将在 DJIMotorControl() 中使用,分组在 MotorSenderGrouping()中进行 + * + * @note 因为只用于发送,所以不需要在bsp_can中注册 + * + * C610(m2006)/C620(m3508):0x1ff,0x200; + * GM6020:0x1ff,0x2ff + * 反馈(rx_id): GM6020: 0x204+id ; C610/C620: 0x200+id + * can1: [0]:0x1FF,[1]:0x200,[2]:0x2FF + * can2: [3]:0x1FF,[4]:0x200,[5]:0x2FF + */ +static CANInstance sender_assignment[6] = { + [0] = {.can_handle = &hcan1, .txconf.StdId = 0x1ff, .txconf.IDE = CAN_ID_STD, .txconf.RTR = CAN_RTR_DATA, .txconf.DLC = 0x08, .tx_buff = {0}}, + [1] = {.can_handle = &hcan1, .txconf.StdId = 0x200, .txconf.IDE = CAN_ID_STD, .txconf.RTR = CAN_RTR_DATA, .txconf.DLC = 0x08, .tx_buff = {0}}, + [2] = {.can_handle = &hcan1, .txconf.StdId = 0x2ff, .txconf.IDE = CAN_ID_STD, .txconf.RTR = CAN_RTR_DATA, .txconf.DLC = 0x08, .tx_buff = {0}}, + [3] = {.can_handle = &hcan2, .txconf.StdId = 0x1ff, .txconf.IDE = CAN_ID_STD, .txconf.RTR = CAN_RTR_DATA, .txconf.DLC = 0x08, .tx_buff = {0}}, + [4] = {.can_handle = &hcan2, .txconf.StdId = 0x200, .txconf.IDE = CAN_ID_STD, .txconf.RTR = CAN_RTR_DATA, .txconf.DLC = 0x08, .tx_buff = {0}}, + [5] = {.can_handle = &hcan2, .txconf.StdId = 0x2ff, .txconf.IDE = CAN_ID_STD, .txconf.RTR = CAN_RTR_DATA, .txconf.DLC = 0x08, .tx_buff = {0}}, +}; + +/** + * @brief 6个用于确认是否有电机注册到sender_assignment中的标志位,防止发送空帧,此变量将在DJIMotorControl()使用 + * flag的初始化在 MotorSenderGrouping()中进行 + */ +static uint8_t sender_enable_flag[6] = {0}; + +/** + * @brief 根据电调/拨码开关上的ID,根据说明书的默认id分配方式计算发送ID和接收ID, + * 并对电机进行分组以便处理多电机控制命令 + */ +static void MotorSenderGrouping(DJIMotorInstance *motor, CAN_Init_Config_s *config) +{ + uint8_t motor_id = config->tx_id - 1; // 下标从零开始,先减一方便赋值 + uint8_t motor_send_num; + uint8_t motor_grouping; + + switch (motor->motor_type) + { + case M2006: + case M3508: + if (motor_id < 4) // 根据ID分组 + { + motor_send_num = motor_id; + motor_grouping = config->can_handle == &hcan1 ? 1 : 4; + } + else + { + motor_send_num = motor_id - 4; + motor_grouping = config->can_handle == &hcan1 ? 0 : 3; + } + + // 计算接收id并设置分组发送id + config->rx_id = 0x200 + motor_id + 1; // 把ID+1,进行分组设置 + sender_enable_flag[motor_grouping] = 1; // 设置发送标志位,防止发送空帧 + motor->message_num = motor_send_num; + motor->sender_group = motor_grouping; + + // 检查是否发生id冲突 + for (size_t i = 0; i < idx; ++i) + { + if (dji_motor_instance[i]->motor_can_instance->can_handle == config->can_handle && dji_motor_instance[i]->motor_can_instance->rx_id == config->rx_id) + { + LOGERROR("[dji_motor] ID crash. Check in debug mode, add dji_motor_instance to watch to get more information."); + uint16_t can_bus = config->can_handle == &hcan1 ? 1 : 2; + while (1) // 6020的id 1-4和2006/3508的id 5-8会发生冲突(若有注册,即1!5,2!6,3!7,4!8) (1!5!,LTC! (((不是) + LOGERROR("[dji_motor] id [%d], can_bus [%d]", config->rx_id, can_bus); + } + } + break; + + case GM6020: + if (motor_id < 4) + { + motor_send_num = motor_id; + motor_grouping = config->can_handle == &hcan1 ? 0 : 3; + } + else + { + motor_send_num = motor_id - 4; + motor_grouping = config->can_handle == &hcan1 ? 2 : 5; + } + + config->rx_id = 0x204 + motor_id + 1; // 把ID+1,进行分组设置 + sender_enable_flag[motor_grouping] = 1; // 只要有电机注册到这个分组,置为1;在发送函数中会通过此标志判断是否有电机注册 + motor->message_num = motor_send_num; + motor->sender_group = motor_grouping; + + for (size_t i = 0; i < idx; ++i) + { + if (dji_motor_instance[i]->motor_can_instance->can_handle == config->can_handle && dji_motor_instance[i]->motor_can_instance->rx_id == config->rx_id) + { + LOGERROR("[dji_motor] ID crash. Check in debug mode, add dji_motor_instance to watch to get more information."); + uint16_t can_bus = config->can_handle == &hcan1 ? 1 : 2; + while (1) // 6020的id 1-4和2006/3508的id 5-8会发生冲突(若有注册,即1!5,2!6,3!7,4!8) (1!5!,LTC! (((不是) + LOGERROR("[dji_motor] id [%d], can_bus [%d]", config->rx_id, can_bus); + } + } + break; + + default: // other motors should not be registered here + while (1) + LOGERROR("[dji_motor]You must not register other motors using the API of DJI motor."); // 其他电机不应该在这里注册 + } +} + +/** + * @todo 是否可以简化多圈角度的计算? + * @brief 根据返回的can_instance对反馈报文进行解析 + * + * @param _instance 收到数据的instance,通过遍历与所有电机进行对比以选择正确的实例 + */ +static void DecodeDJIMotor(CANInstance *_instance) +{ + // 这里对can instance的id进行了强制转换,从而获得电机的instance实例地址 + // _instance指针指向的id是对应电机instance的地址,通过强制转换为电机instance的指针,再通过->运算符访问电机的成员motor_measure,最后取地址获得指针 + uint8_t *rxbuff = _instance->rx_buff; + DJIMotorInstance *motor = (DJIMotorInstance *)_instance->id; + DJI_Motor_Measure_s *measure = &motor->measure; // measure要多次使用,保存指针减小访存开销 + + DaemonReload(motor->daemon); + motor->dt = DWT_GetDeltaT(&motor->feed_cnt); + + // 解析数据并对电流和速度进行滤波,电机的反馈报文具体格式见电机说明手册 + measure->last_ecd = measure->ecd; + measure->ecd = ((uint16_t)rxbuff[0]) << 8 | rxbuff[1]; + measure->angle_single_round = ECD_ANGLE_COEF_DJI * (float)measure->ecd; + measure->speed_aps = (1.0f - SPEED_SMOOTH_COEF) * measure->speed_aps + + RPM_2_ANGLE_PER_SEC * SPEED_SMOOTH_COEF * (float)((int16_t)(rxbuff[2] << 8 | rxbuff[3])); + measure->real_current = (1.0f - CURRENT_SMOOTH_COEF) * measure->real_current + + CURRENT_SMOOTH_COEF * (float)((int16_t)(rxbuff[4] << 8 | rxbuff[5])); + measure->temperature = rxbuff[6]; + + // 多圈角度计算,前提是假设两次采样间电机转过的角度小于180°,自己画个图就清楚计算过程了 + if (measure->ecd - measure->last_ecd > 4096) + measure->total_round--; + else if (measure->ecd - measure->last_ecd < -4096) + measure->total_round++; + measure->total_angle = measure->total_round * 360 + measure->angle_single_round; +} + +static void DJIMotorLostCallback(void *motor_ptr) +{ + DJIMotorInstance *motor = (DJIMotorInstance *)motor_ptr; + uint16_t can_bus = motor->motor_can_instance->can_handle == &hcan1 ? 1 : 2; + LOGWARNING("[dji_motor] Motor lost, can bus [%d] , id [%d]", can_bus, motor->motor_can_instance->tx_id); +} + +// 电机初始化,返回一个电机实例 +DJIMotorInstance *DJIMotorInit(Motor_Init_Config_s *config) +{ + DJIMotorInstance *instance = (DJIMotorInstance *)malloc(sizeof(DJIMotorInstance)); + memset(instance, 0, sizeof(DJIMotorInstance)); + + // motor basic setting 电机基本设置 + instance->motor_type = config->motor_type; // 6020 or 2006 or 3508 + instance->motor_settings = config->controller_setting_init_config; // 正反转,闭环类型等 + + // motor controller init 电机控制器初始化 + PIDInit(&instance->motor_controller.current_PID, &config->controller_param_init_config.current_PID); + PIDInit(&instance->motor_controller.speed_PID, &config->controller_param_init_config.speed_PID); + PIDInit(&instance->motor_controller.angle_PID, &config->controller_param_init_config.angle_PID); + instance->motor_controller.other_angle_feedback_ptr = config->controller_param_init_config.other_angle_feedback_ptr; + instance->motor_controller.other_speed_feedback_ptr = config->controller_param_init_config.other_speed_feedback_ptr; + instance->motor_controller.current_feedforward_ptr = config->controller_param_init_config.current_feedforward_ptr; + instance->motor_controller.speed_feedforward_ptr = config->controller_param_init_config.speed_feedforward_ptr; + // 后续增加电机前馈控制器(速度和电流) + + // 电机分组,因为至多4个电机可以共用一帧CAN控制报文 + MotorSenderGrouping(instance, &config->can_init_config); + + // 注册电机到CAN总线 + config->can_init_config.can_module_callback = DecodeDJIMotor; // set callback + config->can_init_config.id = instance; // set id,eq to address(it is identity) + instance->motor_can_instance = CANRegister(&config->can_init_config); + + // 注册守护线程 + Daemon_Init_Config_s daemon_config = { + .callback = DJIMotorLostCallback, + .owner_id = instance, + .reload_count = 2, // 20ms未收到数据则丢失 + }; + instance->daemon = DaemonRegister(&daemon_config); + + DJIMotorEnable(instance); + dji_motor_instance[idx++] = instance; + return instance; +} + +/* 电流只能通过电机自带传感器监测,后续考虑加入力矩传感器应变片等 */ +void DJIMotorChangeFeed(DJIMotorInstance *motor, Closeloop_Type_e loop, Feedback_Source_e type) +{ + if (loop == ANGLE_LOOP) + motor->motor_settings.angle_feedback_source = type; + else if (loop == SPEED_LOOP) + motor->motor_settings.speed_feedback_source = type; + else + LOGERROR("[dji_motor] loop type error, check memory access and func param"); // 检查是否传入了正确的LOOP类型,或发生了指针越界 +} + +void DJIMotorStop(DJIMotorInstance *motor) +{ + motor->stop_flag = MOTOR_STOP; +} + +void DJIMotorEnable(DJIMotorInstance *motor) +{ + motor->stop_flag = MOTOR_ENALBED; +} + +/* 修改电机的实际闭环对象 */ +void DJIMotorOuterLoop(DJIMotorInstance *motor, Closeloop_Type_e outer_loop) +{ + motor->motor_settings.outer_loop_type = outer_loop; +} + +// 设置参考值 +void DJIMotorSetRef(DJIMotorInstance *motor, float ref) +{ + motor->motor_controller.pid_ref = ref; +} + +// 为所有电机实例计算三环PID,发送控制报文 +void DJIMotorControl() +{ + // 直接保存一次指针引用从而减小访存的开销,同样可以提高可读性 + uint8_t group, num; // 电机组号和组内编号 + int16_t set; // 电机控制CAN发送设定值 + DJIMotorInstance *motor; + Motor_Control_Setting_s *motor_setting; // 电机控制参数 + Motor_Controller_s *motor_controller; // 电机控制器 + DJI_Motor_Measure_s *measure; // 电机测量值 + float pid_measure, pid_ref; // 电机PID测量值和设定值 + + // 遍历所有电机实例,进行串级PID的计算并设置发送报文的值 + for (size_t i = 0; i < idx; ++i) + { // 减小访存开销,先保存指针引用 + motor = dji_motor_instance[i]; + motor_setting = &motor->motor_settings; + motor_controller = &motor->motor_controller; + measure = &motor->measure; + pid_ref = motor_controller->pid_ref; // 保存设定值,防止motor_controller->pid_ref在计算过程中被修改 + if (motor_setting->motor_reverse_flag == MOTOR_DIRECTION_REVERSE) + pid_ref *= -1; // 设置反转 + + // pid_ref会顺次通过被启用的闭环充当数据的载体 + // 计算位置环,只有启用位置环且外层闭环为位置时会计算速度环输出 + if ((motor_setting->close_loop_type & ANGLE_LOOP) && motor_setting->outer_loop_type == ANGLE_LOOP) + { + if (motor_setting->angle_feedback_source == OTHER_FEED) + pid_measure = *motor_controller->other_angle_feedback_ptr; + else + pid_measure = measure->total_angle; // MOTOR_FEED,对total angle闭环,防止在边界处出现突跃 + // 更新pid_ref进入下一个环 + pid_ref = PIDCalculate(&motor_controller->angle_PID, pid_measure, pid_ref); + } + + // 计算速度环,(外层闭环为速度或位置)且(启用速度环)时会计算速度环 + if ((motor_setting->close_loop_type & SPEED_LOOP) && (motor_setting->outer_loop_type & (ANGLE_LOOP | SPEED_LOOP))) + { + if (motor_setting->feedforward_flag & SPEED_FEEDFORWARD) + pid_ref += *motor_controller->speed_feedforward_ptr; + + if (motor_setting->speed_feedback_source == OTHER_FEED) + pid_measure = *motor_controller->other_speed_feedback_ptr; + else // MOTOR_FEED + pid_measure = measure->speed_aps; + // 更新pid_ref进入下一个环 + pid_ref = PIDCalculate(&motor_controller->speed_PID, pid_measure, pid_ref); + } + + // 计算电流环,目前只要启用了电流环就计算,不管外层闭环是什么,并且电流只有电机自身传感器的反馈 + if (motor_setting->feedforward_flag & CURRENT_FEEDFORWARD) + pid_ref += *motor_controller->current_feedforward_ptr; + if (motor_setting->close_loop_type & CURRENT_LOOP) + { + pid_ref = PIDCalculate(&motor_controller->current_PID, measure->real_current, pid_ref); + } + + if (motor_setting->feedback_reverse_flag == FEEDBACK_DIRECTION_REVERSE) + pid_ref *= -1; + + // 获取最终输出 + set = (int16_t)pid_ref; + + + // 分组填入发送数据 + group = motor->sender_group; + num = motor->message_num; + sender_assignment[group].tx_buff[2 * num] = (uint8_t)(set >> 8); // 低八位 + sender_assignment[group].tx_buff[2 * num + 1] = (uint8_t)(set & 0x00ff); // 高八位 + + // 若该电机处于停止状态,直接将buff置零 + if (motor->stop_flag == MOTOR_STOP) + memset(sender_assignment[group].tx_buff + 2 * num, 0, 2u); + } + + // 遍历flag,检查是否要发送这一帧报文 + for (size_t i = 0; i < 6; ++i) + { + if (sender_enable_flag[i]) + { + CANTransmit(&sender_assignment[i], 1); + } + } +} diff --git a/modules/motor/DJImotor/dji_motor.h b/modules/motor/DJImotor/dji_motor.h new file mode 100644 index 0000000..bd07c1a --- /dev/null +++ b/modules/motor/DJImotor/dji_motor.h @@ -0,0 +1,130 @@ +/** + * @file dji_motor.h + * @author neozng + * @brief DJI智能电机头文件 + * @version 0.2 + * @date 2022-11-01 + * + * @todo 1. 给不同的电机设置不同的低通滤波器惯性系数而不是统一使用宏 + 2. 为M2006和M3508增加开环的零位校准函数,并在初始化时调用(根据用户配置决定是否调用) + + * @copyright Copyright (c) 2022 HNU YueLu EC all rights reserved + * + */ + +#ifndef DJI_MOTOR_H +#define DJI_MOTOR_H + +#include "bsp_can.h" +#include "controller.h" +#include "motor_def.h" +#include "stdint.h" +#include "daemon.h" + +#define DJI_MOTOR_CNT 12 + +/* 滤波系数设置为1的时候即关闭滤波 */ +#define SPEED_SMOOTH_COEF 0.85f // 最好大于0.85 +#define CURRENT_SMOOTH_COEF 0.9f // 必须大于0.9 +#define ECD_ANGLE_COEF_DJI 0.043945f // (360/8192),将编码器值转化为角度制 + +/* DJI电机CAN反馈信息*/ +typedef struct +{ + uint16_t last_ecd; // 上一次读取的编码器值 + uint16_t ecd; // 0-8191,刻度总共有8192格 + float angle_single_round; // 单圈角度 + float speed_aps; // 角速度,单位为:度/秒 + int16_t real_current; // 实际电流 + uint8_t temperature; // 温度 Celsius + + float total_angle; // 总角度,注意方向 + int32_t total_round; // 总圈数,注意方向 +} DJI_Motor_Measure_s; + +/** + * @brief DJI intelligent motor typedef + * + */ +typedef struct +{ + DJI_Motor_Measure_s measure; // 电机测量值 + Motor_Control_Setting_s motor_settings; // 电机设置 + Motor_Controller_s motor_controller; // 电机控制器 + + CANInstance *motor_can_instance; // 电机CAN实例 + // 分组发送设置 + uint8_t sender_group; + uint8_t message_num; + + Motor_Type_e motor_type; // 电机类型 + Motor_Working_Type_e stop_flag; // 启停标志 + + DaemonInstance* daemon; + uint32_t feed_cnt; + float dt; +} DJIMotorInstance; + +/** + * @brief 调用此函数注册一个DJI智能电机,需要传递较多的初始化参数,请在application初始化的时候调用此函数 + * 推荐传参时像标准库一样构造initStructure然后传入此函数. + * recommend: type xxxinitStructure = {.member1=xx, + * .member2=xx, + * ....}; + * 请注意不要在一条总线上挂载过多的电机(超过6个),若一定要这么做,请降低每个电机的反馈频率(设为500Hz), + * 并减小DJIMotorControl()任务的运行频率. + * + * @attention M3508和M2006的反馈报文都是0x200+id,而GM6020的反馈是0x204+id,请注意前两者和后者的id不要冲突. + * 如果产生冲突,在初始化电机的时候会进入IDcrash_Handler(),可以通过debug来判断是否出现冲突. + * + * @param config 电机初始化结构体,包含了电机控制设置,电机PID参数设置,电机类型以及电机挂载的CAN设置 + * + * @return DJIMotorInstance* + */ +DJIMotorInstance *DJIMotorInit(Motor_Init_Config_s *config); + +/** + * @brief 被application层的应用调用,给电机设定参考值. + * 对于应用,可以将电机视为传递函数为1的设备,不需要关心底层的闭环 + * + * @param motor 要设置的电机 + * @param ref 设定参考值 + */ +void DJIMotorSetRef(DJIMotorInstance *motor, float ref); + +/** + * @brief 切换反馈的目标来源,如将角速度和角度的来源换为IMU(小陀螺模式常用) + * + * @param motor 要切换反馈数据来源的电机 + * @param loop 要切换反馈数据来源的控制闭环 + * @param type 目标反馈模式 + */ +void DJIMotorChangeFeed(DJIMotorInstance *motor, Closeloop_Type_e loop, Feedback_Source_e type); + +/** + * @brief 该函数被motor_task调用运行在rtos上,motor_stask内通过osDelay()确定控制频率 + */ +void DJIMotorControl(); + +/** + * @brief 停止电机,注意不是将设定值设为零,而是直接给电机发送的电流值置零 + * + */ +void DJIMotorStop(DJIMotorInstance *motor); + +/** + * @brief 启动电机,此时电机会响应设定值 + * 初始化时不需要此函数,因为stop_flag的默认值为0 + * + */ +void DJIMotorEnable(DJIMotorInstance *motor); + +/** + * @brief 修改电机闭环目标(外层闭环) + * + * @param motor 要修改的电机实例指针 + * @param outer_loop 外层闭环类型 + */ +void DJIMotorOuterLoop(DJIMotorInstance *motor, Closeloop_Type_e outer_loop); + +#endif // !DJI_MOTOR_H diff --git a/modules/motor/DJImotor/dji_motor.md b/modules/motor/DJImotor/dji_motor.md new file mode 100644 index 0000000..6e1dfda --- /dev/null +++ b/modules/motor/DJImotor/dji_motor.md @@ -0,0 +1,470 @@ +# dji_motor + +
neozng1@hnu.edu.cn
+ +> TODO: +> +> 1. 给不同的电机设置不同的低通滤波器惯性系数而不是统一使用宏 +> 2. 为M2006和M3508增加开环的零位校准函数 + +--- + +> 建议将电机的反馈频率通过RoboMaster Assistant统一设置为500Hz。当前默认的`MotorTask()`执行频率为500Hz,若不修改电机反馈频率可能导致单条总线挂载的电机数量有限,且容易出现帧错误和仲裁失败的情况。 + +## 总览和封装说明 + +> 如果你不需要理解该模块的工作原理,你只需要查看这一小节。 + +dji_motor模块对DJI智能电机,包括M2006,M3508以及GM6020进行了详尽的封装。你不再需要关心PID的计算以及CAN报文的发送和接收解析,你只需要专注于根据应用层的需求,设定合理的期望值,并通过`DJIMotorSetRef()`设置对应电机的输入参考即可。 + +**==设定值的单位==** + +1. ==位置环为**角度制**(0-360,total_angle可以为任意值)== + +2. ==速度环为角速度,单位为**度/每秒**(deg/sec)== + +3. ==电流环为A== + +4. ==GM6020的输入设定为**力矩**,待测量(-30000~30000)== + + ==M3508的输入设定为-20A~20A (-16384~16384)== + + ==M2006的输入设定为-10A~10A (-10000~10000)== + +如果你希望更改电机的反馈来源,比如进入小陀螺模式/视觉模式(这时候你想要云台保持静止,使用IMU的yaw角度值作为反馈来源),只需要调用`DJIMotorChangeFeed()`,电机便可立刻切换反馈数据来源至IMU。 + +要获得一个电机,请通过`DJIMotorInit()`并传入一些参数,他就会返回一个电机的指针。你也不再需要查看这些电机和电调的说明书,**只需要设置其电机id**(6020为拨码开关值,2006和3508为电调的闪动次数),该模块会自动为你计算CAN发送和接收ID并搞定所有硬件层的琐事。 + +初始化电机时,你需要传入的参数包括: + +- **电机挂载的CAN总线设置**,CAN1 or CAN2,以及电机的id,使用`can_instance_config_s`封装,只需要设置这两个参数: + + ```c + CAN_HandleTypeDef *can_handle; + uint32_t tx_id; // tx_id设置为电机id,不需要查说明书计算,直接为电调的闪动次数或拨码开关值,为1-8 + ``` + +- **电机类型**,使用`Motor_Type_e`: + + ```c + GM6020 = 0 + M3508 = 1 + M2006 = 2 + ``` + +- **电机控制设置** + + - 闭环类型 + + ```c + OPEN_LOOP + CURRENT_LOOP + SPEED_LOOP + ANGLE_LOOP + CURRENT_LOOP | SPEED_LOOP // 同时对电流和速度闭环 + SPEED_LOOP | ANGLE_LOOP // 同时对速度和位置闭环 + CURRENT_LOOP | SPEED_LOOP |ANGLE_LOOP // 三环全开 + ``` + + - 是否反转 + + ```c + MOTOR_DIRECTION_NORMAL + MOTOR_DIRECTION_REVERSE + ``` + + - 是否其他反馈来源,以及他们对应的数据指针(如果有的话) + + ```c + MOTOR_FEED = 0 + OTHER_FEED = 1 + --- + + // 电流只能从电机传感器获得所以无法设置其他来源 + ``` + + - 每个环的PID参数以及是否使用改进功能,以及其他反馈来源指针(如果在上一步启用了其他数据来源) + + ```c + typedef struct // config parameter + { + float Kp; + float Ki; + float Kd; + + float MaxOut; // 输出限幅 + // 以下是优化参数 + float IntegralLimit; // 积分限幅 + float DeadBand; // 死区 + float CoefA; // For Changing Integral + float CoefB; // ITerm = Err*((A-abs(err)+B)/A) when B<|err|motor_measure->speed_rpm; +... +``` + +***现在,忘记PID的计算和发送、接收以及协议解析,专注于模块之间的逻辑交互吧。*** + +--- + +## 代码结构 + +.h文件内包括了外部接口和类型定义,以及模块对应的宏。c文件内为私有函数和外部接口的定义。 + +motor_def.h内包含了一些电机通用的定义。 + +## 类型定义 + +```c +#define DJI_MOTOR_CNT 12 +#define SPEED_SMOOTH_COEF 0.9f // better to be greater than 0.85 +#define CURRENT_SMOOTH_COEF 0.98f // this coef must be greater than 0.95 + +typedef struct /* DJI电机CAN反馈信息*/ +{ + uint16_t ecd; + uint16_t last_ecd; + int16_t speed_rpm; + int16_t given_current; + uint8_t temperate; + int16_t total_round; + int32_t total_angle; +} dji_motor_measure; + +typedef struct +{ + /* motor measurement recv from CAN feedback */ + dji_motor_measure motor_measure; + /* basic config of a motor*/ + Motor_Control_Setting_s motor_settings; + /* controller used in the motor (3 loops)*/ + Motor_Controller_s motor_controller; + /* the CAN instance own by motor instance*/ + can_instance motor_can_instance; + /* sender assigment*/ + uint8_t sender_group; + uint8_t message_num; + + uint8_t stop_flag; + + Motor_Type_e motor_type; +} dji_motor_instance; +``` + +- `DJI_MOTOR_CNT`是允许的最大DJI电机数量,根据经验,暂定为每个CAN6个,防止出现拥塞。 + +- `SPEED_SMOOTH_COEF`和`CURRENT_SMOOTH_COEF`是电机反馈的电流和速度数据低通滤波器惯性系数,数值越小平滑效果越大,但滞后也越大。设定时不应当低于推荐值。 +- `dji_motor_measure`是DJI电机的反馈信息,包括当前编码器值、上次测量编码器值、速度、电流、温度、总圈数和单圈角度。 + +- `Motor_Control_Setting_s`的定义在`motor_def.h`之中,它和`Motor_Controller_s`都是所有电机通用的组件(如M3508,LK9025,HT04,MT6023等),其包含内容如下: + + ```c + typedef struct /* 电机控制配置 */ + { + Closeloop_Type_e outer_loop_type; + Closeloop_Type_e close_loop_type; + Motor_Reverse_Flag_e motor_reverse_flag; + Feedback_Source_e angle_feedback_source; + Feedback_Source_e speed_feedback_source; + } Motor_Control_Setting_s; + ``` + + `Motor_Control_Setting_s`里包含了电机的闭环类型,反转标志以及额外的反馈来源标志。 + + - 闭环类型指示该电机使用的控制器配置,其枚举定义如下: + + ```c + typedef enum + { + CURRENT_LOOP = 0b0001, + SPEED_LOOP = 0b0010, + ANGLE_LOOP = 0b0100, + _ = 0b0011, + __ = 0b0110, + ___ = 0b0111 + } Closeloop_Type_e; + ``` + + 以M3508为例,假设需要进行**速度闭环**和**电流闭环**,那么在初始化时就将这个变量的值设为`CURRENT_LOOP | SPEED_LOOP`。在`DJIMotorControl()`中,函数将会根据此标志位判断设定的参考值需要经过那些控制器的计算。 + 另外,你还需要设置当前电机的最外层闭环,即电机的闭环目标为什么类型的值。初始化时需要设置`outer_loop_type`。以M2006作为拨盘电机时为例,你希望它在单发/双发等固定发射数量的模式下对位置进行闭环(拨盘转过一定角度对应拨出一颗弹丸),但你也有可能希望在连发的时候让拨盘连续的转动,以一定的频率发射弹丸。我们提供了`DJIMotorOuterLoop()`用于修改电机的外层闭环,改变电机的闭环对象。 + + > 注意,务必分清串级控制(多环)和外层闭环的区别。前者是为了提高内环的性能,使得其能更好地跟随外环参考值;而后者描述的是系统真实的控制目标(闭环目标)。如3508,没有电流环仍然可以对速度完成闭环,对于高层的应用来说,它们本质上不关心电机内部是否还有电流环,它们只把外层闭环为速度的电机当作一个**速度伺服执行器**,**外层闭环**描述的就是真正的闭环目标。 + + - 为了避开恼人的正负号,提高代码的可维护性,在初始化电机时设定`motor_reverse_flag`使得所有电机都按照你想要的方向旋转,其定义如下: + + ```c + typedef enum + { + MOTOR_DIRECTION_NORMAL = 0, + MOTOR_DIRECTION_REVERSE = 1 + } Motor_Reverse_Flag_e; + ``` + + - `speed_feedback_source`以及`angle_feedback_source`是指示电机反馈来源的标志位。一般情况下电机使用自身的编码器作为控制反馈量。但在某些时候,如小陀螺模式,云台电机会使用IMU的姿态数据作为反馈数据来源。其定义如下: + + ```c + typedef enum + { + MOTOR_FEED = 0, + OTHER_FEED = 1 + } Feedback_Source_e; + ``` + + **注意,如果启用其他数据来源,你需要在电机的控制器配置`Motor_Controller_s`下的`other_xxx_feedback_ptr`中指定其他数据来源。** + + 你可以在`DJIMotorChangeFeed()`中修改电机的数据来源。 + +- `Motor_Controller_s`的定义也在`motor_def.h`之中: + + ```c + /* 电机控制器,包括其他来源的反馈数据指针,3环控制器和电机的参考输入*/ + typedef struct + { + float *other_angle_feedback_ptr; + float *other_speed_feedback_ptr; + PID_t current_PID; + PID_t speed_PID; + PID_t angle_PID; + + float pid_ref; // 将会作为每个环的输入和输出顺次通过串级闭环 + } Motor_Controller_s; + ``` + + 两个`float*`指针应当指向其他反馈来源数据(如果有的话,需要在`motor_settings`中设定)。 + + 三个PID分别为三个控制闭环所用,在`DJIMotorControl()`中,该函数会根据`close_loop_type`的设定计算对应的闭环。 + + **`pid_ref`是控制的设定值,app层的应用想要更改电机的输出,就要调用`DJIMotorSetRef()`更改此值。** + +- `dji_motor_instance`是一个DJI电机实例。一个电机实例内包含电机的反馈信息,电机的控制设置,电机控制器,电机对应的CAN实例以及电机的类型;由于DJI电机支持**一帧报文控制至多4个电机**,该结构体还包含了用于给电机分组发送进行特殊处理的`sender_group`和`message_num`(具体实现细节参考`MotorSenderGrouping()`函数)。 + +## 外部接口 + +```c +dji_motor_instance *DJIMotorInit(can_instance_config config, + Motor_Control_Setting_s motor_setting, + Motor_Controller_Init_s controller_init, + Motor_Type_e type); + +void DJIMotorSetRef(dji_motor_instance *motor, float ref); + +void DJIMotorChangeFeed(dji_motor_instance *motor, + Closeloop_Type_e loop, + Feedback_Source_e type); + +void DJIMotorControl(); + +void DJIMotorStop(dji_motor_instance *motor); + +void DJIMotorEnable(dji_motor_instance *motor); + +void DJIMotorOuterLoop(dji_motor_instance *motor); +``` + +- `DJIMotorInit()`是用于初始化电机对象的接口,传入包括电机can配置、电机控制配置、电机控制器配置以及电机类型在内的初始化参数。**它将会返回一个电机实例指针**,你应当在应用层保存这个指针,这样才能操控这个电机。 + +- `DJIMotorSetRef()`是设定电机输出的接口,**在调用这个函数的时候,你可以认为你的设定值会直接转变为电机的输出**。`DJIMotorControl()`会帮你完成闭环计算,不用担心PID。 + +- `DJIMotorChangeFeed()`一般在更改云台或底盘的运动模式的时候被调用,传入要修改反馈来源的电机实例指针、要修改的闭环以及反馈来源类型。如希望切换到IMU的yaw值作为云台设定值,传入yaw轴电机实例和`ANGLE_LOOP`(位置环)、`OTHER_FEED`(启用其他数据来源)即可。当然,你需要在初始化的时候设定`motor_controller`中的 `other_angle_feedback_ptr`,使其指向yaw值的变量。 + +- `DJIMotorControl()`是根据电机的配置计算控制值的函数。该函数在`motor_task.c`中被调用,应当在freeRTOS中以一定频率运行。此函数为PID的计算进行了彻底的封装,要修改电机的参考输入,请在app层的应用中调用`DJIMotorSetRef()`。 + + 该函数的具体实现请参照代码,注释已经较为清晰。流程大致为: + + 1. 根据电机的初始化控制配置,计算各个控制闭环 + 2. 根据反转标志位,确定是否将输出反转 + 3. 根据每个电机的发送分组,将最终输出值填入对应的分组buff + 4. 检查每一个分组,若该分组有电机,发送报文 + +- `DJIMotorStop()`和`DJIMotorEnable()`用于控制电机的启动和停止。当电机被设为stop的时候,不会响应任何的参考输入。 + +- `DJIMotorOuterLoop()`用于修改电机的外部闭环类型,即电机的真实闭环目标。 + +## 私有函数和变量 + +在.c文件内设为static的函数和变量 + +```c +static uint8_t idx = 0; // register idx,是该文件的全局电机索引,在注册时使用 +static dji_motor_instance *dji_motor_info[DJI_MOTOR_CNT] = {NULL}; +``` + +这是管理所有电机实例的入口。idx用于电机初始化。 + +```c +#define PI2 (3.141592f * 2) +#define ECD_ANGLE_COEF_DJI 3.835e-4 // ecd/8192*pi +``` + +这两个宏用于在电机反馈信息中的多圈角度计算,将编码器的0~8192转化为角度表示。 + +```c +/* @brief 由于DJI电机发送以四个一组的形式进行,故对其进行特殊处理,用6个(2can*3group)can_instance专门负责发送 + * 该变量将在 DJIMotorControl() 中使用,分组在 MotorSenderGrouping()中进行 + * + * can1: [0]:0x1FF,[1]:0x200,[2]:0x2FF + * can2: [0]:0x1FF,[1]:0x200,[2]:0x2FF */ +static can_instance sender_assignment[6] = +{ + [0] = {.can_handle = &hcan1, .txconf.StdId = 0x1ff, .txconf.IDE = CAN_ID_STD, .txconf.RTR = CAN_RTR_DATA, .txconf.DLC = 0x08, .tx_buff = {0}}, + ... + ... +}; + +static uint8_t sender_enable_flag[6] = {0}; +``` + +- 这些是电机分组发送所需的变量。注册电机时,会根据挂载的总线以及发送id,将电机分组。在CAN发送电机控制信息的时候,根据`sender_assignment[]`保存的分组进行发送,而不会使用电机实例自带的`can_instance`。 +- DJI电机共有3种分组,分别为0x1FF,0x200,0x2FF。注册电机的时候,`MotorSenderGrouping()`函数会根据发送id计算出CAN的`tx_id`(即上述三个中的一个)和`rx_id`。然后为电机实例分配用于指示其在`sender_assignment[]`中的编号的 `sender_group`和其在该发送组中的位置`message_num`(一帧报文可以发送四条控制指令,`message_num`会指定电机是这四个中的哪一个)。具体的分配请查看`MotorSenderGrouping()`的定义。 +- 当某一个分组有电机注册时,该分组的索引将会在`sender_enable_flag`[]中被置1,这样,就可以避免发送没有电机注册的报文,防止总线拥塞。具体的,在`DecodeDJIMotor()`中,该函数会查看`sender_enable_flag[]`的每一个位置,确定这一组是否有电机被注册,若有则发送`sender_assignment[]`中对应位置的`tx_buff`。 + +```c +static void IDcrash_Handler(uint8_t conflict_motor_idx, uint8_t temp_motor_idx) + +static void MotorSenderGrouping(can_instance_config *config) + +static void DecodeDJIMotor(can_instance *_instance) +``` + +- `IDcrash_Handler()`在电机id发生冲突的时候会被`MotorSenderGrouping()`调用,陷入死循环之中,并把冲突的id保存在函数里。这样就可以通过debug确定是否发生冲突以及冲突的编号。 + +- `MotorSenderGrouping()`被`DJIMotorInit()`调用,他将会根据电机id计算出CAN的发送和接收ID,并根据发送ID对电机进行分组。 + +- `DecodeDJIMotor()`是解析电机反馈报文的函数,在`DJIMotorInit()`中会将其注册到该电机实例对应的`can_instance`中(即`can_instance`的`can_module_callback()`)。这样,当该电机的反馈报文到达时,`bsp_can.c`中的回调函数会调用解包函数进行反馈数据解析。 + + 该函数还会对电流和速度反馈值进行滤波,消除高频噪声;同时计算多圈角度和单圈绝对角度。 + + **电机反馈的电流值为说明书中的映射值,需转换为实际值。** + + **反馈的速度单位是rpm(转每分钟),转换为角度每秒。** + + **反馈的位置是编码器值(0~8191),转换为角度。** + +## 使用范例 + +```c +//初始化设置 +Motor_Init_Config_s config = { + .motor_type = GM6020, + .can_init_config = { + .can_handle = &hcan1, + .tx_id = 6 + }, + .controller_setting_init_config = { + .angle_feedback_source = MOTOR_FEED, + .outer_loop_type = SPEED_LOOP, + .close_loop_type = SPEED_LOOP | ANGLE_LOOP, + .speed_feedback_source = MOTOR_FEED, + .motor_reverse_flag = MOTOR_DIRECTION_NORMAL + }, + .controller_param_init_config = { + .angle_PID = { + .Improve = 0, + .Kp = 1, + .Ki = 0, + .Kd = 0, + .DeadBand = 0, + .MaxOut = 4000}, + .speed_PID = { + .Improve = 0, + .Kp = 1, + .Ki = 0, + .Kd = 0, + .DeadBand = 0, + .MaxOut = 4000 + } + } +}; +//注册电机并保存实例指针 +dji_motor_instance *djimotor = DJIMotorInit(&config); +``` + +然后在任务中修改电机设定值即可实现控制: + +``` +DJIMotorSetRef(djimotor, 10); +``` + +前提是已经将`DJIMotorControl()`放入实时系统任务当中或以一定d。你也可以单独执行`DJIMotorControl()`。 diff --git a/modules/motor/DMmotor/DMmotor.c b/modules/motor/DMmotor/DMmotor.c new file mode 100644 index 0000000..cd7cb32 --- /dev/null +++ b/modules/motor/DMmotor/DMmotor.c @@ -0,0 +1,175 @@ +#include "DMmotor.h" +#include "memory.h" +#include "general_def.h" +#include "user_lib.h" +#include "cmsis_os.h" +#include "string.h" +#include "daemon.h" +#include "stdlib.h" +#include "bsp_log.h" + +static uint8_t idx; +static DMMotorInstance *dm_motor_instance[DM_MOTOR_CNT]; +static osThreadId dm_task_handle[DM_MOTOR_CNT]; +/* 两个用于将uint值和float值进行映射的函数,在设定发送值和解析反馈值时使用 */ +static uint16_t float_to_uint(float x, float x_min, float x_max, uint8_t bits) +{ + float span = x_max - x_min; + float offset = x_min; + return (uint16_t)((x - offset) * ((float)((1 << bits) - 1)) / span); +} +static float uint_to_float(int x_int, float x_min, float x_max, int bits) +{ + float span = x_max - x_min; + float offset = x_min; + return ((float)x_int) * span / ((float)((1 << bits) - 1)) + offset; +} + +static void DMMotorSetMode(DMMotor_Mode_e cmd, DMMotorInstance *motor) +{ + memset(motor->motor_can_instace->tx_buff, 0xff, 7); // 发送电机指令的时候前面7bytes都是0xff + motor->motor_can_instace->tx_buff[7] = (uint8_t)cmd; // 最后一位是命令id + CANTransmit(motor->motor_can_instace, 1); +} + +static void DMMotorDecode(CANInstance *motor_can) +{ + uint16_t tmp; // 用于暂存解析值,稍后转换成float数据,避免多次创建临时变量 + uint8_t *rxbuff = motor_can->rx_buff; + DMMotorInstance *motor = (DMMotorInstance *)motor_can->id; + DM_Motor_Measure_s *measure = &(motor->measure); // 将can实例中保存的id转换成电机实例的指针 + + DaemonReload(motor->motor_daemon); + + measure->last_position = measure->position; + tmp = (uint16_t)((rxbuff[1] << 8) | rxbuff[2]); + measure->position = uint_to_float(tmp, DM_P_MIN, DM_P_MAX, 16); + + tmp = (uint16_t)((rxbuff[3] << 4) | rxbuff[4] >> 4); + measure->velocity = uint_to_float(tmp, DM_V_MIN, DM_V_MAX, 12); + + tmp = (uint16_t)(((rxbuff[4] & 0x0f) << 8) | rxbuff[5]); + measure->torque = uint_to_float(tmp, DM_T_MIN, DM_T_MAX, 12); + + measure->T_Mos = (float)rxbuff[6]; + measure->T_Rotor = (float)rxbuff[7]; +} + +static void DMMotorLostCallback(void *motor_ptr) +{ +} +void DMMotorCaliEncoder(DMMotorInstance *motor) +{ + DMMotorSetMode(DM_CMD_ZERO_POSITION, motor); + DWT_Delay(0.1); +} +DMMotorInstance *DMMotorInit(Motor_Init_Config_s *config) +{ + DMMotorInstance *motor = (DMMotorInstance *)malloc(sizeof(DMMotorInstance)); + memset(motor, 0, sizeof(DMMotorInstance)); + + motor->motor_settings = config->controller_setting_init_config; + PIDInit(&motor->current_PID, &config->controller_param_init_config.current_PID); + PIDInit(&motor->speed_PID, &config->controller_param_init_config.speed_PID); + PIDInit(&motor->angle_PID, &config->controller_param_init_config.angle_PID); + motor->other_angle_feedback_ptr = config->controller_param_init_config.other_angle_feedback_ptr; + motor->other_speed_feedback_ptr = config->controller_param_init_config.other_speed_feedback_ptr; + + config->can_init_config.can_module_callback = DMMotorDecode; + config->can_init_config.id = motor; + motor->motor_can_instace = CANRegister(&config->can_init_config); + + Daemon_Init_Config_s conf = { + .callback = DMMotorLostCallback, + .owner_id = motor, + .reload_count = 10, + }; + motor->motor_daemon = DaemonRegister(&conf); + + DMMotorEnable(motor); + DMMotorSetMode(DM_CMD_MOTOR_MODE, motor); + DWT_Delay(0.1); + DMMotorCaliEncoder(motor); + DWT_Delay(0.1); + dm_motor_instance[idx++] = motor; + return motor; +} + +void DMMotorSetRef(DMMotorInstance *motor, float ref) +{ + motor->pid_ref = ref; +} + +void DMMotorEnable(DMMotorInstance *motor) +{ + motor->stop_flag = MOTOR_ENALBED; +} + +void DMMotorStop(DMMotorInstance *motor)//不使用使能模式是因为需要收到反馈 +{ + motor->stop_flag = MOTOR_STOP; +} + +void DMMotorOuterLoop(DMMotorInstance *motor, Closeloop_Type_e type) +{ + motor->motor_settings.outer_loop_type = type; +} + + +//@Todo: 目前只实现了力控,更多位控PID等请自行添加 +void DMMotorTask(void const *argument) +{ + float pid_ref, set; + DMMotorInstance *motor = (DMMotorInstance *)argument; + //DM_Motor_Measure_s *measure = &motor->measure; + Motor_Control_Setting_s *setting = &motor->motor_settings; + //CANInstance *motor_can = motor->motor_can_instace; + //uint16_t tmp; + DMMotor_Send_s motor_send_mailbox; + while (1) + { + pid_ref = motor->pid_ref; + + set = pid_ref; + if (setting->motor_reverse_flag == MOTOR_DIRECTION_REVERSE) + set *= -1; + + LIMIT_MIN_MAX(set, DM_T_MIN, DM_T_MAX); + motor_send_mailbox.position_des = float_to_uint(0, DM_P_MIN, DM_P_MAX, 16); + motor_send_mailbox.velocity_des = float_to_uint(0, DM_V_MIN, DM_V_MAX, 12); + motor_send_mailbox.torque_des = float_to_uint(pid_ref, DM_T_MIN, DM_T_MAX, 12); + motor_send_mailbox.Kp = 0; + motor_send_mailbox.Kd = 0; + + if(motor->stop_flag == MOTOR_STOP) + motor_send_mailbox.torque_des = float_to_uint(0, DM_T_MIN, DM_T_MAX, 12); + + motor->motor_can_instace->tx_buff[0] = (uint8_t)(motor_send_mailbox.position_des >> 8); + motor->motor_can_instace->tx_buff[1] = (uint8_t)(motor_send_mailbox.position_des); + motor->motor_can_instace->tx_buff[2] = (uint8_t)(motor_send_mailbox.velocity_des >> 4); + motor->motor_can_instace->tx_buff[3] = (uint8_t)(((motor_send_mailbox.velocity_des & 0xF) << 4) | (motor_send_mailbox.Kp >> 8)); + motor->motor_can_instace->tx_buff[4] = (uint8_t)(motor_send_mailbox.Kp); + motor->motor_can_instace->tx_buff[5] = (uint8_t)(motor_send_mailbox.Kd >> 4); + motor->motor_can_instace->tx_buff[6] = (uint8_t)(((motor_send_mailbox.Kd & 0xF) << 4) | (motor_send_mailbox.torque_des >> 8)); + motor->motor_can_instace->tx_buff[7] = (uint8_t)(motor_send_mailbox.torque_des); + + CANTransmit(motor->motor_can_instace, 1); + + osDelay(2); + } +} +void DMMotorControlInit() +{ + char dm_task_name[5] = "dm"; + // 遍历所有电机实例,创建任务 + if (!idx) + return; + for (size_t i = 0; i < idx; i++) + { + char dm_id_buff[2] = {0}; + __itoa(i, dm_id_buff, 10); + strcat(dm_task_name, dm_id_buff); + osThreadDef(dm_task_name, DMMotorTask, osPriorityNormal, 0, 128); + dm_task_handle[i] = osThreadCreate(osThread(dm_task_name), dm_motor_instance[i]); + } +} \ No newline at end of file diff --git a/modules/motor/DMmotor/DMmotor.h b/modules/motor/DMmotor/DMmotor.h new file mode 100644 index 0000000..8f03e28 --- /dev/null +++ b/modules/motor/DMmotor/DMmotor.h @@ -0,0 +1,76 @@ +#ifndef DMMOTOR_H +#define DMMOTOR_H +#include+#include "bsp_can.h" +#include "controller.h" +#include "motor_def.h" +#include "daemon.h" + +#define DM_MOTOR_CNT 4 + +#define DM_P_MIN (-12.5f) +#define DM_P_MAX 12.5f +#define DM_V_MIN (-45.0f) +#define DM_V_MAX 45.0f +#define DM_T_MIN (-18.0f) +#define DM_T_MAX 18.0f + +typedef struct +{ + uint8_t id; + uint8_t state; + float velocity; + float last_position; + float position; + float torque; + float T_Mos; + float T_Rotor; + int32_t total_round; +}DM_Motor_Measure_s; + +typedef struct +{ + uint16_t position_des; + uint16_t velocity_des; + uint16_t torque_des; + uint16_t Kp; + uint16_t Kd; +}DMMotor_Send_s; +typedef struct +{ + DM_Motor_Measure_s measure; + Motor_Control_Setting_s motor_settings; + PIDInstance current_PID; + PIDInstance speed_PID; + PIDInstance angle_PID; + float *other_angle_feedback_ptr; + float *other_speed_feedback_ptr; + float *speed_feedforward_ptr; + float *current_feedforward_ptr; + float pid_ref; + Motor_Working_Type_e stop_flag; + CANInstance *motor_can_instace; + DaemonInstance* motor_daemon; + uint32_t lost_cnt; +}DMMotorInstance; + +typedef enum +{ + DM_CMD_MOTOR_MODE = 0xfc, // 使能,会响应指令 + DM_CMD_RESET_MODE = 0xfd, // 停止 + DM_CMD_ZERO_POSITION = 0xfe, // 将当前的位置设置为编码器零位 + DM_CMD_CLEAR_ERROR = 0xfb // 清除电机过热错误 +}DMMotor_Mode_e; + +DMMotorInstance *DMMotorInit(Motor_Init_Config_s *config); + +void DMMotorSetRef(DMMotorInstance *motor, float ref); + +void DMMotorOuterLoop(DMMotorInstance *motor,Closeloop_Type_e closeloop_type); + +void DMMotorEnable(DMMotorInstance *motor); + +void DMMotorStop(DMMotorInstance *motor); +void DMMotorCaliEncoder(DMMotorInstance *motor); +void DMMotorControlInit(); +#endif // !DMMOTOR \ No newline at end of file diff --git a/modules/motor/HTmotor/HT04.c b/modules/motor/HTmotor/HT04.c new file mode 100644 index 0000000..fdfad15 --- /dev/null +++ b/modules/motor/HTmotor/HT04.c @@ -0,0 +1,235 @@ +#include "HT04.h" +#include "memory.h" +#include "general_def.h" +#include "user_lib.h" +#include "cmsis_os.h" +#include "string.h" +#include "daemon.h" +#include "stdlib.h" +#include "bsp_log.h" + +static uint8_t idx; +static HTMotorInstance *ht_motor_instance[HT_MOTOR_CNT]; +static osThreadId ht_task_handle[HT_MOTOR_CNT]; +static uint8_t zero_buff[6] = {0}; + +/** + * @brief 设置电机模式,报文内容[0xff,0xff,0xff,0xff,0xff,0xff,0xff,cmd] + * + * @param cmd + * @param motor + */ +static void HTMotorSetMode(HTMotor_Mode_t cmd, HTMotorInstance *motor) +{ + memset(motor->motor_can_instace->tx_buff, 0xff, 7); // 发送电机指令的时候前面7bytes都是0xff + motor->motor_can_instace->tx_buff[7] = (uint8_t)cmd; // 最后一位是命令id + CANTransmit(motor->motor_can_instace, 1); + memcpy(motor->motor_can_instace->tx_buff, zero_buff, 6); +} +/* 两个用于将uint值和float值进行映射的函数,在设定发送值和解析反馈值时使用 */ +static uint16_t float_to_uint(float x, float x_min, float x_max, uint8_t bits) +{ + float span = x_max - x_min; + float offset = x_min; + return (uint16_t)((x - offset) * ((float)((1 << bits) - 1)) / span); +} +static float uint_to_float(int x_int, float x_min, float x_max, int bits) +{ + float span = x_max - x_min; + float offset = x_min; + return ((float)x_int) * span / ((float)((1 << bits) - 1)) + offset; +} + +/** + * @brief 解析电机反馈值 + * + * @param motor_can 收到 + */ +static void HTMotorDecode(CANInstance *motor_can) +{ + uint16_t tmp; // 用于暂存解析值,稍后转换成float数据,避免多次创建临时变量 + uint8_t const *rxbuff = motor_can->rx_buff; + HTMotorInstance *motor = (HTMotorInstance *)motor_can->id; + HTMotor_Measure_t *measure = &(motor->measure); // 将can实例中保存的id转换成电机实例的指针 + + DaemonReload(motor->motor_daemon); + measure->feed_dt = DWT_GetDeltaT(&measure->feed_cnt); + + measure->last_angle = measure->total_angle; + tmp = (uint16_t)((rxbuff[1] << 8) | rxbuff[2]); + measure->total_angle = uint_to_float(tmp, P_MIN, P_MAX, 16); + + tmp = (uint16_t)(rxbuff[3] << 4) | (rxbuff[4] >> 4); + measure->speed_rads = AverageFilter((uint_to_float(tmp, V_MIN, V_MAX, 12) - HT_SPEED_BIAS), measure->speed_buff, SPEED_BUFFER_SIZE); + + tmp = (uint16_t)(((rxbuff[4] & 0x0f) << 8) | rxbuff[5]); + measure->real_current = CURRENT_SMOOTH_COEF * uint_to_float(tmp, T_MIN, T_MAX, 12) + + (1 - CURRENT_SMOOTH_COEF) * measure->real_current; +} + +static void HTMotorLostCallback(void *motor_ptr) +{ + HTMotorInstance *motor = (HTMotorInstance *)motor_ptr; + LOGWARNING("[ht_motor] motor %d lost\n", motor->motor_can_instace->tx_id); + if (++motor->lost_cnt % 10 != 0) + HTMotorSetMode(CMD_MOTOR_MODE, motor); // 尝试重新让电机进入控制模式 +} + +/* 海泰电机一生黑,什么垃圾协议! */ +void HTMotorCalibEncoder(HTMotorInstance *motor) +{ + uint16_t p, v, kp, kd, t; + p = float_to_uint(0, P_MIN, P_MAX, 16); + v = float_to_uint(0, V_MIN, V_MAX, 12); + kp = float_to_uint(0, KP_MIN, KP_MAX, 12); + kd = float_to_uint(0, KD_MIN, KD_MAX, 12); + t = float_to_uint(0, T_MIN, T_MAX, 12); + + uint8_t *buf = motor->motor_can_instace->tx_buff; + buf[0] = p >> 8; + buf[1] = p & 0xFF; + buf[2] = v >> 4; + buf[3] = ((v & 0xF) << 4) | (kp >> 8); + buf[4] = kp & 0xFF; + buf[5] = kd >> 4; + buf[6] = ((kd & 0xF) << 4) | (t >> 8); + buf[7] = t & 0xff; + memcpy(zero_buff, buf, 6); // 初始化的时候至少调用一次,故将其他指令为0时发送的报文保存一下,详见ht04电机说明 + CANTransmit(motor->motor_can_instace, 1); + DWT_Delay(0.005); + HTMotorSetMode(CMD_ZERO_POSITION, motor); // sb 玩意校准完了编码器也不为0 + DWT_Delay(0.005); + // HTMotorSetMode(CMD_MOTOR_MODE, motor); +} + +HTMotorInstance *HTMotorInit(Motor_Init_Config_s *config) +{ + HTMotorInstance *motor = (HTMotorInstance *)malloc(sizeof(HTMotorInstance)); + memset(motor, 0, sizeof(HTMotorInstance)); + + motor->motor_settings = config->controller_setting_init_config; + PIDInit(&motor->current_PID, &config->controller_param_init_config.current_PID); + PIDInit(&motor->speed_PID, &config->controller_param_init_config.speed_PID); + PIDInit(&motor->angle_PID, &config->controller_param_init_config.angle_PID); + motor->other_angle_feedback_ptr = config->controller_param_init_config.other_angle_feedback_ptr; + motor->other_speed_feedback_ptr = config->controller_param_init_config.other_speed_feedback_ptr; + + config->can_init_config.can_module_callback = HTMotorDecode; + config->can_init_config.id = motor; + motor->motor_can_instace = CANRegister(&config->can_init_config); + + Daemon_Init_Config_s conf = { + .callback = HTMotorLostCallback, + .owner_id = motor, + .reload_count = 5, // 20ms + }; + motor->motor_daemon = DaemonRegister(&conf); + + HTMotorEnable(motor); + HTMotorSetMode(CMD_MOTOR_MODE, motor); // 确保电机已经上电并执行电机模式 + DWT_Delay(0.05f); + HTMotorCalibEncoder(motor); // 将当前编码器位置作为零位 + DWT_Delay(0.05f); // 保证下一个电机发送时CAN是空闲的,注意应用在初始化模块的时候不应该进入中断 + ht_motor_instance[idx++] = motor; + return motor; +} + +void HTMotorSetRef(HTMotorInstance *motor, float ref) +{ + motor->pid_ref = ref; +} + +/** + * @brief 为了避免总线堵塞,为每个电机创建一个发送任务 + * @param argument 传入的电机指针 + */ +__attribute__((noreturn)) void HTMotorTask(void const *argument) +{ + float set, pid_measure, pid_ref; + HTMotorInstance *motor = (HTMotorInstance *)argument; + HTMotor_Measure_t *measure = &motor->measure; + Motor_Control_Setting_s *setting = &motor->motor_settings; + CANInstance *motor_can = motor->motor_can_instace; + uint16_t tmp; + + while (1) + { + pid_ref = motor->pid_ref; + if ((setting->close_loop_type & ANGLE_LOOP) && setting->outer_loop_type == ANGLE_LOOP) + { + if (setting->angle_feedback_source == OTHER_FEED) + pid_measure = *motor->other_angle_feedback_ptr; + else + pid_measure = measure->total_angle; + // measure单位是rad,ref是角度,统一到angle下计算,方便建模 + pid_ref = PIDCalculate(&motor->angle_PID, pid_measure * RAD_2_DEGREE, pid_ref); + } + + if ((setting->close_loop_type & SPEED_LOOP) && setting->outer_loop_type & (ANGLE_LOOP | SPEED_LOOP)) + { + if (setting->feedforward_flag & SPEED_FEEDFORWARD) + pid_ref += *motor->speed_feedforward_ptr; + + if (setting->angle_feedback_source == OTHER_FEED) + pid_measure = *motor->other_speed_feedback_ptr; + else + pid_measure = measure->speed_rads; + // measure单位是rad / s ,ref是angle per sec,统一到angle下计算 + pid_ref = PIDCalculate(&motor->speed_PID, pid_measure * RAD_2_DEGREE, pid_ref); + } + + if (setting->feedforward_flag & CURRENT_FEEDFORWARD) + pid_ref += *motor->current_feedforward_ptr; + if (setting->close_loop_type & CURRENT_LOOP) + { + pid_ref = PIDCalculate(&motor->current_PID, measure->real_current, pid_ref); + } + + set = pid_ref; + if (setting->motor_reverse_flag == MOTOR_DIRECTION_REVERSE) + set *= -1; + + LIMIT_MIN_MAX(set, T_MIN, T_MAX); + tmp = float_to_uint(set, T_MIN, T_MAX, 12); + if (motor->stop_flag == MOTOR_STOP) + tmp = float_to_uint(0, T_MIN, T_MAX, 12); + motor_can->tx_buff[6] = (tmp >> 8); + motor_can->tx_buff[7] = tmp & 0xff; + + CANTransmit(motor_can, 0.5); + + osDelay(1); + } +} + +void HTMotorControlInit() +{ + char ht_task_name[5] = "ht"; + // 遍历所有电机实例,创建任务 + if (!idx) + return; + for (size_t i = 0; i < idx; i++) + { + char ht_id_buff[2] = {0}; + __itoa(i, ht_id_buff, 10); + strcat(ht_task_name, ht_id_buff); // 似乎没什么吊用,osthreaddef会把第一个变量当作宏字符串传入,作为任务名 + // @todo 还需要一个更优雅的方案来区分不同的电机任务 + osThreadDef(ht_task_name, HTMotorTask, osPriorityNormal, 0, 128); + ht_task_handle[i] = osThreadCreate(osThread(ht_task_name), ht_motor_instance[i]); + } +} + +void HTMotorStop(HTMotorInstance *motor) +{ + motor->stop_flag = MOTOR_STOP; +} + +void HTMotorEnable(HTMotorInstance *motor) +{ + motor->stop_flag = MOTOR_ENALBED; +} + +void HTMotorOuterLoop(HTMotorInstance *motor, Closeloop_Type_e type) +{ + motor->motor_settings.outer_loop_type = type; +} diff --git a/modules/motor/HTmotor/HT04.h b/modules/motor/HTmotor/HT04.h new file mode 100644 index 0000000..1ad61f5 --- /dev/null +++ b/modules/motor/HTmotor/HT04.h @@ -0,0 +1,123 @@ +#ifndef HT04_H +#define HT04_H + +#include +#include "bsp_can.h" +#include "controller.h" +#include "motor_def.h" +#include "daemon.h" + +#define HT_MOTOR_CNT 4 +#define CURRENT_SMOOTH_COEF 0.9f +#define SPEED_BUFFER_SIZE 5 +#define HT_SPEED_BIAS -0.0109901428f // 电机速度偏差,单位rad/s + +#define P_MIN -95.5f // Radians +#define P_MAX 95.5f +#define V_MIN -45.0f // Rad/s +#define V_MAX 45.0f +#define T_MIN -18.0f // N·m +#define T_MAX 18.0f +#define KP_MIN 0.0f // N-m/rad +#define KP_MAX 500.0f +#define KD_MIN 0.0f // N-m/rad/s +#define KD_MAX 5.0f + +typedef struct // HT04 +{ + float total_angle; // 角度为多圈角度,范围是-95.5~95.5,单位为rad + float last_angle; + + float speed_rads; + float speed_buff[SPEED_BUFFER_SIZE]; + + float real_current; + + float feed_dt; + uint32_t feed_cnt; +} HTMotor_Measure_t; + +/* HT电机类型定义*/ +typedef struct +{ + HTMotor_Measure_t measure; + + Motor_Control_Setting_s motor_settings; + + PIDInstance current_PID; + PIDInstance speed_PID; + PIDInstance angle_PID; + float *other_angle_feedback_ptr; + float *other_speed_feedback_ptr; + float *speed_feedforward_ptr; + float *current_feedforward_ptr; + float pid_ref; + + Motor_Working_Type_e stop_flag; // 启停标志 + + CANInstance *motor_can_instace; + + DaemonInstance *motor_daemon; + uint32_t lost_cnt; +} HTMotorInstance; + +/* HT电机模式,初始化时自动进入CMD_MOTOR_MODE*/ +typedef enum +{ + CMD_MOTOR_MODE = 0xfc, // 使能,会响应指令 + CMD_RESET_MODE = 0xfd, // 停止 + CMD_ZERO_POSITION = 0xfe // 将当前的位置设置为编码器零位 +} HTMotor_Mode_t; + +/** + * @brief + * + * @param config + * @return HTMotorInstance* + */ +HTMotorInstance *HTMotorInit(Motor_Init_Config_s *config); + +/** + * @brief 设定电机的参考值 + * + * @param motor 要设定的电机 + * @param current 设定值 + */ +void HTMotorSetRef(HTMotorInstance *motor, float ref); + +/** + * @brief 初始化电机任务,若要使用,需要在motortask的死循环前调用 + * + */ +void HTMotorControlInit(); + +/** + * @brief 停止电机,之后电机不会响应HTMotorSetRef设定的值 + * + * @param motor + */ +void HTMotorStop(HTMotorInstance *motor); + +/** + * @brief 启动电机 + * + * @param motor 要启动的电机 + */ +void HTMotorEnable(HTMotorInstance *motor); + +/** + * @brief 修改电机闭环对象 + * + * @param motor + * @param type + */ +void HTMotorOuterLoop(HTMotorInstance *motor, Closeloop_Type_e type); + +/** + * @brief 将当前编码器位置置零 + * + * @param motor + */ +void HTMotorCalibEncoder(HTMotorInstance *motor); + +#endif // !HT04_H#define HT04_H \ No newline at end of file diff --git a/modules/motor/HTmotor/HT04.md b/modules/motor/HTmotor/HT04.md new file mode 100644 index 0000000..2f3ba49 --- /dev/null +++ b/modules/motor/HTmotor/HT04.md @@ -0,0 +1,44 @@ +- 在通过串口设置电机的时候,注意发送指令不要追加回车\n,否则电机端不响应。可以使用sscom,其会将你的按键直接当作ascii字符发送出去。 + +- **此电机的CAN线序和RoboMaster开发板相反,注意单独制作CAN线** + +- 电机控制和反馈报文: +  + +注意,我们的代码实现不使用其电调协议的位置PD算法;自行实现了三环,并在最后给出电流参考值,发送给电调。因此command packed structure中的**pos cmd & vel cmd & Kp & Kd均为零**。报文均为小端,**低位在前**。 + +请注意发送和反馈数据的**单位**。 + +> ~~HT的电机协议做的真不行,纯纯直接抄mit还抄不明白,之后全部换成LK!~~ + +另一种上电时校准编码器的方法: + +```c +static void HTMotorDecode(CANInstance *motor_can) +{ + uint16_t tmp; // 用于暂存解析值,稍后转换成float数据,避免多次创建临时变量 + uint8_t *rxbuff = motor_can->rx_buff; + HTMotor_Measure_t *measure = &((HTMotorInstance *)motor_can->id)->measure; // 将can实例中保存的id转换成电机实例的指针 + + measure->last_angle = measure->total_angle; + tmp = (uint16_t)((rxbuff[1] << 8) | rxbuff[2]); + measure->total_angle = uint_to_float(tmp, P_MIN, P_MAX, 16) - measure->angle_bias; + + tmp = (uint16_t)(rxbuff[3] << 4) | (rxbuff[4] >> 4); + measure->speed_rads = AverageFilter((uint_to_float(tmp, V_MIN, V_MAX, 12) - HT_SPEED_BIAS), measure->speed_buff, SPEED_BUFFER_SIZE); + + tmp = (uint16_t)(((rxbuff[4] & 0x0f) << 8) | rxbuff[5]); + measure->real_current = CURRENT_SMOOTH_COEF * uint_to_float(tmp, T_MIN, T_MAX, 12) + + (1 - CURRENT_SMOOTH_COEF) * measure->real_current; + + if (!measure->first_feedback_flag) // 初始化的时候设置偏置 + { + measure->first_feedback_flag = 1; + measure->angle_bias = measure->total_angle; + measure->total_angle = 0; + measure->speed_rads = 0; + } +} +``` + +第一次收到数据时默认电机处于限位处,将速度和角度都设置为零,记录当前的编码器数据,之后每次收到都减去该值. diff --git a/modules/motor/HTmotor/控制报文.png b/modules/motor/HTmotor/控制报文.png new file mode 100644 index 0000000..ebc490e Binary files /dev/null and b/modules/motor/HTmotor/控制报文.png differ diff --git a/modules/motor/HTmotor/驱动器硬件说明.pdf b/modules/motor/HTmotor/驱动器硬件说明.pdf new file mode 100644 index 0000000..2b990fa Binary files /dev/null and b/modules/motor/HTmotor/驱动器硬件说明.pdf differ diff --git a/modules/motor/LKmotor/LK-TECH电机CAN协议说明V2_3.pdf b/modules/motor/LKmotor/LK-TECH电机CAN协议说明V2_3.pdf new file mode 100644 index 0000000..47d3206 Binary files /dev/null and b/modules/motor/LKmotor/LK-TECH电机CAN协议说明V2_3.pdf differ diff --git a/modules/motor/LKmotor/LKMotor.c b/modules/motor/LKmotor/LKMotor.c new file mode 100644 index 0000000..24a67ea --- /dev/null +++ b/modules/motor/LKmotor/LKMotor.c @@ -0,0 +1,177 @@ +#include "LKMotor.h" +#include "stdlib.h" +#include "general_def.h" +#include "daemon.h" +#include "bsp_dwt.h" +#include "bsp_log.h" + +static uint8_t idx; +static LKMotorInstance *lkmotor_instance[LK_MOTOR_MX_CNT] = {NULL}; +static CANInstance *sender_instance; // 多电机发送时使用的caninstance(当前保存的是注册的第一个电机的caninstance) +// 后续考虑兼容单电机和多电机指令. + +/** + * @brief 电机反馈报文解析 + * + * @param _instance 发生中断的caninstance + */ +static void LKMotorDecode(CANInstance *_instance) +{ + LKMotorInstance *motor = (LKMotorInstance *)_instance->id; // 通过caninstance保存的father id获取对应的motorinstance + LKMotor_Measure_t *measure = &motor->measure; + uint8_t *rx_buff = _instance->rx_buff; + + DaemonReload(motor->daemon); // 喂狗 + measure->feed_dt = DWT_GetDeltaT(&measure->feed_dwt_cnt); + + measure->last_ecd = measure->ecd; + measure->ecd = (uint16_t)((rx_buff[7] << 8) | rx_buff[6]); + + measure->angle_single_round = ECD_ANGLE_COEF_LK * measure->ecd; + + measure->speed_rads = (1 - SPEED_SMOOTH_COEF) * measure->speed_rads + + DEGREE_2_RAD * SPEED_SMOOTH_COEF * (float)((int16_t)(rx_buff[5] << 8 | rx_buff[4])); + + measure->real_current = (1 - CURRENT_SMOOTH_COEF) * measure->real_current + + CURRENT_SMOOTH_COEF * (float)((int16_t)(rx_buff[3] << 8 | rx_buff[2])); + + measure->temperature = rx_buff[1]; + + if (measure->ecd - measure->last_ecd > 65536)//MFV2是18bit编码器,这里用65536判断是否发生了跨越零点 + measure->total_round--; + else if (measure->ecd - measure->last_ecd < -65536) + measure->total_round++; + measure->total_angle = measure->total_round * 360 + measure->angle_single_round; +} + +static void LKMotorLostCallback(void *motor_ptr) +{ + LKMotorInstance *motor = (LKMotorInstance *)motor_ptr; + LOGWARNING("[LKMotor] motor lost, id: %d", motor->motor_can_ins->tx_id); +} + +LKMotorInstance *LKMotorInit(Motor_Init_Config_s *config) +{ + LKMotorInstance *motor = (LKMotorInstance *)malloc(sizeof(LKMotorInstance)); + motor = (LKMotorInstance *)malloc(sizeof(LKMotorInstance)); + memset(motor, 0, sizeof(LKMotorInstance)); + + motor->motor_settings = config->controller_setting_init_config; + PIDInit(&motor->current_PID, &config->controller_param_init_config.current_PID); + PIDInit(&motor->speed_PID, &config->controller_param_init_config.speed_PID); + PIDInit(&motor->angle_PID, &config->controller_param_init_config.angle_PID); + motor->other_angle_feedback_ptr = config->controller_param_init_config.other_angle_feedback_ptr; + motor->other_speed_feedback_ptr = config->controller_param_init_config.other_speed_feedback_ptr; + + config->can_init_config.id = motor; + config->can_init_config.can_module_callback = LKMotorDecode; + config->can_init_config.rx_id = 0x140 + config->can_init_config.tx_id; + config->can_init_config.tx_id = config->can_init_config.tx_id + 0x280 - 1; // 这样在发送写入buffer的时候更方便,因为下标从0开始,LK多电机发送id为0x280 + motor->motor_can_ins = CANRegister(&config->can_init_config); + + if (idx == 0) // 用第一个电机的can instance发送数据 + { + sender_instance = motor->motor_can_ins; + sender_instance->tx_id = 0x280; // 修改tx_id为0x280,用于多电机发送,不用管其他LKMotorInstance的tx_id,它们仅作初始化用 + } + + LKMotorEnable(motor); + DWT_GetDeltaT(&motor->measure.feed_dwt_cnt); + lkmotor_instance[idx++] = motor; + + Daemon_Init_Config_s daemon_config = { + .callback = LKMotorLostCallback, + .owner_id = motor, + .reload_count = 5, // 50ms + }; + motor->daemon = DaemonRegister(&daemon_config); + + return motor; +} + +/* 第一个电机的can instance用于发送数据,向其tx_buff填充数据 */ +void LKMotorControl() +{ + float pid_measure, pid_ref; + int16_t set; + LKMotorInstance *motor; + LKMotor_Measure_t *measure; + Motor_Control_Setting_s *setting; + + for (size_t i = 0; i < idx; ++i) + { + motor = lkmotor_instance[i]; + measure = &motor->measure; + setting = &motor->motor_settings; + pid_ref = motor->pid_ref; + + if (setting->motor_reverse_flag == MOTOR_DIRECTION_REVERSE) + pid_ref *= -1; + + // 角度环计算 + if ((setting->close_loop_type & ANGLE_LOOP) && setting->outer_loop_type == ANGLE_LOOP) + { + if (setting->angle_feedback_source == OTHER_FEED) + pid_measure = *motor->other_angle_feedback_ptr; + else + pid_measure = measure->total_angle; // 修正:使用角度反馈 + pid_ref = PIDCalculate(&motor->angle_PID, pid_measure, pid_ref); + if (setting->feedforward_flag & SPEED_FEEDFORWARD) + pid_ref += *motor->speed_feedforward_ptr; + } + + // 速度环计算 + if ((setting->close_loop_type & SPEED_LOOP) && setting->outer_loop_type & (ANGLE_LOOP | SPEED_LOOP)) + { + if (setting->speed_feedback_source == OTHER_FEED) // 修正:判断speed_feedback_source + pid_measure = *motor->other_speed_feedback_ptr; + else + pid_measure = measure->speed_rads; // 修正:使用速度反馈 + pid_ref = PIDCalculate(&motor->speed_PID, pid_measure, pid_ref); // 修正:使用speed_PID + if (setting->feedforward_flag & CURRENT_FEEDFORWARD) + pid_ref += *motor->current_feedforward_ptr; + } + + // 电流环计算 + if (setting->close_loop_type & CURRENT_LOOP) + { + pid_ref = PIDCalculate(&motor->current_PID, measure->real_current, pid_ref); + } + + // 反馈方向反转 + if (setting->feedback_reverse_flag == FEEDBACK_DIRECTION_REVERSE) + pid_ref *= -1; + + set = (int16_t)pid_ref; + + memcpy(sender_instance->tx_buff + (motor->motor_can_ins->tx_id - 0x280) * 2, &set, sizeof(uint16_t)); + + if (motor->stop_flag == MOTOR_STOP) + { + memset(sender_instance->tx_buff + (motor->motor_can_ins->tx_id - 0x280) * 2, 0, sizeof(uint16_t)); + } + } + + if (idx) + CANTransmit(sender_instance, 0.2); +} + +void LKMotorStop(LKMotorInstance *motor) +{ + motor->stop_flag = MOTOR_STOP; +} + +void LKMotorEnable(LKMotorInstance *motor) +{ + motor->stop_flag = MOTOR_ENALBED; +} + +void LKMotorSetRef(LKMotorInstance *motor, float ref) +{ + motor->pid_ref = ref; +} + +uint8_t LKMotorIsOnline(LKMotorInstance *motor) +{ + return DaemonIsOnline(motor->daemon); +} diff --git a/modules/motor/LKmotor/LKMotor.h b/modules/motor/LKmotor/LKMotor.h new file mode 100644 index 0000000..df8dff9 --- /dev/null +++ b/modules/motor/LKmotor/LKMotor.h @@ -0,0 +1,98 @@ +#ifndef LKMOTOR_H +#define LKMOTOR_H + +#include "stdint.h" +#include "bsp_can.h" +#include "controller.h" +#include "motor_def.h" +#include "daemon.h" + +#define LK_MOTOR_MX_CNT 4 // 最多允许4个LK电机使用多电机指令,挂载在一条总线上 + +#define I_MIN -2000 +#define I_MAX 2000 +#define CURRENT_SMOOTH_COEF 0.9f +#define SPEED_SMOOTH_COEF 0.85f +#define REDUCTION_RATIO_DRIVEN 1 +#define ECD_ANGLE_COEF_LK (360.0f / 65536.0f) +#define CURRENT_TORQUE_COEF_LK 0.003645f // 电流设定值转换成扭矩的系数,算出来的设定值除以这个系数就是扭矩值 + +typedef struct // 9025 +{ + uint16_t last_ecd; // 上一次读取的编码器值 + uint16_t ecd; // 当前编码器值 + float angle_single_round; // 单圈角度 + float speed_rads; // speed rad/s + int16_t real_current; // 实际电流 + uint8_t temperature; // 温度,C° + + float total_angle; // 总角度 + int32_t total_round; // 总圈数 + + float feed_dt; + uint32_t feed_dwt_cnt; +} LKMotor_Measure_t; + +typedef struct +{ + LKMotor_Measure_t measure; + + Motor_Control_Setting_s motor_settings; + + float *other_angle_feedback_ptr; // 其他反馈来源的反馈数据指针 + float *other_speed_feedback_ptr; + float *speed_feedforward_ptr; // 速度前馈数据指针,可以通过此指针设置速度前馈值,或LQR等时作为速度状态变量的输入 + float *current_feedforward_ptr; // 电流前馈指针 + PIDInstance current_PID; + PIDInstance speed_PID; + PIDInstance angle_PID; + float pid_ref; + + Motor_Working_Type_e stop_flag; // 启停标志 + + CANInstance *motor_can_ins; + + DaemonInstance *daemon; + +} LKMotorInstance; + +/** + * @brief 初始化LK电机 + * + * @param config 电机配置 + * @return LKMotorInstance* 返回实例指针 + */ +LKMotorInstance *LKMotorInit(Motor_Init_Config_s *config); + +/** + * @brief 设置参考值 + * @attention 注意此函数设定的ref是最外层闭环的输入,若要设定内层闭环的值请通过前馈数据指针设置 + * + * @param motor 要设置的电机 + * @param ref 设定值 + */ +void LKMotorSetRef(LKMotorInstance *motor, float ref); + +/** + * @brief 为所有LK电机计算pid/反转/模式控制,并通过bspcan发送电流值(发送CAN报文) + * + */ +void LKMotorControl(); + +/** + * @brief 停止LK电机,之后电机不会响应任何指令 + * + * @param motor + */ +void LKMotorStop(LKMotorInstance *motor); + +/** + * @brief 启动LK电机 + * + * @param motor + */ +void LKMotorEnable(LKMotorInstance *motor); + +uint8_t LKMotorIsOnline(LKMotorInstance *motor); + +#endif // LKMotor_H diff --git a/modules/motor/LKmotor/LK_motor.md b/modules/motor/LKmotor/LK_motor.md new file mode 100644 index 0000000..6784747 --- /dev/null +++ b/modules/motor/LKmotor/LK_motor.md @@ -0,0 +1,12 @@ +# LK motor + +这是瓴控电机的模块封装说明文档。关于LK电机的控制报文和反馈报文值,详见LK电机的说明文档,由于电机实例已经自带三环PID计算,一般来说**我们能用到的只有单电机的力矩指令和多电机指令。** + +注意LK电机在使用多电机发送的时候,只支持一条总线上至多4个电机,多电机模式下LK仅支持发送id 0x280为接收ID为0x140+id. + +要设置为多电机模式,请通过串口连接电机,并使用该文件夹下的LK motor tool.exe进行配置。 + + +## LK的其他电机 + +若使用其他LK电机,唯一需要修改的是确定编码器的精度,即LKMotorDecode()部分的速度反馈和编码器反馈解析。 \ No newline at end of file diff --git a/modules/motor/LKmotor/反馈报文.png b/modules/motor/LKmotor/反馈报文.png new file mode 100644 index 0000000..554042a Binary files /dev/null and b/modules/motor/LKmotor/反馈报文.png differ diff --git a/modules/motor/LKmotor/报文格式.png b/modules/motor/LKmotor/报文格式.png new file mode 100644 index 0000000..882a23d Binary files /dev/null and b/modules/motor/LKmotor/报文格式.png differ diff --git a/modules/motor/motor_def.h b/modules/motor/motor_def.h new file mode 100644 index 0000000..68a3b49 --- /dev/null +++ b/modules/motor/motor_def.h @@ -0,0 +1,140 @@ +/** + * @file motor_def.h + * @author neozng + * @brief 电机通用的数据结构定义 + * @version beta + * @date 2022-11-01 + * + * @copyright Copyright (c) 2022 HNU YueLu EC all rights reserved + * + */ + +#ifndef MOTOR_DEF_H +#define MOTOR_DEF_H + +#include "controller.h" +#include "stdint.h" + +#define LIMIT_MIN_MAX(x, min, max) (x) = (((x) <= (min)) ? (min) : (((x) >= (max)) ? (max) : (x))) + +/** + * @brief 闭环类型,如果需要多个闭环,则使用或运算 + * 例如需要速度环和电流环: CURRENT_LOOP|SPEED_LOOP + */ +typedef enum +{ + OPEN_LOOP = 0b0000, + CURRENT_LOOP = 0b0001, + SPEED_LOOP = 0b0010, + ANGLE_LOOP = 0b0100, + + // only for checking + SPEED_AND_CURRENT_LOOP = 0b0011, + ANGLE_AND_SPEED_LOOP = 0b0110, + ALL_THREE_LOOP = 0b0111, +} Closeloop_Type_e; + +typedef enum +{ + FEEDFORWARD_NONE = 0b00, + CURRENT_FEEDFORWARD = 0b01, + SPEED_FEEDFORWARD = 0b10, + CURRENT_AND_SPEED_FEEDFORWARD = CURRENT_FEEDFORWARD | SPEED_FEEDFORWARD, +} Feedfoward_Type_e; + +/* 反馈来源设定,若设为OTHER_FEED则需要指定数据来源指针,详见Motor_Controller_s*/ +typedef enum +{ + MOTOR_FEED = 0, + OTHER_FEED, +} Feedback_Source_e; + +/* 电机正反转标志 */ +typedef enum +{ + MOTOR_DIRECTION_NORMAL = 0, + MOTOR_DIRECTION_REVERSE = 1 +} Motor_Reverse_Flag_e; + +/* 反馈量正反标志 */ +typedef enum +{ + FEEDBACK_DIRECTION_NORMAL = 0, + FEEDBACK_DIRECTION_REVERSE = 1 +} Feedback_Reverse_Flag_e; +typedef enum +{ + MOTOR_STOP = 0, + MOTOR_ENALBED = 1, +} Motor_Working_Type_e; + +/* 电机控制设置,包括闭环类型,反转标志和反馈来源 */ +typedef struct +{ + Closeloop_Type_e outer_loop_type; // 最外层的闭环,未设置时默认为最高级的闭环 + Closeloop_Type_e close_loop_type; // 使用几个闭环(串级) + Motor_Reverse_Flag_e motor_reverse_flag; // 是否反转 + Feedback_Reverse_Flag_e feedback_reverse_flag; // 反馈是否反向 + Feedback_Source_e angle_feedback_source; // 角度反馈类型 + Feedback_Source_e speed_feedback_source; // 速度反馈类型 + Feedfoward_Type_e feedforward_flag; // 前馈标志 + +} Motor_Control_Setting_s; + +/* 电机控制器,包括其他来源的反馈数据指针,3环控制器和电机的参考输入*/ +// 后续增加前馈数据指针 +typedef struct +{ + float *other_angle_feedback_ptr; // 其他反馈来源的反馈数据指针 + float *other_speed_feedback_ptr; + float *speed_feedforward_ptr; + float *current_feedforward_ptr; + + PIDInstance current_PID; + PIDInstance speed_PID; + PIDInstance angle_PID; + + float pid_ref; // 将会作为每个环的输入和输出顺次通过串级闭环 +} Motor_Controller_s; + +/* 电机类型枚举 */ +typedef enum +{ + MOTOR_TYPE_NONE = 0, + GM6020, + M3508, + M2006, + LK9025, + LK9015, + DM4310, + HT04, +} Motor_Type_e; + +/** + * @brief 电机控制器初始化结构体,包括三环PID的配置以及两个反馈数据来源指针 + * 如果不需要某个控制环,可以不设置对应的pid config + * 需要其他数据来源进行反馈闭环,不仅要设置这里的指针还需要在Motor_Control_Setting_s启用其他数据来源标志 + */ +typedef struct +{ + float *other_angle_feedback_ptr; // 角度反馈数据指针,注意电机使用total_angle + float *other_speed_feedback_ptr; // 速度反馈数据指针,单位为angle per sec + + float *speed_feedforward_ptr; // 速度前馈数据指针 + float *current_feedforward_ptr; // 电流前馈数据指针 + + PID_Init_Config_s current_PID; + PID_Init_Config_s speed_PID; + PID_Init_Config_s angle_PID; +} Motor_Controller_Init_s; + +/* 用于初始化CAN电机的结构体,各类电机通用 */ +typedef struct +{ + Motor_Controller_Init_s controller_param_init_config; + Motor_Control_Setting_s controller_setting_init_config; + Motor_Type_e motor_type; + CAN_Init_Config_s can_init_config; +} Motor_Init_Config_s; + +#endif // !MOTOR_DEF_H diff --git a/modules/motor/motor_task.c b/modules/motor/motor_task.c new file mode 100644 index 0000000..d751b4a --- /dev/null +++ b/modules/motor/motor_task.c @@ -0,0 +1,30 @@ +#include "motor_task.h" +#include "LKMotor.h" +#include "HT04.h" +#include "dji_motor.h" +#include "step_motor.h" +#include "servo_motor.h" + +void MotorControlTask() +{ + static uint8_t cnt = 0; // 设定不同电机的任务频率 + // if(cnt%5==0) //200hz + // if(cnt%10==0) //100hz + if(cnt%2==0) //500hz + { + DJIMotorControl(); + } + + /* 如果有对应的电机则取消注释,可以加入条件编译或者register对应的idx判断是否注册了电机 */ + LKMotorControl(); + + // legacy support + // 由于ht04电机的反馈方式为接收到一帧消息后立刻回传,以此方式连续发送可能导致总线拥塞 + // 为了保证高频率控制,HTMotor中提供了以任务方式启动控制的接口,可通过宏定义切换 + // HTMotorControl(); + // 将所有的CAN设备集中在一处发送,最高反馈频率仅能达到500Hz,为了更好的控制效果,应使用新的HTMotorControlInit()接口 + + // ServeoMotorControl(); + + // StepMotorControl(); +} diff --git a/modules/motor/motor_task.h b/modules/motor/motor_task.h new file mode 100644 index 0000000..214d3c1 --- /dev/null +++ b/modules/motor/motor_task.h @@ -0,0 +1,25 @@ +/** + * @file motor_task.h + * @author neozng + * @brief 对所有电机,舵机等控制任务的进一步封装,MotorControlTask()将在操作系统中按一定频率调用 + * @version beta + * @date 2022-11-01 + * + * @copyright Copyright (c) 2022 + * + */ +#ifndef MOTOR_TASK_H +#define MOTOR_TASK_H + + +/** + * @brief 电机控制闭环任务,在RTOS中应该设定为1Khz运行 + * 舵机控制任务的频率设定为20Hz或更低 + * + * @note 好无语,就一个函数罢了,干脆全部放到头文件里好了. + * + */ +void MotorControlTask(); + +#endif // !MOTOR_TASK_H + diff --git a/modules/motor/servo_motor/servo_motor.c b/modules/motor/servo_motor/servo_motor.c new file mode 100644 index 0000000..e5c4564 --- /dev/null +++ b/modules/motor/servo_motor/servo_motor.c @@ -0,0 +1,123 @@ +#include "servo_motor.h" +#include "stdlib.h" +#include "memory.h" + +extern TIM_HandleTypeDef htim1; +/*第二版*/ +static ServoInstance *servo_motor_instance[SERVO_MOTOR_CNT] = {NULL}; +static int16_t compare_value[SERVO_MOTOR_CNT] = {0}; +static uint8_t servo_idx = 0; // register servo_idx,是该文件的全局舵机索引,在注册时使用 + +// 通过此函数注册一个舵机 +ServoInstance *ServoInit(Servo_Init_Config_s *Servo_Init_Config) +{ + ServoInstance *servo = (ServoInstance *)malloc(sizeof(ServoInstance)); + memset(servo, 0, sizeof(ServoInstance)); + + servo->Servo_type = Servo_Init_Config->Servo_type; + servo->htim = Servo_Init_Config->htim; + servo->Channel = Servo_Init_Config->Channel; + + HAL_TIM_PWM_Start(Servo_Init_Config->htim, Servo_Init_Config->Channel); + servo_motor_instance[servo_idx++] = servo; + return servo; +} + +/** + * @brief 写入自由角度数值 + * + * @param Servo_Motor 注册的舵机实例 + * @param S_angle 改变自由模式设定的角度 + */ +void Servo_Motor_FreeAngle_Set(ServoInstance *Servo_Motor, int16_t S_angle) +{ + switch (Servo_Motor->Servo_type) + { + case Servo180: + if (S_angle > 180) + S_angle = 180; + break; + case Servo270: + if (S_angle > 270) + S_angle = 270; + break; + case Servo360: + if (S_angle > 100) + S_angle = 100; + break; + default: + break; + } + if (S_angle < 0) + S_angle = 0; + Servo_Motor->Servo_Angle.free_angle = S_angle; +} + +/** + * @brief 写入起始,终止角度数值 + * + * @param Servo_Motor 注册的舵机实例 + * @param Start_angle 起始角度 + * @param Final_angle 终止角度 + */ +void Servo_Motor_StartSTOP_Angle_Set(ServoInstance *Servo_Motor, int16_t Start_angle, int16_t Final_angle) +{ + Servo_Motor->Servo_Angle.Init_angle = Start_angle; + Servo_Motor->Servo_Angle.Final_angle = Final_angle; +} +/** + * @brief 舵机模式选择 + * + * @param Servo_Motor 注册的舵机实例 + * @param mode 需要选择的模式 + */ +void Servo_Motor_Type_Select(ServoInstance *Servo_Motor, int16_t mode) +{ + Servo_Motor->Servo_Angle_Type = mode; +} + +/** + * @brief 舵机输出控制 + * + */ +void ServeoMotorControl() +{ + ServoInstance *Servo_Motor; + + for (size_t i = 0; i < servo_idx; i++) + { + if (servo_motor_instance[i]) + { + Servo_Motor = servo_motor_instance[i]; + + switch (Servo_Motor->Servo_type) + { + case Servo180: + if (Servo_Motor->Servo_Angle_Type == Start_mode) + compare_value[i] = 0.5 * 20000 / 20 + Servo_Motor->Servo_Angle.Init_angle * 20000 / 20 / 90; + if (Servo_Motor->Servo_Angle_Type == Final_mode) + compare_value[i] = 0.5 * 20000 / 20 + Servo_Motor->Servo_Angle.Final_angle * 20000 / 20 / 90; + if (Servo_Motor->Servo_Angle_Type == Free_Angle_mode) + compare_value[i] = 0.5 * 20000 / 20 + Servo_Motor->Servo_Angle.free_angle * 20000 / 20 / 90; + __HAL_TIM_SET_COMPARE(Servo_Motor->htim, Servo_Motor->Channel, compare_value[i]); + break; + case Servo270: + if (Servo_Motor->Servo_Angle_Type == Start_mode) + compare_value[i] = 0.5 * 20000 / 20 + Servo_Motor->Servo_Angle.Init_angle * 20000 / 20 / 135; + if (Servo_Motor->Servo_Angle_Type == Final_mode) + compare_value[i] = 0.5 * 20000 / 20 + Servo_Motor->Servo_Angle.Final_angle * 20000 / 20 / 135; + if (Servo_Motor->Servo_Angle_Type == Free_Angle_mode) + compare_value[i] = 0.5 * 20000 / 20 + Servo_Motor->Servo_Angle.free_angle * 20000 / 20 / 135; + __HAL_TIM_SET_COMPARE(Servo_Motor->htim, Servo_Motor->Channel, compare_value[i]); + break; + case Servo360: + /*500-2500的占空比 500-1500对应正向转速 1500-2500对于反向转速*/ + compare_value[i] = 500 + 20 * Servo_Motor->Servo_Angle.servo360speed; + __HAL_TIM_SET_COMPARE(Servo_Motor->htim, Servo_Motor->Channel, compare_value[i]); + break; + default: + break; + } + } + } +} diff --git a/modules/motor/servo_motor/servo_motor.h b/modules/motor/servo_motor/servo_motor.h new file mode 100644 index 0000000..8ab6807 --- /dev/null +++ b/modules/motor/servo_motor/servo_motor.h @@ -0,0 +1,91 @@ +/** + * @file servo_motor.h + * @author panrui + * @brief 舵机控制头文件 + * @version 0.1 + * @date 2022-12-12 + * + * @copyright Copyright (c) 2022 + * + */ + +#ifndef SERVO_MOTOR_H +#define SERVO_MOTOR_H + +#include "main.h" +#include "tim.h" +// #include +#include + +#define SERVO_MOTOR_CNT 7 + +/*各种舵机类型*/ +typedef enum +{ + Servo180 = 0, + Servo270 = 1, + Servo360 = 2, +} Servo_Type_e; + +/*舵机模式选择*/ +typedef enum +{ + Free_Angle_mode, // 任意角度模式 + Start_mode, // 起始角度模式 + Final_mode, // 终止角度模式 +} Servo_Angle_Type_e; +/*角度设置*/ +typedef struct +{ + /*起止角度模式设置值*/ + int16_t Init_angle; + int16_t Final_angle; + /*任意角度模式设置值*/ + int16_t free_angle; + /*下述值仅仅适用于360°舵机 + *设定值为0-100 为速度值百分比 + *0-50为正转 速度由快到慢 + *51-100为反转 速度由慢到快 + */ + int16_t servo360speed; +} Servo_Angle_s; + +/* 用于初始化不同舵机的结构体,各类舵机通用 */ +typedef struct +{ + Servo_Type_e Servo_type; + Servo_Angle_Type_e Servo_Angle_Type; + // 使用的定时器类型及通道 + TIM_HandleTypeDef *htim; + /*Channel值设定 + *TIM_CHANNEL_1 + *TIM_CHANNEL_2 + *TIM_CHANNEL_3 + *TIM_CHANNEL_4 + *TIM_CHANNEL_ALL + */ + uint32_t Channel; + +} Servo_Init_Config_s; +typedef struct +{ + Servo_Angle_Type_e Servo_Angle_Type; + Servo_Angle_s Servo_Angle; + Servo_Type_e Servo_type; + // 使用的定时器类型及通道 + TIM_HandleTypeDef *htim; + /*Channel值设定 + *TIM_CHANNEL_1 + *TIM_CHANNEL_2 + *TIM_CHANNEL_3 + *TIM_CHANNEL_4 + *TIM_CHANNEL_ALL + */ + uint32_t Channel; +} ServoInstance; + +ServoInstance *ServoInit(Servo_Init_Config_s *Servo_Init_Config); +void Servo_Motor_FreeAngle_Set(ServoInstance *Servo_Motor, int16_t S_angle); +void Servo_Motor_Type_Select(ServoInstance *Servo_Motor,int16_t mode); +void ServeoMotorControl(); +#endif // SERVO_MOTOR_H \ No newline at end of file diff --git a/modules/motor/servo_motor/servo_motor.md b/modules/motor/servo_motor/servo_motor.md new file mode 100644 index 0000000..12d1079 --- /dev/null +++ b/modules/motor/servo_motor/servo_motor.md @@ -0,0 +1,70 @@ +##舵机的使用 + + panrui@hnu.edu.cn
+ +> todo: 由于新增了bsp_pwm的支持,舵机模块需要部分重构 +### 舵机基础知识 + +已最常见的SG90舵机为例,SG90舵机要求工作在频率为50HZ——周期为20ms的PWM波,且对应信号的高低电平在0.5ms - 2.5ms之间,对应的舵机转动角度如下表所示(当然也可以按照这个线性的对应关系去达到转动自己想要的角度,如想要转动60°,则高电平脉宽为大概为1.2ms,具体能不能转到特定的角度还和舵机的精度有关) + +>0.5ms-------------0度; 2.5% +>1.0ms------------45度; 5.0% +>1.5ms------------90度; 7.5% +>2.0ms-----------135度; 10.0% +>2.5ms-----------180度; 12.5% + +根据`Tout = (PSC+1)* (ARR+1)/Tclk`公式 +则我们需要产生50Hz的PWM波,则预分频的系数为 Prescaler = 168-1,自动重装载值 Counter Period = 20000-1,此时定时器产生的频率为 168Mhz/168/20000 = 50Hz。 当然这个值也可以自己设置,只要满足产生的频率为50Hz即可. +`__HAL_TIM_SET_COMPARE(htim, Channel, compare_value);` +这是设置占空比的函数 +eg:当初始占空比为1200/20000则为6%,根据20*6%=1.2ms (1.2-0.5)/(2.5-0.5)*180=63° 故舵机会转动63° +为了方便通过上述eg我们将所需要的角度与PWM计数值对应关系封装成函数。需要在初始化的時候输入我们所需要的角度和相关定时器参数即可。这样我们就可以设置SG90为参数范围内(0~180°)任意度数。 + +--- + +## 如何注册一个舵机实例 +!!! + +**注意!由于舵机为开环控制,无论选择舵机为何种类型,舵机都能够正常运行,但是运行的角度可能会与设定不同,请务必正确选择舵机型号!且最多添加7个舵机!** +我们可以像这样注册一个舵机实例 +```c + +static ServoInstance *leftservomoto; +//初始化参数 +Servo_Init_Config_s config={ + //舵机安装选择的定时器及通道 + //C板有常用的7路PWM输出:TIM1-1,2,3,4 TIM8-1,2,3 + .htim=&htim1, + .Channel=TIM_CHANNEL_1, + //舵机的初始化模式和类型 + .Servo_Angle_Type=Start_mode, + .Servo_type=Servo180, +}; +// 设置好参数后进行初始化并保留返回的指针 +leftservomoto = ServoInit(&config); +``` +>要控制一个舵机 我们提供了以下三个接口 +```c +//自由模式下,写入自由角度数值 +void Servo_Motor_FreeAngle_Set(ServoInstance *Servo_Motor, int16_t S_angle); +//起止模式下,写入起始,终止角度数值(防止反复写入起始和终止角度) +void Servo_Motor_StartSTOP_Angle_Set(ServoInstance *Servo_Motor, int16_t Start_angle, int16_t Final_angle); +/* + Free_Angle_mode, // 任意角度模式 + Start_mode, // 起始角度模式 + Final_mode, // 终止角度模式 +*/ +void Servo_Motor_Type_Select(ServoInstance *Servo_Motor,int16_t mode); +//比如我们要使用舵机,并更改一个舵机的模式 +void ServoTask() +{ + //更改leftservomoto为Free_Angle_mode模式 + Servo_Motor_Type_Select(leftservomoto,Free_Angle_mode); + //设置转到0角度 + Servo_Motor_FreeAngle_Set(leftservomoto, 0); + //调用函数,控制电机 + Servo_Motor_Control(); +} + + +``` \ No newline at end of file diff --git a/modules/motor/step_motor/step_motor.c b/modules/motor/step_motor/step_motor.c new file mode 100644 index 0000000..e69de29 diff --git a/modules/motor/step_motor/step_motor.h b/modules/motor/step_motor/step_motor.h new file mode 100644 index 0000000..e69de29 diff --git a/modules/oled/oled.c b/modules/oled/oled.c new file mode 100644 index 0000000..a9e62c9 --- /dev/null +++ b/modules/oled/oled.c @@ -0,0 +1,378 @@ +#include "oled.h" +#include "oledfont.h" +#include "main.h" +#include+#include + +extern I2C_HandleTypeDef hi2c2; +static uint8_t OLED_GRAM[128][8]; + +/** + * @brief 写数据或者指令到OLED, 如果使用的是SPI,请重写这个函数 + * @param[in] dat: 要写入的字节 + * @param[in] cmd: OLED_CMD 代表写入的字节是指令; OLED_DATA 代表写入的字节是数据 + * @retval none + */ +void oled_write_byte(uint8_t dat, uint8_t cmd) +{ + static uint8_t cmd_data[2]; + if(cmd == OLED_CMD) + { + cmd_data[0] = 0x00; + } + else + { + cmd_data[0] = 0x40; + } + cmd_data[1] = dat; + HAL_I2C_Master_Transmit(&hi2c2, OLED_I2C_ADDRESS, cmd_data, 2, 10); +} + + +/** + * @brief 初始化OLED模块, + * @param[in] none + * @retval none + */ +void OLED_init(void) +{ + oled_write_byte(0xAE, OLED_CMD); //display off + oled_write_byte(0x20, OLED_CMD); //Set Memory Addressing Mode + oled_write_byte(0x10, OLED_CMD); //00,Horizontal Addressing Mode;01,Vertical Addressing Mode;10,Page Addressing Mode (RESET);11,Invalid + oled_write_byte(0xb0, OLED_CMD); //Set Page Start Address for Page Addressing Mode,0-7 + oled_write_byte(0xc8, OLED_CMD); //Set COM Output Scan Direction + oled_write_byte(0x00, OLED_CMD); //---set low column address + oled_write_byte(0x10, OLED_CMD); //---set high column address + oled_write_byte(0x40, OLED_CMD); //--set start line address + oled_write_byte(0x81, OLED_CMD); //--set contrast control register + oled_write_byte(0xff, OLED_CMD); //brightness 0x00~0xff + oled_write_byte(0xa1, OLED_CMD); //--set segment re-map 0 to 127 + oled_write_byte(0xa6, OLED_CMD); //--set normal display + oled_write_byte(0xa8, OLED_CMD); //--set multiplex ratio(1 to 64) + oled_write_byte(0x3F, OLED_CMD); // + oled_write_byte(0xa4, OLED_CMD); //0xa4,Output follows RAM content;0xa5,Output ignores RAM content + oled_write_byte(0xd3, OLED_CMD); //-set display offset + oled_write_byte(0x00, OLED_CMD); //-not offset + oled_write_byte(0xd5, OLED_CMD); //--set display clock divide ratio/oscillator frequency + oled_write_byte(0xf0, OLED_CMD); //--set divide ratio + oled_write_byte(0xd9, OLED_CMD); //--set pre-charge period + oled_write_byte(0x22, OLED_CMD); // + oled_write_byte(0xda, OLED_CMD); //--set com pins hardware configuration + oled_write_byte(0x12, OLED_CMD); + oled_write_byte(0xdb, OLED_CMD); //--set vcomh + oled_write_byte(0x20, OLED_CMD); //0x20,0.77xVcc + oled_write_byte(0x8d, OLED_CMD); //--set DC-DC enable + oled_write_byte(0x14, OLED_CMD); // + oled_write_byte(0xaf, OLED_CMD); //--turn on oled panel +} + + +/** + * @brief 打开OLED显示 + * @param[in] none + * @retval none + */ +void OLED_display_on(void) +{ + oled_write_byte(0x8d, OLED_CMD); + oled_write_byte(0x14, OLED_CMD); + oled_write_byte(0xaf, OLED_CMD); +} + + +/** + * @brief 关闭OLED显示 + * @param[in] none + * @retval none + */ +void OLED_display_off(void) +{ + oled_write_byte(0x8d, OLED_CMD); + oled_write_byte(0x10, OLED_CMD); + oled_write_byte(0xae, OLED_CMD); +} + + +/** + * @brief 操作GRAM内存(128*8char数组) + * @param[in] pen: 操作类型. + PEN_CLEAR: 设置为0x00 + PEN_WRITE: 设置为0xff + PEN_INVERSION: 按位取反 + * @retval none + */ +void OLED_operate_gram(pen_typedef pen) +{ + uint8_t i, n; + + for (i = 0; i < 8; i++) + { + for (n = 0; n < 128; n++) + { + if (pen == PEN_WRITE) + { + OLED_GRAM[n][i] = 0xff; + } + else if (pen == PEN_CLEAR) + { + OLED_GRAM[n][i] = 0x00; + } + else + { + OLED_GRAM[n][i] = 0xff - OLED_GRAM[n][i]; + } + } + } +} + +/** + * @brief 设置光标起点(x,y) + * @param[in] x:x轴, 从 0 到 127 + * @param[in] y:y轴, 从 0 到 7 + * @retval none + */ +void OLED_set_pos(uint8_t x, uint8_t y) +{ + oled_write_byte((0xb0 + y), OLED_CMD); //set page address y + oled_write_byte(((x&0xf0)>>4)|0x10, OLED_CMD); //set column high address + oled_write_byte((x&0x0f), OLED_CMD); //set column low address +} + +/** + * @brief 操作GRAM中的一个位,相当于操作屏幕的一个点 + * @param[in] x:x轴, [0,X_WIDTH-1] + * @param[in] y:y轴, [0,Y_WIDTH-1] + * @param[in] pen: 操作类型, + PEN_CLEAR: 设置 (x,y) 点为 0 + PEN_WRITE: 设置 (x,y) 点为 1 + PEN_INVERSION: (x,y) 值反转 + * @retval none + */ +void OLED_draw_point(int8_t x, int8_t y, pen_typedef pen) +{ + uint8_t page = 0, row = 0; + + /* check the corrdinate */ + if ((x < 0) || (x > (X_WIDTH - 1)) || (y < 0) || (y > (Y_WIDTH - 1))) + { + return; + } + page = y / 8; + row = y % 8; + + if (pen == PEN_WRITE) + { + OLED_GRAM[x][page] |= 1 << row; + } + else if (pen == PEN_INVERSION) + { + OLED_GRAM[x][page] ^= 1 << row; + } + else + { + OLED_GRAM[x][page] &= ~(1 << row); + } +} + + +/** + * @brief 画一条直线,从(x1,y1)到(x2,y2) + * @param[in] x1: 起点 + * @param[in] y1: 起点 + * @param[in] x2: 终点 + * @param[in] y2: 终点 + * @param[in] pen: 操作类型,PEN_CLEAR,PEN_WRITE,PEN_INVERSION. + * @retval none + */ + +void OLED_draw_line(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2, pen_typedef pen) +{ + uint8_t col = 0, row = 0; + uint8_t x_st = 0, x_ed = 0, y_st = 0, y_ed = 0; + float k = 0.0f, b = 0.0f; + + if (y1 == y2) + { + (x1 <= x2) ? (x_st = x1):(x_st = x2); + (x1 <= x2) ? (x_ed = x2):(x_ed = x1); + + for (col = x_st; col <= x_ed; col++) + { + OLED_draw_point(col, y1, pen); + } + } + else if (x1 == x2) + { + (y1 <= y2) ? (y_st = y1):(y_st = y2); + (y1 <= y2) ? (y_ed = y2):(y_ed = y1); + + for (row = y_st; row <= y_ed; row++) + { + OLED_draw_point(x1, row, pen); + } + } + else + { + k = ((float)(y2 - y1)) / (x2 - x1); + b = (float)y1 - k * x1; + + (x1 <= x2) ? (x_st = x1):(x_st = x2); + (x1 <= x2) ? (x_ed = x2):(x_ed = x2); + + for (col = x_st; col <= x_ed; col++) + { + OLED_draw_point(col, (uint8_t)(col * k + b), pen); + } + } +} + +/** + * @brief 显示一个字符 + * @param[in] row: 字符的开始行 + * @param[in] col: 字符的开始列 + * @param[in] chr: 字符 + * @retval none + */ +void OLED_show_char(uint8_t row, uint8_t col, uint8_t chr) +{ + uint8_t x = col * 6; + uint8_t y = row * 12; + uint8_t temp, t, t1; + uint8_t y0 = y; + chr = chr - ' '; + + for (t = 0; t < 12; t++) + { + temp = asc2_1206[chr][t]; + + for (t1 = 0; t1 < 8; t1++) + { + if (temp&0x80) + OLED_draw_point(x, y, PEN_WRITE); + else + OLED_draw_point(x, y, PEN_CLEAR); + + temp <<= 1; + y++; + if ((y - y0) == 12) + { + y = y0; + x++; + break; + } + } + } +} + +/** + * @brief 显示一个字符串 + * @param[in] row: 字符串的开始行 + * @param[in] col: 字符串的开始列 + * @param[in] chr: 字符串 + * @retval none + */ +void OLED_show_string(uint8_t row, uint8_t col, uint8_t *chr) +{ + uint8_t n =0; + + while (chr[n] != '\0') + { + OLED_show_char(row, col, chr[n]); + col++; + + if (col > 20) + { + col = 0; + row += 1; + } + n++; + } +} + + +/** + * @brief 格式输出 + * @param[in] row: 开始列,0 <= row <= 4; + * @param[in] col: 开始行, 0 <= col <= 20; + * @param[in] *fmt:格式化输出字符串 + * @note 如果字符串长度大于一行,额外的字符会换行 + * @retval none + */ +void OLED_printf(uint8_t row, uint8_t col, const char *fmt,...) +{ + static uint8_t LCD_BUF[128] = {0}; + static va_list ap; + uint8_t remain_size = 0; + + if ((row > 4) || (col > 20) ) + { + return; + } + va_start(ap, fmt); + + vsprintf((char *)LCD_BUF, fmt, ap); + + va_end(ap); + + remain_size = 21 - col; + + LCD_BUF[remain_size] = '\0'; + + OLED_show_string(row, col, LCD_BUF); +} + +/** + * @brief 发送数据到OLED的GRAM + * @param[in] none + * @retval none + */ +void OLED_refresh_gram(void) +{ + uint8_t i, n; + + for (i = 0; i < 8; i++) + { + OLED_set_pos(0, i); + for (n = 0; n < 128; n++) + { + oled_write_byte(OLED_GRAM[n][i], OLED_DATA); + } + } +} + + + +/** + * @brief 显示RM的LOGO + * @param[in] none + * @retval none + */ +void OLED_LOGO(void) +{ + uint8_t temp_char = 0; + uint8_t x = 0, y = 0; + uint8_t i = 0; + OLED_operate_gram(PEN_CLEAR); + + + for(; y < 64; y += 8) + { + for(x = 0; x < 128; x++) + { + temp_char = LOGO_BMP[x][y/8]; + for(i = 0; i < 8; i++) + { + if(temp_char & 0x80) + { + OLED_draw_point(x, y + i,PEN_WRITE); + } + else + { + OLED_draw_point(x,y + i,PEN_CLEAR); + } + temp_char <<= 1; + } + } + } + OLED_refresh_gram(); +} \ No newline at end of file diff --git a/modules/oled/oled.h b/modules/oled/oled.h new file mode 100644 index 0000000..f1bb53d --- /dev/null +++ b/modules/oled/oled.h @@ -0,0 +1,145 @@ +/** + * @file oled.h + * @author your name (you@domain.com) + * @brief 待重构实现 + * @version 0.1 + * @date 2023-02-14 + * @todo 请重构show string/init/clean/update buffer等的实现 + * + * @copyright Copyright (c) 2023 + * + */ + +#ifndef OLED_H +#define OLED_H +#include + +// the I2C address of oled +#define OLED_I2C_ADDRESS 0x78 + +// the resolution of oled 128*64 +#define MAX_COLUMN 128 +#define MAX_ROW 64 + +#define X_WIDTH MAX_COLUMN +#define Y_WIDTH MAX_ROW + +#define OLED_CMD 0x00 +#define OLED_DATA 0x01 + +#define CHAR_SIZE_WIDTH 6 +#define CHAR_SIZE_HIGHT 12 + +typedef enum +{ + PEN_CLEAR = 0x00, + PEN_WRITE = 0x01, + PEN_INVERSION = 0x02, +} pen_typedef; + +/** + * @brief 初始化OLED模块, + * @param[in] none + * @retval none + */ +extern void OLED_init(void); + +/** + * @brief 打开OLED显示 + * @param[in] none + * @retval none + */ +extern void OLED_display_on(void); + +/** + * @brief 关闭OLED显示 + * @param[in] none + * @retval none + */ +extern void OLED_display_off(void); + +/** + * @brief 操作GRAM内存(128*8char数组) + * @param[in] pen: 操作类型. + PEN_CLEAR: 设置为0x00 + PEN_WRITE: 设置为0xff + PEN_INVERSION: 按位取反 + * @retval none + */ +extern void OLED_operate_gram(pen_typedef pen); + +/** + * @brief 设置光标起点(x,y) + * @param[in] x:x轴, 从 0 到 127 + * @param[in] y:y轴, 从 0 到 7 + * @retval none + */ +extern void OLED_set_pos(uint8_t x, uint8_t y); + +/** + * @brief 操作GRAM中的一个位,相当于操作屏幕的一个点 + * @param[in] x:x轴, [0,X_WIDTH-1] + * @param[in] y:y轴, [0,Y_WIDTH-1] + * @param[in] pen: 操作类型, + PEN_CLEAR: 设置 (x,y) 点为 0 + PEN_WRITE: 设置 (x,y) 点为 1 + PEN_INVERSION: (x,y) 值反转 + * @retval none + */ +extern void OLED_draw_point(int8_t x, int8_t y, pen_typedef pen); + +/** + * @brief 画一条直线,从(x1,y1)到(x2,y2) + * @param[in] x1: 起点 + * @param[in] y1: 起点 + * @param[in] x2: 终点 + * @param[in] y2: 终点 + * @param[in] pen: 操作类型,PEN_CLEAR,PEN_WRITE,PEN_INVERSION. + * @retval none + */ +extern void OLED_draw_line(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2, pen_typedef pen); + +/** + * @brief 显示一个字符 + * @param[in] row: 字符的开始行 + * @param[in] col: 字符的开始列 + * @param[in] chr: 字符 + * @retval none + */ +extern void OLED_show_char(uint8_t row, uint8_t col, uint8_t chr); + +/** + * @brief 显示一个字符串 + * @param[in] row: 字符串的开始行 + * @param[in] col: 字符串的开始列 + * @param[in] chr: 字符串 + * @retval none + */ +extern void OLED_show_string(uint8_t row, uint8_t col, uint8_t *chr); + +/** + * @brief 格式输出 + * @param[in] row: 开始列,0 <= row <= 4; + * @param[in] col: 开始行, 0 <= col <= 20; + * @param[in] *fmt:格式化输出字符串 + * @note 如果字符串长度大于一行,额外的字符会换行 + * @retval none + */ +extern void OLED_printf(uint8_t row, uint8_t col, const char *fmt, ...); + + +/** + * @brief 发送数据到OLED的GRAM + * @param[in] none + * @retval none + */ +extern void OLED_refresh_gram(void); + + +/** + * @brief 显示RM的LOGO + * @param[in] none + * @retval none + */ +extern void OLED_LOGO(void); +#endif diff --git a/modules/oled/oled.md b/modules/oled/oled.md new file mode 100644 index 0000000..f7610e7 --- /dev/null +++ b/modules/oled/oled.md @@ -0,0 +1,11 @@ +# oled + +当前oled支持不完整,api较为混乱. 需要使用bsp_iic进行实现的重构,并提供统一方便的接口 + +请使用字库软件制作自己的图标和不同大小的ascii码. + +> 后续尝试移植一些图形库使得功能更加丰富 +> oled主要作调试和log/错误显示等使用 +> 可以提供给视觉和机械的同学调试接口,方便他们通过显示屏进行简单的设置 + +*可以引入RoboMaster oled,或额外增加一个编码器用于控制oled界面并设定一些功能.* \ No newline at end of file diff --git a/modules/oled/oledfont.h b/modules/oled/oledfont.h new file mode 100644 index 0000000..f2ee51e --- /dev/null +++ b/modules/oled/oledfont.h @@ -0,0 +1,247 @@ +/** + ***************************************(C) COPYRIGHT 2019 DJI*************************************** + * @file oledfont.h + * @brief character lib of oled + * @note + * @Version V1.0.0 + * @Date Oct-7-2019 + ***************************************(C) COPYRIGHT 2019 DJI*************************************** + */ + +#ifndef __OLED__FONT__H +#define __OLED__FONT__H + +//the common ascii character +const unsigned char asc2_1206[95][12]={ +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*" ",0*/ +{0x00,0x00,0x00,0x00,0x3F,0x40,0x00,0x00,0x00,0x00,0x00,0x00},/*"!",1*/ +{0x00,0x00,0x30,0x00,0x40,0x00,0x30,0x00,0x40,0x00,0x00,0x00},/*""",2*/ +{0x09,0x00,0x0B,0xC0,0x3D,0x00,0x0B,0xC0,0x3D,0x00,0x09,0x00},/*"#",3*/ +{0x18,0xC0,0x24,0x40,0x7F,0xE0,0x22,0x40,0x31,0x80,0x00,0x00},/*"$",4*/ +{0x18,0x00,0x24,0xC0,0x1B,0x00,0x0D,0x80,0x32,0x40,0x01,0x80},/*"%",5*/ +{0x03,0x80,0x1C,0x40,0x27,0x40,0x1C,0x80,0x07,0x40,0x00,0x40},/*"&",6*/ +{0x10,0x00,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"'",7*/ +{0x00,0x00,0x00,0x00,0x00,0x00,0x1F,0x80,0x20,0x40,0x40,0x20},/*"(",8*/ +{0x00,0x00,0x40,0x20,0x20,0x40,0x1F,0x80,0x00,0x00,0x00,0x00},/*")",9*/ +{0x09,0x00,0x06,0x00,0x1F,0x80,0x06,0x00,0x09,0x00,0x00,0x00},/*"*",10*/ +{0x04,0x00,0x04,0x00,0x3F,0x80,0x04,0x00,0x04,0x00,0x00,0x00},/*"+",11*/ +{0x00,0x10,0x00,0x60,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*",",12*/ +{0x04,0x00,0x04,0x00,0x04,0x00,0x04,0x00,0x04,0x00,0x00,0x00},/*"-",13*/ +{0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*".",14*/ +{0x00,0x20,0x01,0xC0,0x06,0x00,0x38,0x00,0x40,0x00,0x00,0x00},/*"/",15*/ +{0x1F,0x80,0x20,0x40,0x20,0x40,0x20,0x40,0x1F,0x80,0x00,0x00},/*"0",16*/ +{0x00,0x00,0x10,0x40,0x3F,0xC0,0x00,0x40,0x00,0x00,0x00,0x00},/*"1",17*/ +{0x18,0xC0,0x21,0x40,0x22,0x40,0x24,0x40,0x18,0x40,0x00,0x00},/*"2",18*/ +{0x10,0x80,0x20,0x40,0x24,0x40,0x24,0x40,0x1B,0x80,0x00,0x00},/*"3",19*/ +{0x02,0x00,0x0D,0x00,0x11,0x00,0x3F,0xC0,0x01,0x40,0x00,0x00},/*"4",20*/ +{0x3C,0x80,0x24,0x40,0x24,0x40,0x24,0x40,0x23,0x80,0x00,0x00},/*"5",21*/ +{0x1F,0x80,0x24,0x40,0x24,0x40,0x34,0x40,0x03,0x80,0x00,0x00},/*"6",22*/ +{0x30,0x00,0x20,0x00,0x27,0xC0,0x38,0x00,0x20,0x00,0x00,0x00},/*"7",23*/ +{0x1B,0x80,0x24,0x40,0x24,0x40,0x24,0x40,0x1B,0x80,0x00,0x00},/*"8",24*/ +{0x1C,0x00,0x22,0xC0,0x22,0x40,0x22,0x40,0x1F,0x80,0x00,0x00},/*"9",25*/ +{0x00,0x00,0x00,0x00,0x08,0x40,0x00,0x00,0x00,0x00,0x00,0x00},/*":",26*/ +{0x00,0x00,0x00,0x00,0x04,0x60,0x00,0x00,0x00,0x00,0x00,0x00},/*";",27*/ +{0x00,0x00,0x04,0x00,0x0A,0x00,0x11,0x00,0x20,0x80,0x40,0x40},/*"<",28*/ +{0x09,0x00,0x09,0x00,0x09,0x00,0x09,0x00,0x09,0x00,0x00,0x00},/*"=",29*/ +{0x00,0x00,0x40,0x40,0x20,0x80,0x11,0x00,0x0A,0x00,0x04,0x00},/*">",30*/ +{0x18,0x00,0x20,0x00,0x23,0x40,0x24,0x00,0x18,0x00,0x00,0x00},/*"?",31*/ +{0x1F,0x80,0x20,0x40,0x27,0x40,0x29,0x40,0x1F,0x40,0x00,0x00},/*"@",32*/ +{0x00,0x40,0x07,0xC0,0x39,0x00,0x0F,0x00,0x01,0xC0,0x00,0x40},/*"A",33*/ +{0x20,0x40,0x3F,0xC0,0x24,0x40,0x24,0x40,0x1B,0x80,0x00,0x00},/*"B",34*/ +{0x1F,0x80,0x20,0x40,0x20,0x40,0x20,0x40,0x30,0x80,0x00,0x00},/*"C",35*/ +{0x20,0x40,0x3F,0xC0,0x20,0x40,0x20,0x40,0x1F,0x80,0x00,0x00},/*"D",36*/ +{0x20,0x40,0x3F,0xC0,0x24,0x40,0x2E,0x40,0x30,0xC0,0x00,0x00},/*"E",37*/ +{0x20,0x40,0x3F,0xC0,0x24,0x40,0x2E,0x00,0x30,0x00,0x00,0x00},/*"F",38*/ +{0x0F,0x00,0x10,0x80,0x20,0x40,0x22,0x40,0x33,0x80,0x02,0x00},/*"G",39*/ +{0x20,0x40,0x3F,0xC0,0x04,0x00,0x04,0x00,0x3F,0xC0,0x20,0x40},/*"H",40*/ +{0x20,0x40,0x20,0x40,0x3F,0xC0,0x20,0x40,0x20,0x40,0x00,0x00},/*"I",41*/ +{0x00,0x60,0x20,0x20,0x20,0x20,0x3F,0xC0,0x20,0x00,0x20,0x00},/*"J",42*/ +{0x20,0x40,0x3F,0xC0,0x24,0x40,0x0B,0x00,0x30,0xC0,0x20,0x40},/*"K",43*/ +{0x20,0x40,0x3F,0xC0,0x20,0x40,0x00,0x40,0x00,0x40,0x00,0xC0},/*"L",44*/ +{0x3F,0xC0,0x3C,0x00,0x03,0xC0,0x3C,0x00,0x3F,0xC0,0x00,0x00},/*"M",45*/ +{0x20,0x40,0x3F,0xC0,0x0C,0x40,0x23,0x00,0x3F,0xC0,0x20,0x00},/*"N",46*/ +{0x1F,0x80,0x20,0x40,0x20,0x40,0x20,0x40,0x1F,0x80,0x00,0x00},/*"O",47*/ +{0x20,0x40,0x3F,0xC0,0x24,0x40,0x24,0x00,0x18,0x00,0x00,0x00},/*"P",48*/ +{0x1F,0x80,0x21,0x40,0x21,0x40,0x20,0xE0,0x1F,0xA0,0x00,0x00},/*"Q",49*/ +{0x20,0x40,0x3F,0xC0,0x24,0x40,0x26,0x00,0x19,0xC0,0x00,0x40},/*"R",50*/ +{0x18,0xC0,0x24,0x40,0x24,0x40,0x22,0x40,0x31,0x80,0x00,0x00},/*"S",51*/ +{0x30,0x00,0x20,0x40,0x3F,0xC0,0x20,0x40,0x30,0x00,0x00,0x00},/*"T",52*/ +{0x20,0x00,0x3F,0x80,0x00,0x40,0x00,0x40,0x3F,0x80,0x20,0x00},/*"U",53*/ +{0x20,0x00,0x3E,0x00,0x01,0xC0,0x07,0x00,0x38,0x00,0x20,0x00},/*"V",54*/ +{0x38,0x00,0x07,0xC0,0x3C,0x00,0x07,0xC0,0x38,0x00,0x00,0x00},/*"W",55*/ +{0x20,0x40,0x39,0xC0,0x06,0x00,0x39,0xC0,0x20,0x40,0x00,0x00},/*"X",56*/ +{0x20,0x00,0x38,0x40,0x07,0xC0,0x38,0x40,0x20,0x00,0x00,0x00},/*"Y",57*/ +{0x30,0x40,0x21,0xC0,0x26,0x40,0x38,0x40,0x20,0xC0,0x00,0x00},/*"Z",58*/ +{0x00,0x00,0x00,0x00,0x7F,0xE0,0x40,0x20,0x40,0x20,0x00,0x00},/*"[",59*/ +{0x00,0x00,0x70,0x00,0x0C,0x00,0x03,0x80,0x00,0x40,0x00,0x00},/*"\",60*/ +{0x00,0x00,0x40,0x20,0x40,0x20,0x7F,0xE0,0x00,0x00,0x00,0x00},/*"]",61*/ +{0x00,0x00,0x20,0x00,0x40,0x00,0x20,0x00,0x00,0x00,0x00,0x00},/*"^",62*/ +{0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10,0x00,0x10},/*"_",63*/ +{0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"`",64*/ +{0x00,0x00,0x02,0x80,0x05,0x40,0x05,0x40,0x03,0xC0,0x00,0x40},/*"a",65*/ +{0x20,0x00,0x3F,0xC0,0x04,0x40,0x04,0x40,0x03,0x80,0x00,0x00},/*"b",66*/ +{0x00,0x00,0x03,0x80,0x04,0x40,0x04,0x40,0x06,0x40,0x00,0x00},/*"c",67*/ +{0x00,0x00,0x03,0x80,0x04,0x40,0x24,0x40,0x3F,0xC0,0x00,0x40},/*"d",68*/ +{0x00,0x00,0x03,0x80,0x05,0x40,0x05,0x40,0x03,0x40,0x00,0x00},/*"e",69*/ +{0x00,0x00,0x04,0x40,0x1F,0xC0,0x24,0x40,0x24,0x40,0x20,0x00},/*"f",70*/ +{0x00,0x00,0x02,0xE0,0x05,0x50,0x05,0x50,0x06,0x50,0x04,0x20},/*"g",71*/ +{0x20,0x40,0x3F,0xC0,0x04,0x40,0x04,0x00,0x03,0xC0,0x00,0x40},/*"h",72*/ +{0x00,0x00,0x04,0x40,0x27,0xC0,0x00,0x40,0x00,0x00,0x00,0x00},/*"i",73*/ +{0x00,0x10,0x00,0x10,0x04,0x10,0x27,0xE0,0x00,0x00,0x00,0x00},/*"j",74*/ +{0x20,0x40,0x3F,0xC0,0x01,0x40,0x07,0x00,0x04,0xC0,0x04,0x40},/*"k",75*/ +{0x20,0x40,0x20,0x40,0x3F,0xC0,0x00,0x40,0x00,0x40,0x00,0x00},/*"l",76*/ +{0x07,0xC0,0x04,0x00,0x07,0xC0,0x04,0x00,0x03,0xC0,0x00,0x00},/*"m",77*/ +{0x04,0x40,0x07,0xC0,0x04,0x40,0x04,0x00,0x03,0xC0,0x00,0x40},/*"n",78*/ +{0x00,0x00,0x03,0x80,0x04,0x40,0x04,0x40,0x03,0x80,0x00,0x00},/*"o",79*/ +{0x04,0x10,0x07,0xF0,0x04,0x50,0x04,0x40,0x03,0x80,0x00,0x00},/*"p",80*/ +{0x00,0x00,0x03,0x80,0x04,0x40,0x04,0x50,0x07,0xF0,0x00,0x10},/*"q",81*/ +{0x04,0x40,0x07,0xC0,0x02,0x40,0x04,0x00,0x04,0x00,0x00,0x00},/*"r",82*/ +{0x00,0x00,0x06,0x40,0x05,0x40,0x05,0x40,0x04,0xC0,0x00,0x00},/*"s",83*/ +{0x00,0x00,0x04,0x00,0x1F,0x80,0x04,0x40,0x00,0x40,0x00,0x00},/*"t",84*/ +{0x04,0x00,0x07,0x80,0x00,0x40,0x04,0x40,0x07,0xC0,0x00,0x40},/*"u",85*/ +{0x04,0x00,0x07,0x00,0x04,0xC0,0x01,0x80,0x06,0x00,0x04,0x00},/*"v",86*/ +{0x06,0x00,0x01,0xC0,0x07,0x00,0x01,0xC0,0x06,0x00,0x00,0x00},/*"w",87*/ +{0x04,0x40,0x06,0xC0,0x01,0x00,0x06,0xC0,0x04,0x40,0x00,0x00},/*"x",88*/ +{0x04,0x10,0x07,0x10,0x04,0xE0,0x01,0x80,0x06,0x00,0x04,0x00},/*"y",89*/ +{0x00,0x00,0x04,0x40,0x05,0xC0,0x06,0x40,0x04,0x40,0x00,0x00},/*"z",90*/ +{0x00,0x00,0x00,0x00,0x04,0x00,0x7B,0xE0,0x40,0x20,0x00,0x00},/*"{",91*/ +{0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0xF0,0x00,0x00,0x00,0x00},/*"|",92*/ +{0x00,0x00,0x40,0x20,0x7B,0xE0,0x04,0x00,0x00,0x00,0x00,0x00},/*"}",93*/ +{0x40,0x00,0x80,0x00,0x40,0x00,0x20,0x00,0x20,0x00,0x40,0x00},/*"~",94*/ +}; + +// 你可以使用图标字库软件生成自己的pattern,软件会输出一个数组,将数组复制到这里即可. + +//the logo of robomaster +const unsigned char LOGO_BMP[128][8] = { +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1E}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD8}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD8}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD8}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x72}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7C}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7C}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1E}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDE}, +{0x40,0x00,0x00,0x00,0x00,0x00,0x00,0xFE}, +{0x60,0x00,0x00,0x00,0x00,0x10,0x00,0x6C}, +{0x70,0x00,0x00,0x00,0x00,0x30,0x00,0x00}, +{0x78,0x00,0x00,0x00,0x00,0xF0,0x00,0x7C}, +{0x7C,0x00,0x00,0x00,0x07,0xF0,0x00,0xFE}, +{0x7E,0x00,0x00,0x00,0x3F,0xF0,0x00,0xC6}, +{0x7F,0x00,0x00,0x01,0xFF,0xF0,0x00,0xC6}, +{0x7F,0x80,0x00,0x0F,0xFF,0xF0,0x00,0xC6}, +{0x7F,0xC0,0x00,0x7F,0xFF,0xF0,0x00,0xFE}, +{0x7F,0xE0,0x03,0xFF,0xFF,0xF0,0x00,0x7C}, +{0x7F,0xF0,0x3F,0xFF,0xFF,0xF0,0x00,0x02}, +{0x7F,0xF8,0x3F,0xFF,0xFF,0xF0,0x00,0x06}, +{0x7F,0xFC,0x3F,0xFF,0xFF,0xF0,0x00,0x1E}, +{0x7F,0xFE,0x3F,0xFF,0xFF,0xF0,0x00,0xBC}, +{0x7F,0xFF,0x3F,0xFF,0xFF,0xF0,0x00,0xE0}, +{0x7F,0xFF,0xBF,0xFF,0xFF,0x80,0x00,0xF8}, +{0x7F,0xFF,0xFF,0xFF,0xFC,0x00,0x00,0x3E}, +{0x7F,0xFF,0xFF,0xFF,0xE0,0x00,0x00,0x0E}, +{0x7F,0xFF,0xFF,0xFF,0x00,0x00,0x00,0xB8}, +{0x7F,0xFF,0xFF,0xF8,0x00,0x00,0x00,0xE0}, +{0x7F,0xFF,0xFF,0xF0,0x00,0x00,0x00,0xFE}, +{0x7F,0xFF,0xFF,0xF0,0x00,0x00,0x00,0x1E}, +{0x7F,0xFF,0xFF,0xF0,0x00,0x00,0x00,0x02}, +{0x7F,0xFF,0xFF,0xF0,0x00,0x00,0x00,0x00}, +{0x7F,0xEF,0xFF,0xF0,0x02,0x00,0x00,0x06}, +{0x7F,0xE7,0xFF,0xF0,0x02,0x00,0x00,0x0E}, +{0x7F,0xE3,0xFF,0xF0,0x02,0x00,0x00,0x1C}, +{0x7F,0xE1,0xFF,0xF8,0x03,0x00,0x00,0xBA}, +{0x7F,0xE0,0xFF,0xFC,0x03,0x00,0x00,0xF6}, +{0x7F,0xE0,0x7F,0xFE,0x03,0x80,0x00,0xE6}, +{0x7F,0xE0,0x3F,0xFF,0x03,0x80,0x00,0xF6}, +{0x7F,0xE0,0x3F,0xFF,0x83,0xC0,0x00,0x3E}, +{0x7F,0xE0,0x3F,0xFF,0xC3,0xC0,0x00,0x0E}, +{0x7F,0xE0,0x3F,0xFF,0xE3,0xE0,0x00,0x02}, +{0x7F,0xE0,0x3F,0xFF,0xF3,0xE0,0x00,0x00}, +{0x7F,0xE0,0x3F,0xFF,0xFB,0xF0,0x00,0x02}, +{0x7F,0xE0,0x3F,0xFF,0xFF,0xF0,0x00,0x66}, +{0x7F,0xE0,0x3F,0xFF,0xFF,0xF8,0x00,0xF6}, +{0x7F,0xE0,0x3F,0xFF,0xFF,0xF8,0x00,0xD6}, +{0x7F,0xE0,0x3F,0xFF,0xFF,0xFC,0x00,0xD6}, +{0x7F,0xF0,0x7F,0xFF,0xFF,0xFC,0x00,0xD6}, +{0x7F,0xF8,0xFF,0xF7,0xFF,0xFE,0x00,0xD6}, +{0x7F,0xFF,0xFF,0xF3,0xFF,0xFE,0x00,0xDE}, +{0x3F,0xFF,0xFF,0xE1,0xFF,0xFF,0x00,0x8C}, +{0x3F,0xFF,0xFF,0xE0,0xFF,0xCF,0x00,0x40}, +{0x1F,0xFF,0xFF,0xC0,0x7F,0xC7,0x80,0xC0}, +{0x1F,0xFF,0xFF,0xC0,0x3F,0xC3,0x80,0xC0}, +{0x0F,0xFF,0xFF,0x80,0x1F,0xC1,0xC0,0xFE}, +{0x07,0xFF,0xFF,0x00,0x0F,0xC0,0xC0,0xFE}, +{0x03,0xFF,0xFE,0x00,0x07,0xC0,0x60,0xC0}, +{0x01,0xFF,0xFC,0x00,0x03,0xC0,0x20,0xC0}, +{0x00,0x7F,0xF0,0x00,0x01,0xC0,0x00,0x86}, +{0x00,0x0F,0x80,0x00,0x00,0xC0,0x00,0x16}, +{0x00,0x00,0x00,0x00,0x00,0x40,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD0}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC0}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1E}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD8}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD8}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD8}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x72}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x62}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD6}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDE}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x8C}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, +}; + +#endif diff --git a/modules/referee/crc_ref.c b/modules/referee/crc_ref.c new file mode 100644 index 0000000..b22b6ac --- /dev/null +++ b/modules/referee/crc_ref.c @@ -0,0 +1,192 @@ +#include "crc_ref.h" +#include + + +const uint8_t CRC8_INIT = 0xff; +const uint8_t CRC8_TAB[256] = +{ + 0x00, 0x5e, 0xbc, 0xe2, 0x61, 0x3f, 0xdd, 0x83, 0xc2, 0x9c, 0x7e, 0x20, 0xa3, 0xfd, 0x1f, 0x41, + 0x9d, 0xc3, 0x21, 0x7f, 0xfc, 0xa2, 0x40, 0x1e, 0x5f, 0x01, 0xe3, 0xbd, 0x3e, 0x60, 0x82, 0xdc, + 0x23, 0x7d, 0x9f, 0xc1, 0x42, 0x1c, 0xfe, 0xa0, 0xe1, 0xbf, 0x5d, 0x03, 0x80, 0xde, 0x3c, 0x62, + 0xbe, 0xe0, 0x02, 0x5c, 0xdf, 0x81, 0x63, 0x3d, 0x7c, 0x22, 0xc0, 0x9e, 0x1d, 0x43, 0xa1, 0xff, + 0x46, 0x18, 0xfa, 0xa4, 0x27, 0x79, 0x9b, 0xc5, 0x84, 0xda, 0x38, 0x66, 0xe5, 0xbb, 0x59, 0x07, + 0xdb, 0x85, 0x67, 0x39, 0xba, 0xe4, 0x06, 0x58, 0x19, 0x47, 0xa5, 0xfb, 0x78, 0x26, 0xc4, 0x9a, + 0x65, 0x3b, 0xd9, 0x87, 0x04, 0x5a, 0xb8, 0xe6, 0xa7, 0xf9, 0x1b, 0x45, 0xc6, 0x98, 0x7a, 0x24, + 0xf8, 0xa6, 0x44, 0x1a, 0x99, 0xc7, 0x25, 0x7b, 0x3a, 0x64, 0x86, 0xd8, 0x5b, 0x05, 0xe7, 0xb9, + 0x8c, 0xd2, 0x30, 0x6e, 0xed, 0xb3, 0x51, 0x0f, 0x4e, 0x10, 0xf2, 0xac, 0x2f, 0x71, 0x93, 0xcd, + 0x11, 0x4f, 0xad, 0xf3, 0x70, 0x2e, 0xcc, 0x92, 0xd3, 0x8d, 0x6f, 0x31, 0xb2, 0xec, 0x0e, 0x50, + 0xaf, 0xf1, 0x13, 0x4d, 0xce, 0x90, 0x72, 0x2c, 0x6d, 0x33, 0xd1, 0x8f, 0x0c, 0x52, 0xb0, 0xee, + 0x32, 0x6c, 0x8e, 0xd0, 0x53, 0x0d, 0xef, 0xb1, 0xf0, 0xae, 0x4c, 0x12, 0x91, 0xcf, 0x2d, 0x73, + 0xca, 0x94, 0x76, 0x28, 0xab, 0xf5, 0x17, 0x49, 0x08, 0x56, 0xb4, 0xea, 0x69, 0x37, 0xd5, 0x8b, + 0x57, 0x09, 0xeb, 0xb5, 0x36, 0x68, 0x8a, 0xd4, 0x95, 0xcb, 0x29, 0x77, 0xf4, 0xaa, 0x48, 0x16, + 0xe9, 0xb7, 0x55, 0x0b, 0x88, 0xd6, 0x34, 0x6a, 0x2b, 0x75, 0x97, 0xc9, 0x4a, 0x14, 0xf6, 0xa8, + 0x74, 0x2a, 0xc8, 0x96, 0x15, 0x4b, 0xa9, 0xf7, 0xb6, 0xe8, 0x0a, 0x54, 0xd7, 0x89, 0x6b, 0x35, +}; + + +uint16_t CRC_INIT = 0xffff; +const uint16_t wCRC_Table[256] = +{ + 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, + 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, + 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, + 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, + 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, + 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, + 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, + 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, + 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, + 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, + 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, + 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, + 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, + 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, + 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, + 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, + 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, + 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, + 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, + 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, + 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, + 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, + 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, + 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, + 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, + 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, + 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, + 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, + 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, + 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, + 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, + 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 +}; + +// CRC8 +void Append_CRC8_Check_Sum( uint8_t *pchMessage, uint16_t dwLength); +uint32_t Verify_CRC8_Check_Sum( uint8_t *pchMessage, uint16_t dwLength); +uint8_t Get_CRC8_Check_Sum( uint8_t *pchMessage, uint16_t dwLength, uint8_t ucCRC8 ); + +// CRC16 +void Append_CRC16_Check_Sum(uint8_t * pchMessage,uint32_t dwLength); +uint32_t Verify_CRC16_Check_Sum(uint8_t *pchMessage, uint32_t dwLength); +uint16_t Get_CRC16_Check_Sum(uint8_t *pchMessage,uint32_t dwLength,uint16_t wCRC); + + + + +/* CRC校验 */ + +uint8_t Get_CRC8_Check_Sum( uint8_t *pchMessage, uint16_t dwLength, uint8_t ucCRC8 ) +{ + uint8_t ucIndex; + + while (dwLength--) + { + ucIndex = ucCRC8^(*pchMessage++); + ucCRC8 = CRC8_TAB[ucIndex]; + } + return ucCRC8; +} + + +/* +** Descriptions: CRC8 Verify function +** Input: Data to Verify,Stream length = Data + checksum +** Output: True or False (CRC Verify Result) +*/ +uint32_t Verify_CRC8_Check_Sum( uint8_t *pchMessage, uint16_t dwLength) +{ + uint8_t ucExpected = 0; + + if (pchMessage == 0 || dwLength <= 2) + { + return 0; + } + + ucExpected = Get_CRC8_Check_Sum( pchMessage, dwLength-1, CRC8_INIT); + + return ( ucExpected == pchMessage[dwLength-1] ); +} + + +/* +** Descriptions: append CRC8 to the end of data +** Input: Data to CRC and append,Stream length = Data + checksum +** Output: True or False (CRC Verify Result) +*/ +void Append_CRC8_Check_Sum( uint8_t *pchMessage, uint16_t dwLength) +{ + uint8_t ucCRC = 0; + + if (pchMessage == 0 || dwLength <= 2) + { + return; + } + + ucCRC = Get_CRC8_Check_Sum( (uint8_t *)pchMessage, dwLength-1, CRC8_INIT); + + pchMessage[dwLength-1] = ucCRC; +} + + +/* +** Descriptions: CRC16 checksum function +** Input: Data to check,Stream length, initialized checksum +** Output: CRC checksum +*/ +uint16_t Get_CRC16_Check_Sum(uint8_t *pchMessage,uint32_t dwLength,uint16_t wCRC) +{ + uint8_t chData; + if (pchMessage == NULL) + { + return 0xFFFF; + } + while(dwLength--) + { + chData = *pchMessage++; + (wCRC) = ((uint16_t)(wCRC) >> 8) ^ + wCRC_Table[((uint16_t)(wCRC) ^ (uint16_t)(chData)) & 0x00ff]; + } + return wCRC; +} + + +/* +** Descriptions: CRC16 Verify function +** Input: Data to Verify,Stream length = Data + checksum +** Output: True or False (CRC Verify Result) +*/ +uint32_t Verify_CRC16_Check_Sum(uint8_t *pchMessage, uint32_t dwLength) +{ + uint16_t wExpected = 0; + + if ((pchMessage == NULL) || (dwLength <= 2)) + { + return FALSE; + } + + wExpected = Get_CRC16_Check_Sum ( pchMessage, dwLength - 2, CRC_INIT); + return ( (wExpected & 0xff) == pchMessage[dwLength - 2] + && ((wExpected >> 8) & 0xff) == pchMessage[dwLength - 1]); +} + + +/* +** Descriptions: append CRC16 to the end of data +** Input: Data to CRC and append,Stream length = Data + checksum +** Output: True or False (CRC Verify Result) +*/ +void Append_CRC16_Check_Sum(uint8_t * pchMessage,uint32_t dwLength) +{ + uint16_t wCRC = 0; + + if ((pchMessage == NULL) || (dwLength <= 2)) + { + return; + } + + wCRC = Get_CRC16_Check_Sum ( (uint8_t *)pchMessage, dwLength-2, CRC_INIT ); + + pchMessage[dwLength-2] = (uint8_t)(wCRC & 0x00ff); + pchMessage[dwLength-1] = (uint8_t)((wCRC >> 8)& 0x00ff); +} diff --git a/modules/referee/crc_ref.h b/modules/referee/crc_ref.h new file mode 100644 index 0000000..7ad1297 --- /dev/null +++ b/modules/referee/crc_ref.h @@ -0,0 +1,20 @@ +#ifndef __CRC_H_ +#define __CRC_H_ + +// 裁判系统官方CRC校验,LUT和module/algorithms中的不同,后续需要统一实现crc,提供8/16/32的支持 + +#include + +#define TRUE 1 +#define FALSE 0 +// CRC8 +void Append_CRC8_Check_Sum(uint8_t *pchMessage, uint16_t dwLength); +uint32_t Verify_CRC8_Check_Sum(uint8_t *pchMessage, uint16_t dwLength); +uint8_t Get_CRC8_Check_Sum(uint8_t *pchMessage, uint16_t dwLength, uint8_t ucCRC8); + +// CRC16 +void Append_CRC16_Check_Sum(uint8_t *pchMessage, uint32_t dwLength); +uint32_t Verify_CRC16_Check_Sum(uint8_t *pchMessage, uint32_t dwLength); +uint16_t Get_CRC16_Check_Sum(uint8_t *pchMessage, uint32_t dwLength, uint16_t wCRC); + +#endif diff --git a/modules/referee/referee.md b/modules/referee/referee.md new file mode 100644 index 0000000..e245a7c --- /dev/null +++ b/modules/referee/referee.md @@ -0,0 +1,196 @@ +# referee + +## referee运行流程 + +首先在chassis的初始化中调用裁判系统初始化函数,将要绘制的uidata的指针传递给接口,接口会返回裁判系统的反馈数据指针。然后,在refereeUItask里进行UI初始化,确定ui发送的目标并绘制初始化UI。完成后,uitask会以10hz的频率按顺序更新UI。 + +## 如何绘制你的自定义UI?以绘制超级电容能量条为例 + +UI的绘制包含初始化和TASK两个部分,初始化部分在`MyUIInit`函数中,TASK部分在`MyUIRefresh`函数中。 + +### 初始化部分 + +初始化部分的UI主要有两个目的:静态UI的绘制、为动态UI的绘制做准备。 + +分析超级电容能量条功能可知,此UI包含如下: +Power:xxx Power为静态不变的,冒号后的xxx为变化的量。 +方框以及方框内的能量条:方框为静态不变的,能量条为变化的量。(参考游戏血条) + +因而,静态UI的绘制包含如下: +绘制字符“Power:”、绘制矩形方框。 +为动态UI的准备如下: +绘制矩形方框内的初始能量条、绘制Power的初始值。 + +### 绘制字符“Power:” + +设置绘制用结构体,此处使用数组是因为需要绘制多个字符。本次绘制的字符为“Power:”,只是用到了第6个,即xxx[5]: + +```c +static String_Data_t UI_State_sta[6]; // 静态 +``` + +字符格式以及内容设置: + +```c +UICharDraw(&UI_State_sta[5], "ss5", UI_Graph_ADD, 7, UI_Color_Green, 18, 2, 620, 230, "Power:"); + +//各参数意义如下,函数定义中有详细注释: + string String_Data类型变量指针,用于存放字符串数据 + stringname[3] 字符串名称,用于标识更改 + String_Operate 字符串操作,初始化时一般使用"UI_Graph_ADD" + String_Layer 图层0-9 + String_Color 字符串颜色 + String_Size 字号 + String_Width 字符串线宽 + Start_x、Start_y 开始坐标 + *stringdata 字符串数据 + +//设置完毕后,使用“Char_ReFresh”发送即可: +UICharRefresh(&referee_recv_info->referee_id, UI_State_sta[5]); +``` + +### 绘制能量框 + +定义一个图形类结构体,用于绘制能量框: + +```c +static Graph_Data_t UI_energy_line[3]; // 电容能量条 +``` + +能量框参数设置以及发送函数: + +```c +UIRectangleDraw(&UI_energy_line[0],"ss6", UI_Graph_ADD, 7, UI_Color_Green,20, 720, 220, 820, 240) +UIRefresh(&referee_recv_info->referee_id, 1,UI_energy_line[0]); +``` + +### 绘制power的初始值 + +```c +UIFloatDraw(&UI_Energy[1], "sd5", UI_Graph_ADD, 8, UI_Color_Green, 18, 2, 2, 750, 230, 24000); +``` + +### 绘制能量条的初始值 + +```c +UILineDraw(&UI_Energy[2], "sd6", UI_Graph_ADD, 8, UI_Color_Pink, 30, 720, 160, 1020, 160); +``` + +将两个图形打包发送 + +``` +UIRefresh(&referee_recv_info->referee_id, 2, UI_Energy[1], UI_Energy[2]); +``` + +## TASK部分 + +task中UI处于动态变化,此时需要检测所画的UI是否发生变化,若发生变化,则刷新对应UI。 + +### 添加变化检测 + +绘制功率部分UI,我们需要的是`Chassis_Power_Data_s`中的数据,我们定义`Chassis_Power_Data_s Chassis_Power_Data;`和`Chassis_Power_Data_s Chassis_last_Power_Data;`分别存储此次和上次的对应数据,本次和上次对应检测变化的需求。 + +```c +typedef struct +{ + Referee_Interactive_Flag_t Referee_Interactive_Flag; + // 为UI绘制以及交互数据所用 + chassis_mode_e chassis_mode; // 底盘模式 + gimbal_mode_e gimbal_mode; // 云台模式 + shoot_mode_e shoot_mode; // 发射模式设置 + friction_mode_e friction_mode; // 摩擦轮关闭 + lid_mode_e lid_mode; // 弹舱盖打开 + Chassis_Power_Data_s Chassis_Power_Data; // 功率控制 + + // 上一次的模式,用于flag判断 + chassis_mode_e chassis_last_mode; + gimbal_mode_e gimbal_last_mode; + shoot_mode_e shoot_last_mode; + friction_mode_e friction_last_mode; + lid_mode_e lid_last_mode; + Chassis_Power_Data_s Chassis_last_Power_Data; + +} Referee_Interactive_info_t; +``` + +添加功率变化标志位,`uint32_t Power_flag : 1;`,1为检测到变化,0为未检测到变换 + +``` +typedef struct +{ + uint32_t chassis_flag : 1; + uint32_t gimbal_flag : 1; + uint32_t shoot_flag : 1; + uint32_t lid_flag : 1; + uint32_t friction_flag : 1; + uint32_t Power_flag : 1; +} Referee_Interactive_Flag_t; +``` + +在变化检测函数中增加对应判断,由于voltage和能量条的变化对应同一个参数`Chassis_last_Power_Data.chassis_power_mx`的变化,所以只需要一个参数即可: + +``` +static void UIChangeCheck(Referee_Interactive_info_t *_Interactive_data) +{ + if (_Interactive_data->chassis_mode != _Interactive_data->chassis_last_mode) + ...... + ...... + if (_Interactive_data->lid_mode != _Interactive_data->lid_last_mode) + { + _Interactive_data->Referee_Interactive_Flag.lid_flag = 1; + _Interactive_data->lid_last_mode = _Interactive_data->lid_mode; + } + + if (_Interactive_data->Chassis_Power_Data.chassis_power_mx != _Interactive_data->Chassis_last_Power_Data.chassis_power_mx) + { + _Interactive_data->Referee_Interactive_Flag.Power_flag = 1; + _Interactive_data->Chassis_last_Power_Data.chassis_power_mx = _Interactive_data->Chassis_Power_Data.chassis_power_mx; + } +} +``` + +### 根据功率的变化绘制UI + +在绘制变化的UI时,由于初始化时已经使用`UI_Graph_ADD`操作添加了UI,所以在绘制时,需要使用`UI_Graph_Change`操作,以便于刷新UI。 + +同时,完成UI刷新后,需要将对应的flag置0,以便于下次检测变化 + +``` +if (_Interactive_data->Referee_Interactive_Flag.Power_flag == 1) +{ + UIFloatDraw(&UI_Energy[1], "sd5", UI_Graph_Change, 8, UI_Color_Green, 18, 2, 2, 750, 230, _Interactive_data->Chassis_Power_Data.chassis_power_mx * 1000); + UILineDraw(&UI_Energy[2], "sd6", UI_Graph_Change, 8, UI_Color_Pink, 30, 720, 160, (uint32_t)750 + _Interactive_data->Chassis_Power_Data.chassis_power_mx * 30, 160); + UIRefresh(&referee_recv_info->referee_id, 2, UI_Energy[1], UI_Energy[2]); + _Interactive_data->Referee_Interactive_Flag.Power_flag = 0; +} +``` + +--- + +若需要进行多机交互,可增加此函数: + +```c +void CommBetweenRobotSend(referee_id_t *_id, robot_interactive_data_t *_data) +{ + Communicate_SendData_t SendData; + uint8_t temp_datalength = Interactive_Data_LEN_Head + Communicate_Data_LEN; // 计算交互数据长度 6+n,n为交互数据长度 + + SendData.FrameHeader.SOF = REFEREE_SOF; + SendData.FrameHeader.DataLength = temp_datalength; + SendData.FrameHeader.Seq = UI_Seq; + SendData.FrameHeader.CRC8 = Get_CRC8_Check_Sum((uint8_t *)&SendData, LEN_CRC8, 0xFF); + + SendData.CmdID = ID_student_interactive; + + SendData.datahead.data_cmd_id = Communicate_Data_ID; + SendData.datahead.sender_ID = _id->Robot_ID; + SendData.datahead.receiver_ID = _id->Receiver_Robot_ID; + + SendData.Data = *_data; + + SendData.frametail = Get_CRC16_Check_Sum((uint8_t *)&SendData, LEN_HEADER + LEN_CMDID + temp_datalength, 0xFFFF); + + RefereeSend((uint8_t *)&SendData, LEN_HEADER + LEN_CMDID + temp_datalength + LEN_TAIL); // 发送 + UI_Seq++; // 包序号+1 +} +``` diff --git a/modules/referee/referee_UI.c b/modules/referee/referee_UI.c new file mode 100644 index 0000000..55ce3c6 --- /dev/null +++ b/modules/referee/referee_UI.c @@ -0,0 +1,424 @@ +/** + * @file referee_UI.C + * @author kidneygood (you@domain.com) + * @brief + * @version 0.1 + * @date 2023-1-18 + * + * @copyright Copyright (c) 2022 + * + */ +#include "referee_UI.h" +#include "string.h" +#include "crc_ref.h" +#include "stdio.h" +#include "rm_referee.h" + +// 包序号 +/********************************************删除操作************************************* +**参数:_id 对应的id结构体 + Del_Operate 对应头文件删除操作 + Del_Layer 要删除的层 取值0-9 +*****************************************************************************************/ +void UIDelete(referee_id_t *_id, uint8_t Del_Operate, uint8_t Del_Layer) +{ + static UI_delete_t UI_delete_data; + uint8_t temp_datalength = Interactive_Data_LEN_Head + UI_Operate_LEN_Del; // 计算交互数据长度 + + UI_delete_data.FrameHeader.SOF = REFEREE_SOF; + UI_delete_data.FrameHeader.DataLength = temp_datalength; + UI_delete_data.FrameHeader.Seq = UI_Seq; + UI_delete_data.FrameHeader.CRC8 = Get_CRC8_Check_Sum((uint8_t *)&UI_delete_data, LEN_CRC8, 0xFF); + + UI_delete_data.CmdID = ID_student_interactive; + + UI_delete_data.datahead.data_cmd_id = UI_Data_ID_Del; + UI_delete_data.datahead.receiver_ID = _id->Cilent_ID; + UI_delete_data.datahead.sender_ID = _id->Robot_ID; + + UI_delete_data.Delete_Operate = Del_Operate; // 删除操作 + UI_delete_data.Layer = Del_Layer; + + UI_delete_data.frametail = Get_CRC16_Check_Sum((uint8_t *)&UI_delete_data, LEN_HEADER + LEN_CMDID + temp_datalength, 0xFFFF); + /* 填入0xFFFF,关于crc校验 */ + + RefereeSend((uint8_t *)&UI_delete_data, LEN_HEADER + LEN_CMDID + temp_datalength + LEN_TAIL); // 发送 + + UI_Seq++; // 包序号+1 +} +/************************************************绘制直线************************************************* +**参数:*graph Graph_Data类型变量指针,用于存放图形数据 + graphname[3] 图片名称,用于标识更改 + Graph_Operate 图片操作,见头文件 + Graph_Layer 图层0-9 + Graph_Color 图形颜色 + Graph_Width 图形线宽 + Start_x、Start_y 起点xy坐标 + End_x、End_y 终点xy坐标 +**********************************************************************************************************/ + +void UILineDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, uint32_t End_x, uint32_t End_y) +{ + int i; + for (i = 0; i < 3 && graphname[i] != '\0'; i++) // 填充至‘0’为止 + { + graph->graphic_name[2 - i] = graphname[i]; // 按内存地址增大方向填充,所以会有i与2-i + } + + graph->operate_tpye = Graph_Operate; + graph->graphic_tpye = UI_Graph_Line; + graph->layer = Graph_Layer; + graph->color = Graph_Color; + + graph->start_angle = 0; + graph->end_angle = 0; + graph->width = Graph_Width; + graph->start_x = Start_x; + graph->start_y = Start_y; + graph->radius = 0; + graph->end_x = End_x; + graph->end_y = End_y; +} + +/************************************************绘制矩形************************************************* +**参数:*graph Graph_Data类型变量指针,用于存放图形数据 + graphname[3] 图片名称,用于标识更改 + Graph_Operate 图片操作,见头文件 + Graph_Layer 图层0-9 + Graph_Color 图形颜色 + Graph_Width 图形线宽 + Start_x、Start_y 起点xy坐标 + End_x、End_y 对角顶点xy坐标 +**********************************************************************************************************/ +void UIRectangleDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, uint32_t End_x, uint32_t End_y) +{ + int i; + for (i = 0; i < 3 && graphname[i] != '\0'; i++) + { + graph->graphic_name[2 - i] = graphname[i]; + } + + graph->graphic_tpye = UI_Graph_Rectangle; + graph->operate_tpye = Graph_Operate; + graph->layer = Graph_Layer; + graph->color = Graph_Color; + + graph->start_angle = 0; + graph->end_angle = 0; + graph->width = Graph_Width; + graph->start_x = Start_x; + graph->start_y = Start_y; + graph->radius = 0; + graph->end_x = End_x; + graph->end_y = End_y; +} + +/************************************************绘制整圆************************************************* +**参数:*graph Graph_Data类型变量指针,用于存放图形数据 + graphname[3] 图片名称,用于标识更改 + Graph_Operate 图片操作,见头文件 + Graph_Layer 图层0-9 + Graph_Color 图形颜色 + Graph_Width 图形线宽 + Start_x、Start_y 圆心xy坐标 + Graph_Radius 圆形半径 +**********************************************************************************************************/ + +void UICircleDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, uint32_t Graph_Radius) +{ + int i; + for (i = 0; i < 3 && graphname[i] != '\0'; i++) + { + graph->graphic_name[2 - i] = graphname[i]; + } + + graph->graphic_tpye = UI_Graph_Circle; + graph->operate_tpye = Graph_Operate; + graph->layer = Graph_Layer; + graph->color = Graph_Color; + + graph->start_angle = 0; + graph->end_angle = 0; + graph->width = Graph_Width; + graph->start_x = Start_x; + graph->start_y = Start_y; + graph->radius = Graph_Radius; + graph->end_x = 0; + graph->end_y = 0; +} +/************************************************绘制椭圆************************************************* +**参数:*graph Graph_Data类型变量指针,用于存放图形数据 + graphname[3] 图片名称,用于标识更改 + Graph_Operate 图片操作,见头文件 + Graph_Layer 图层0-9 + Graph_Color 图形颜色 + Graph_Width 图形线宽 + Start_x、Start_y 圆心xy坐标 + End_x、End_y xy半轴长度 +**********************************************************************************************************/ +void UIOvalDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, uint32_t end_x, uint32_t end_y) +{ + int i; + for (i = 0; i < 3 && graphname[i] != '\0'; i++) + { + graph->graphic_name[2 - i] = graphname[i]; + } + + graph->graphic_tpye = UI_Graph_Ellipse; + graph->operate_tpye = Graph_Operate; + graph->layer = Graph_Layer; + graph->color = Graph_Color; + graph->width = Graph_Width; + + graph->start_angle = 0; + graph->end_angle = 0; + graph->width = Graph_Width; + graph->start_x = Start_x; + graph->start_y = Start_y; + graph->radius = 0; + graph->end_x = end_x; + graph->end_y = end_y; +} + +/************************************************绘制圆弧************************************************* +**参数:*graph Graph_Data类型变量指针,用于存放图形数据 + graphname[3] 图片名称,用于标识更改 + Graph_Operate 图片操作,见头文件 + Graph_Layer 图层0-9 + Graph_Color 图形颜色 + Graph_StartAngle,Graph_EndAngle 起始终止角度 + Graph_Width 图形线宽 + Start_y,Start_y 圆心xy坐标 + x_Length,y_Length xy半轴长度 +**********************************************************************************************************/ + +void UIArcDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_StartAngle, uint32_t Graph_EndAngle, uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, + uint32_t end_x, uint32_t end_y) +{ + int i; + for (i = 0; i < 3 && graphname[i] != '\0'; i++) + { + graph->graphic_name[2 - i] = graphname[i]; + } + + graph->graphic_tpye = UI_Graph_Arc; + graph->operate_tpye = Graph_Operate; + graph->layer = Graph_Layer; + graph->color = Graph_Color; + + graph->start_angle = Graph_StartAngle; + graph->end_angle = Graph_EndAngle; + graph->width = Graph_Width; + graph->start_x = Start_x; + graph->start_y = Start_y; + graph->radius = 0; + graph->end_x = end_x; + graph->end_y = end_y; +} + +/************************************************绘制浮点型数据************************************************* +**参数:*graph Graph_Data类型变量指针,用于存放图形数据 + graphname[3] 图片名称,用于标识更改 + Graph_Operate 图片操作,见头文件 + Graph_Layer 图层0-9 + Graph_Color 图形颜色 + Graph_Size 字号 + Graph_Digit 小数位数 + Graph_Width 图形线宽 + Start_x、Start_y 开始坐标 + radius=a&0x3FF; a为浮点数乘以1000后的32位整型数 + end_x=(a>>10)&0x7FF; + end_y=(a>>21)&0x7FF; +**********************************************************************************************************/ + +void UIFloatDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Size, uint32_t Graph_Digit, uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, int32_t Graph_Float) +{ + + int i; + for (i = 0; i < 3 && graphname[i] != '\0'; i++) + { + graph->graphic_name[2 - i] = graphname[i]; + } + graph->graphic_tpye = UI_Graph_Float; + graph->operate_tpye = Graph_Operate; + graph->layer = Graph_Layer; + graph->color = Graph_Color; + + graph->width = Graph_Width; + graph->start_x = Start_x; + graph->start_y = Start_y; + graph->start_angle = Graph_Size; + graph->end_angle = Graph_Digit; + + graph->radius = Graph_Float & 0x3FF; + graph->end_x = (Graph_Float >> 10) & 0x7FF; + graph->end_y = (Graph_Float >> 21) & 0x7FF; +} + +/************************************************绘制整型数据************************************************* +**参数:*graph Graph_Data类型变量指针,用于存放图形数据 + graphname[3] 图片名称,用于标识更改 + Graph_Operate 图片操作,见头文件 + Graph_Layer 图层0-9 + Graph_Color 图形颜色 + Graph_Size 字号 + Graph_Width 图形线宽 + Start_x、Start_y 开始坐标 + radius=a&0x3FF; a为32位整型数 + end_x=(a>>10)&0x7FF; + end_y=(a>>21)&0x7FF; +**********************************************************************************************************/ +void UIIntDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Size, uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, int32_t Graph_Integer) +{ + int i; + for (i = 0; i < 3 && graphname[i] != '\0'; i++) + { + graph->graphic_name[2 - i] = graphname[i]; + } + graph->graphic_tpye = UI_Graph_Int; + graph->operate_tpye = Graph_Operate; + graph->layer = Graph_Layer; + graph->color = Graph_Color; + + graph->start_angle = Graph_Size; + graph->end_angle = 0; + graph->width = Graph_Width; + graph->start_x = Start_x; + graph->start_y = Start_y; + graph->radius = Graph_Integer & 0x3FF; + graph->end_x = (Graph_Integer >> 10) & 0x7FF; + graph->end_y = (Graph_Integer >> 21) & 0x7FF; +} + +/************************************************绘制字符型数据************************************************* +**参数:*graph Graph_Data类型变量指针,用于存放图形数据 + graphname[3] 图片名称,用于标识更改 + Graph_Operate 图片操作,见头文件 + Graph_Layer 图层0-9 + Graph_Color 图形颜色 + Graph_Size 字号 + Graph_Width 图形线宽 + Start_x、Start_y 开始坐标 + +**参数:*graph Graph_Data类型变量指针,用于存放图形数据 + fmt需要显示的字符串 + 此函数的实现和具体使用类似于printf函数 +**********************************************************************************************************/ +void UICharDraw(String_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Size, uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, char *fmt, ...) +{ + int i; + for (i = 0; i < 3 && graphname[i] != '\0'; i++) + { + graph->Graph_Control.graphic_name[2 - i] = graphname[i]; + } + + graph->Graph_Control.graphic_tpye = UI_Graph_Char; + graph->Graph_Control.operate_tpye = Graph_Operate; + graph->Graph_Control.layer = Graph_Layer; + graph->Graph_Control.color = Graph_Color; + + graph->Graph_Control.width = Graph_Width; + graph->Graph_Control.start_x = Start_x; + graph->Graph_Control.start_y = Start_y; + graph->Graph_Control.start_angle = Graph_Size; + graph->Graph_Control.radius = 0; + graph->Graph_Control.end_x = 0; + graph->Graph_Control.end_y = 0; + + va_list ap; + va_start(ap, fmt); + vsprintf((char *)graph->show_Data, fmt, ap); // 使用参数列表进行格式化并输出到字符串 + va_end(ap); + graph->Graph_Control.end_angle = strlen((const char *)graph->show_Data); +} + +/* UI推送函数(使更改生效) + 参数: cnt 图形个数 + ... 图形变量参数 + Tips::该函数只能推送1,2,5,7个图形,其他数目协议未涉及 + */ +void UIGraphRefresh(referee_id_t *_id, int cnt, ...) +{ + UI_GraphReFresh_t UI_GraphReFresh_data; + Graph_Data_t graphData; + + uint8_t temp_datalength = LEN_HEADER + LEN_CMDID + Interactive_Data_LEN_Head + UI_Operate_LEN_PerDraw * cnt + LEN_TAIL; // 计算交互数据长度 + + static uint8_t buffer[512]; // 交互数据缓存 + + va_list ap; // 创建一个 va_list 类型变量 + va_start(ap, cnt); // 初始化 va_list 变量为一个参数列表 + + UI_GraphReFresh_data.FrameHeader.SOF = REFEREE_SOF; + UI_GraphReFresh_data.FrameHeader.DataLength = Interactive_Data_LEN_Head + cnt * UI_Operate_LEN_PerDraw; + UI_GraphReFresh_data.FrameHeader.Seq = UI_Seq; + UI_GraphReFresh_data.FrameHeader.CRC8 = Get_CRC8_Check_Sum((uint8_t *)&UI_GraphReFresh_data, LEN_CRC8, 0xFF); + + UI_GraphReFresh_data.CmdID = ID_student_interactive; + + switch (cnt) + { + case 1: + UI_GraphReFresh_data.datahead.data_cmd_id = UI_Data_ID_Draw1; + break; + case 2: + UI_GraphReFresh_data.datahead.data_cmd_id = UI_Data_ID_Draw2; + break; + case 5: + UI_GraphReFresh_data.datahead.data_cmd_id = UI_Data_ID_Draw5; + break; + case 7: + UI_GraphReFresh_data.datahead.data_cmd_id = UI_Data_ID_Draw7; + break; + } + + UI_GraphReFresh_data.datahead.receiver_ID = _id->Cilent_ID; + UI_GraphReFresh_data.datahead.sender_ID = _id->Robot_ID; + memcpy(buffer, (uint8_t *)&UI_GraphReFresh_data, LEN_HEADER + LEN_CMDID + Interactive_Data_LEN_Head); // 将帧头、命令码、交互数据帧头三部分复制到缓存中 + + for (uint8_t i = 0; i < cnt; i++) // 发送交互数据的数据帧,并计算CRC16校验值 + { + graphData = va_arg(ap, Graph_Data_t); // 访问参数列表中的每个项,第二个参数是你要返回的参数的类型,在取值时需要将其强制转化为指定类型的变量 + memcpy(buffer + (LEN_HEADER + LEN_CMDID + Interactive_Data_LEN_Head + UI_Operate_LEN_PerDraw * i), (uint8_t *)&graphData, UI_Operate_LEN_PerDraw); + } + Append_CRC16_Check_Sum(buffer, temp_datalength); + RefereeSend(buffer, temp_datalength); + + va_end(ap); // 结束可变参数的获取 +} + +/************************************************UI推送字符(使更改生效)*********************************/ +void UICharRefresh(referee_id_t *_id, String_Data_t string_Data) +{ + static UI_CharReFresh_t UI_CharReFresh_data; + + uint8_t temp_datalength = Interactive_Data_LEN_Head + UI_Operate_LEN_DrawChar; // 计算交互数据长度 + + UI_CharReFresh_data.FrameHeader.SOF = REFEREE_SOF; + UI_CharReFresh_data.FrameHeader.DataLength = temp_datalength; + UI_CharReFresh_data.FrameHeader.Seq = UI_Seq; + UI_CharReFresh_data.FrameHeader.CRC8 = Get_CRC8_Check_Sum((uint8_t *)&UI_CharReFresh_data, LEN_CRC8, 0xFF); + + UI_CharReFresh_data.CmdID = ID_student_interactive; + + UI_CharReFresh_data.datahead.data_cmd_id = UI_Data_ID_DrawChar; + + UI_CharReFresh_data.datahead.receiver_ID = _id->Cilent_ID; + UI_CharReFresh_data.datahead.sender_ID = _id->Robot_ID; + + UI_CharReFresh_data.String_Data = string_Data; + + UI_CharReFresh_data.frametail = Get_CRC16_Check_Sum((uint8_t *)&UI_CharReFresh_data, LEN_HEADER + LEN_CMDID + temp_datalength, 0xFFFF); + + RefereeSend((uint8_t *)&UI_CharReFresh_data, LEN_HEADER + LEN_CMDID + temp_datalength + LEN_TAIL); // 发送 + + UI_Seq++; // 包序号+1 +} diff --git a/modules/referee/referee_UI.h b/modules/referee/referee_UI.h new file mode 100644 index 0000000..4fba98b --- /dev/null +++ b/modules/referee/referee_UI.h @@ -0,0 +1,72 @@ +#ifndef REFEREE_UI_H +#define REFEREE_UI_H + +#include "stdarg.h" +#include "stdint.h" +#include "referee_protocol.h" +#include "rm_referee.h" + +#pragma pack(1) // 按1字节对齐 + +/* 此处的定义只与UI绘制有关 */ +typedef struct +{ + xFrameHeader FrameHeader; + uint16_t CmdID; + ext_student_interactive_header_data_t datahead; + uint8_t Delete_Operate; // 删除操作 + uint8_t Layer; + uint16_t frametail; +} UI_delete_t; + +typedef struct +{ + xFrameHeader FrameHeader; + uint16_t CmdID; + ext_student_interactive_header_data_t datahead; + uint16_t frametail; +} UI_GraphReFresh_t; + +typedef struct +{ + xFrameHeader FrameHeader; + uint16_t CmdID; + ext_student_interactive_header_data_t datahead; + String_Data_t String_Data; + uint16_t frametail; +} UI_CharReFresh_t; // 打印字符串数据 + +#pragma pack() + +void UIDelete(referee_id_t *_id, uint8_t Del_Operate, uint8_t Del_Layer); + +void UILineDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, uint32_t End_x, uint32_t End_y); + +void UIRectangleDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, uint32_t End_x, uint32_t End_y); + +void UICircleDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, uint32_t Graph_Radius); + +void UIOvalDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, uint32_t end_x, uint32_t end_y); + +void UIArcDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_StartAngle, uint32_t Graph_EndAngle, uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, + uint32_t end_x, uint32_t end_y); + +void UIFloatDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Size, uint32_t Graph_Digit, uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, int32_t Graph_Float); + +void UIIntDraw(Graph_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Size, uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, int32_t Graph_Integer); + +void UICharDraw(String_Data_t *graph, char graphname[3], uint32_t Graph_Operate, uint32_t Graph_Layer, uint32_t Graph_Color, + uint32_t Graph_Size, uint32_t Graph_Width, uint32_t Start_x, uint32_t Start_y, char *fmt, ...); + +void UIGraphRefresh(referee_id_t *_id, int cnt, ...); + +void UICharRefresh(referee_id_t *_id, String_Data_t string_Data); + +#endif diff --git a/modules/referee/referee_protocol.h b/modules/referee/referee_protocol.h new file mode 100644 index 0000000..22416b3 --- /dev/null +++ b/modules/referee/referee_protocol.h @@ -0,0 +1,392 @@ +/** + * @file referee_protocol.h + * @author kidneygood (you@domain.com) + * @version 0.1 + * @date 2022-12-02 + * + * @copyright Copyright (c) HNU YueLu EC 2022 all rights reserved + * + */ + +#ifndef referee_protocol_H +#define referee_protocol_H + +#include "stdint.h" + +/****************************宏定义部分****************************/ + +#define REFEREE_SOF 0xA5 // 起始字节,协议固定为0xA5 +#define Robot_Red 0 +#define Robot_Blue 1 +#define Communicate_Data_LEN 5 // 自定义交互数据长度,该长度决定了我方发送和他方接收,自定义交互数据协议更改时只需要更改此宏定义即可 + +#pragma pack(1) + +/****************************通信协议格式****************************/ + +/* 通信协议格式偏移,枚举类型,代替#define声明 */ +typedef enum +{ + FRAME_HEADER_Offset = 0, + CMD_ID_Offset = 5, + DATA_Offset = 7, +} JudgeFrameOffset_e; + +/* 通信协议长度 */ +typedef enum +{ + LEN_HEADER = 5, // 帧头长 + LEN_CMDID = 2, // 命令码长度 + LEN_TAIL = 2, // 帧尾CRC16 + + LEN_CRC8 = 4, // 帧头CRC8校验长度=帧头+数据长+包序号 +} JudgeFrameLength_e; + +/****************************帧头****************************/ +/****************************帧头****************************/ + +/* 帧头偏移 */ +typedef enum +{ + SOF = 0, // 起始位 + DATA_LENGTH = 1, // 帧内数据长度,根据这个来获取数据长度 + SEQ = 3, // 包序号 + CRC8 = 4 // CRC8 +} FrameHeaderOffset_e; + +/* 帧头定义 */ +typedef struct +{ + uint8_t SOF; + uint16_t DataLength; + uint8_t Seq; + uint8_t CRC8; +} xFrameHeader; + +/****************************cmd_id命令码说明****************************/ +/****************************cmd_id命令码说明****************************/ + +/* 命令码ID,用来判断接收的是什么数据 */ +typedef enum +{ + ID_game_state = 0x0001, // 比赛状态数据 + ID_game_result = 0x0002, // 比赛结果数据 + ID_game_robot_survivors = 0x0003, // 比赛机器人血量数据 + ID_event_data = 0x0101, // 场地事件数据 + ID_supply_projectile_action = 0x0102, // 场地补给站动作标识数据 + ID_supply_projectile_booking = 0x0103, // 场地补给站预约子弹数据 + ID_game_robot_state = 0x0201, // 机器人状态数据 + ID_power_heat_data = 0x0202, // 实时功率热量数据 + ID_game_robot_pos = 0x0203, // 机器人位置数据 + ID_buff_musk = 0x0204, // 机器人增益数据 + ID_aerial_robot_energy = 0x0205, // 空中机器人能量状态数据 + ID_robot_hurt = 0x0206, // 伤害状态数据 + ID_shoot_data = 0x0207, // 实时射击数据 + ID_student_interactive = 0x0301, // 机器人间交互数据 +} CmdID_e; + +/* 命令码数据段长,根据官方协议来定义长度,还有自定义数据长度 */ +typedef enum +{ + LEN_game_state = 3, // 0x0001 + LEN_game_result = 1, // 0x0002 + LEN_game_robot_HP = 2, // 0x0003 + LEN_event_data = 4, // 0x0101 + LEN_supply_projectile_action = 4, // 0x0102 + LEN_game_robot_state = 27, // 0x0201 + LEN_power_heat_data = 14, // 0x0202 + LEN_game_robot_pos = 16, // 0x0203 + LEN_buff_musk = 1, // 0x0204 + LEN_aerial_robot_energy = 1, // 0x0205 + LEN_robot_hurt = 1, // 0x0206 + LEN_shoot_data = 7, // 0x0207 + LEN_receive_data = 6 + Communicate_Data_LEN, // 0x0301 + +} JudgeDataLength_e; + +/****************************接收数据的详细说明****************************/ +/****************************接收数据的详细说明****************************/ + +/* ID: 0x0001 Byte: 3 比赛状态数据 */ +typedef struct +{ + uint8_t game_type : 4; + uint8_t game_progress : 4; + uint16_t stage_remain_time; +} ext_game_state_t; + +/* ID: 0x0002 Byte: 1 比赛结果数据 */ +typedef struct +{ + uint8_t winner; +} ext_game_result_t; + +/* ID: 0x0003 Byte: 32 比赛机器人血量数据 */ +typedef struct +{ + uint16_t red_1_robot_HP; + uint16_t red_2_robot_HP; + uint16_t red_3_robot_HP; + uint16_t red_4_robot_HP; + uint16_t red_5_robot_HP; + uint16_t red_7_robot_HP; + uint16_t red_outpost_HP; + uint16_t red_base_HP; + uint16_t blue_1_robot_HP; + uint16_t blue_2_robot_HP; + uint16_t blue_3_robot_HP; + uint16_t blue_4_robot_HP; + uint16_t blue_5_robot_HP; + uint16_t blue_7_robot_HP; + uint16_t blue_outpost_HP; + uint16_t blue_base_HP; +} ext_game_robot_HP_t; + +/* ID: 0x0101 Byte: 4 场地事件数据 */ +typedef struct +{ + uint32_t event_type; +} ext_event_data_t; + +/* ID: 0x0102 Byte: 3 场地补给站动作标识数据 */ +typedef struct +{ + uint8_t supply_projectile_id; + uint8_t supply_robot_id; + uint8_t supply_projectile_step; + uint8_t supply_projectile_num; +} ext_supply_projectile_action_t; + +/* ID: 0X0201 Byte: 27 机器人状态数据 */ +typedef struct +{ + uint8_t robot_id; + uint8_t robot_level; + uint16_t remain_HP; + uint16_t max_HP; + uint16_t shooter_id1_17mm_cooling_rate; + uint16_t shooter_id1_17mm_cooling_limit; + uint16_t shooter_id1_17mm_speed_limit; + uint16_t shooter_id2_17mm_cooling_rate; + uint16_t shooter_id2_17mm_cooling_limit; + uint16_t shooter_id2_17mm_speed_limit; + uint16_t shooter_id1_42mm_cooling_rate; + uint16_t shooter_id1_42mm_cooling_limit; + uint16_t shooter_id1_42mm_speed_limit; + uint16_t chassis_power_limit; + uint8_t mains_power_gimbal_output : 1; + uint8_t mains_power_chassis_output : 1; + uint8_t mains_power_shooter_output : 1; +} ext_game_robot_state_t; + +/* ID: 0X0202 Byte: 14 实时功率热量数据 */ +typedef struct +{ + uint16_t chassis_volt; + uint16_t chassis_current; + float chassis_power; // 瞬时功率 + uint16_t chassis_power_buffer; // 60焦耳缓冲能量 + uint16_t shooter_heat0; // 17mm + uint16_t shooter_heat1; +} ext_power_heat_data_t; + +/* ID: 0x0203 Byte: 16 机器人位置数据 */ +typedef struct +{ + float x; + float y; + float z; + float yaw; +} ext_game_robot_pos_t; + +/* ID: 0x0204 Byte: 1 机器人增益数据 */ +typedef struct +{ + uint8_t power_rune_buff; +} ext_buff_musk_t; + +/* ID: 0x0205 Byte: 1 空中机器人能量状态数据 */ +typedef struct +{ + uint8_t attack_time; +} aerial_robot_energy_t; + +/* ID: 0x0206 Byte: 1 伤害状态数据 */ +typedef struct +{ + uint8_t armor_id : 4; + uint8_t hurt_type : 4; +} ext_robot_hurt_t; + +/* ID: 0x0207 Byte: 7 实时射击数据 */ +typedef struct +{ + uint8_t bullet_type; + uint8_t shooter_id; + uint8_t bullet_freq; + float bullet_speed; +} ext_shoot_data_t; + +/****************************机器人交互数据****************************/ +/****************************机器人交互数据****************************/ +/* 发送的内容数据段最大为 113 检测是否超出大小限制?实际上图形段不会超,数据段最多30个,也不会超*/ +/* 交互数据头结构 */ +typedef struct +{ + uint16_t data_cmd_id; // 由于存在多个内容 ID,但整个cmd_id 上行频率最大为 10Hz,请合理安排带宽。注意交互部分的上行频率 + uint16_t sender_ID; + uint16_t receiver_ID; +} ext_student_interactive_header_data_t; + +/* 机器人id */ +typedef enum +{ + // 红方机器人ID + RobotID_RHero = 1, + RobotID_REngineer = 2, + RobotID_RStandard1 = 3, + RobotID_RStandard2 = 4, + RobotID_RStandard3 = 5, + RobotID_RAerial = 6, + RobotID_RSentry = 7, + RobotID_RRadar = 9, + // 蓝方机器人ID + RobotID_BHero = 101, + RobotID_BEngineer = 102, + RobotID_BStandard1 = 103, + RobotID_BStandard2 = 104, + RobotID_BStandard3 = 105, + RobotID_BAerial = 106, + RobotID_BSentry = 107, + RobotID_BRadar = 109, +} Robot_ID_e; + +/* 交互数据ID */ +typedef enum +{ + UI_Data_ID_Del = 0x100, + UI_Data_ID_Draw1 = 0x101, + UI_Data_ID_Draw2 = 0x102, + UI_Data_ID_Draw5 = 0x103, + UI_Data_ID_Draw7 = 0x104, + UI_Data_ID_DrawChar = 0x110, + + /* 自定义交互数据部分 */ + Communicate_Data_ID = 0x0200, + +} Interactive_Data_ID_e; +/* 交互数据长度 */ +typedef enum +{ + Interactive_Data_LEN_Head = 6, + UI_Operate_LEN_Del = 2, + UI_Operate_LEN_PerDraw = 15, + UI_Operate_LEN_DrawChar = 15 + 30, + + /* 自定义交互数据部分 */ + // Communicate_Data_LEN = 5, + +} Interactive_Data_Length_e; + +/****************************自定义交互数据****************************/ +/* + 学生机器人间通信 cmd_id 0x0301,内容 ID:0x0200~0x02FF + 自定义交互数据 机器人间通信:0x0301。 + 发送频率:上限 10Hz +*/ +// 自定义交互数据协议,可更改,更改后需要修改最上方宏定义数据长度的值 +typedef struct +{ + uint8_t data[Communicate_Data_LEN]; // 数据段,n需要小于113 +} robot_interactive_data_t; + +// 机器人交互信息_发送 +typedef struct +{ + xFrameHeader FrameHeader; + uint16_t CmdID; + ext_student_interactive_header_data_t datahead; + robot_interactive_data_t Data; // 数据段 + uint16_t frametail; +} Communicate_SendData_t; +// 机器人交互信息_接收 +typedef struct +{ + ext_student_interactive_header_data_t datahead; + robot_interactive_data_t Data; // 数据段 +} Communicate_ReceiveData_t; + +/****************************UI交互数据****************************/ + +/* 图形数据 */ +typedef struct +{ + uint8_t graphic_name[3]; + uint32_t operate_tpye : 3; + uint32_t graphic_tpye : 3; + uint32_t layer : 4; + uint32_t color : 4; + uint32_t start_angle : 9; + uint32_t end_angle : 9; + uint32_t width : 10; + uint32_t start_x : 11; + uint32_t start_y : 11; + uint32_t radius : 10; + uint32_t end_x : 11; + uint32_t end_y : 11; +} Graph_Data_t; + +typedef struct +{ + Graph_Data_t Graph_Control; + uint8_t show_Data[30]; +} String_Data_t; // 打印字符串数据 + +/* 删除操作 */ +typedef enum +{ + UI_Data_Del_NoOperate = 0, + UI_Data_Del_Layer = 1, + UI_Data_Del_ALL = 2, // 删除全部图层,后面的参数已经不重要了。 +} UI_Delete_Operate_e; + +/* 图形配置参数__图形操作 */ +typedef enum +{ + UI_Graph_ADD = 1, + UI_Graph_Change = 2, + UI_Graph_Del = 3, +} UI_Graph_Operate_e; + +/* 图形配置参数__图形类型 */ +typedef enum +{ + UI_Graph_Line = 0, // 直线 + UI_Graph_Rectangle = 1, // 矩形 + UI_Graph_Circle = 2, // 整圆 + UI_Graph_Ellipse = 3, // 椭圆 + UI_Graph_Arc = 4, // 圆弧 + UI_Graph_Float = 5, // 浮点型 + UI_Graph_Int = 6, // 整形 + UI_Graph_Char = 7, // 字符型 + +} UI_Graph_Type_e; + +/* 图形配置参数__图形颜色 */ +typedef enum +{ + UI_Color_Main = 0, // 红蓝主色 + UI_Color_Yellow = 1, + UI_Color_Green = 2, + UI_Color_Orange = 3, + UI_Color_Purplish_red = 4, // 紫红色 + UI_Color_Pink = 5, + UI_Color_Cyan = 6, // 青色 + UI_Color_Black = 7, + UI_Color_White = 8, + +} UI_Graph_Color_e; + +#pragma pack() + +#endif diff --git a/modules/referee/referee_task.c b/modules/referee/referee_task.c new file mode 100644 index 0000000..7971265 --- /dev/null +++ b/modules/referee/referee_task.c @@ -0,0 +1,299 @@ +/** + * @file referee.C + * @author kidneygood (you@domain.com) + * @brief + * @version 0.1 + * @date 2022-11-18 + * + * @copyright Copyright (c) 2022 + * + */ +#include "referee_task.h" +#include "robot_def.h" +#include "rm_referee.h" +#include "referee_UI.h" +#include "string.h" +#include "cmsis_os.h" + +static Referee_Interactive_info_t *Interactive_data; // UI绘制需要的机器人状态数据 +static referee_info_t *referee_recv_info; // 接收到的裁判系统数据 +uint8_t UI_Seq; // 包序号,供整个referee文件使用 +// @todo 不应该使用全局变量 + +/** + * @brief 判断各种ID,选择客户端ID + * @param referee_info_t *referee_recv_info + * @retval none + * @attention + */ +static void DeterminRobotID() +{ + // id小于7是红色,大于7是蓝色,0为红色,1为蓝色 #define Robot_Red 0 #define Robot_Blue 1 + referee_recv_info->referee_id.Robot_Color = referee_recv_info->GameRobotState.robot_id > 7 ? Robot_Blue : Robot_Red; + referee_recv_info->referee_id.Robot_ID = referee_recv_info->GameRobotState.robot_id; + referee_recv_info->referee_id.Cilent_ID = 0x0100 + referee_recv_info->referee_id.Robot_ID; // 计算客户端ID + referee_recv_info->referee_id.Receiver_Robot_ID = 0; +} + +static void MyUIRefresh(referee_info_t *referee_recv_info, Referee_Interactive_info_t *_Interactive_data); +static void UIChangeCheck(Referee_Interactive_info_t *_Interactive_data); // 模式切换检测 +static void RobotModeTest(Referee_Interactive_info_t *_Interactive_data); // 测试用函数,实现模式自动变化 + +referee_info_t *UITaskInit(UART_HandleTypeDef *referee_usart_handle, Referee_Interactive_info_t *UI_data) +{ + referee_recv_info = RefereeInit(referee_usart_handle); // 初始化裁判系统的串口,并返回裁判系统反馈数据指针 + Interactive_data = UI_data; // 获取UI绘制需要的机器人状态数据 + referee_recv_info->init_flag = 1; + return referee_recv_info; +} + +void UITask() +{ + RobotModeTest(Interactive_data); // 测试用函数,实现模式自动变化,用于检查该任务和裁判系统是否连接正常 + MyUIRefresh(referee_recv_info, Interactive_data); +} + +static Graph_Data_t UI_shoot_line[10]; // 射击准线 +static Graph_Data_t UI_Energy[3]; // 电容能量条 +static String_Data_t UI_State_sta[6]; // 机器人状态,静态只需画一次 +static String_Data_t UI_State_dyn[6]; // 机器人状态,动态先add才能change +static uint32_t shoot_line_location[10] = {540, 960, 490, 515, 565}; + +void MyUIInit() +{ + if (!referee_recv_info->init_flag) + vTaskDelete(NULL); // 如果没有初始化裁判系统则直接删除ui任务 + while (referee_recv_info->GameRobotState.robot_id == 0) + osDelay(100); // 若还未收到裁判系统数据,等待一段时间后再检查 + + DeterminRobotID(); // 确定ui要发送到的目标客户端 + UIDelete(&referee_recv_info->referee_id, UI_Data_Del_ALL, 0); // 清空UI + + // 绘制发射基准线 + UILineDraw(&UI_shoot_line[0], "sl0", UI_Graph_ADD, 7, UI_Color_White, 3, 710, shoot_line_location[0], 1210, shoot_line_location[0]); + UILineDraw(&UI_shoot_line[1], "sl1", UI_Graph_ADD, 7, UI_Color_White, 3, shoot_line_location[1], 340, shoot_line_location[1], 740); + UILineDraw(&UI_shoot_line[2], "sl2", UI_Graph_ADD, 7, UI_Color_Yellow, 2, 810, shoot_line_location[2], 1110, shoot_line_location[2]); + UILineDraw(&UI_shoot_line[3], "sl3", UI_Graph_ADD, 7, UI_Color_Yellow, 2, 810, shoot_line_location[3], 1110, shoot_line_location[3]); + UILineDraw(&UI_shoot_line[4], "sl4", UI_Graph_ADD, 7, UI_Color_Yellow, 2, 810, shoot_line_location[4], 1110, shoot_line_location[4]); + UIGraphRefresh(&referee_recv_info->referee_id, 5, UI_shoot_line[0], UI_shoot_line[1], UI_shoot_line[2], UI_shoot_line[3], UI_shoot_line[4]); + + // 绘制车辆状态标志指示 + UICharDraw(&UI_State_sta[0], "ss0", UI_Graph_ADD, 8, UI_Color_Main, 15, 2, 150, 750, "chassis:"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_sta[0]); + UICharDraw(&UI_State_sta[1], "ss1", UI_Graph_ADD, 8, UI_Color_Yellow, 15, 2, 150, 700, "gimbal:"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_sta[1]); + UICharDraw(&UI_State_sta[2], "ss2", UI_Graph_ADD, 8, UI_Color_Orange, 15, 2, 150, 650, "shoot:"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_sta[2]); + UICharDraw(&UI_State_sta[3], "ss3", UI_Graph_ADD, 8, UI_Color_Pink, 15, 2, 150, 600, "frict:"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_sta[3]); + UICharDraw(&UI_State_sta[4], "ss4", UI_Graph_ADD, 8, UI_Color_Pink, 15, 2, 150, 550, "lid:"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_sta[4]); + + // 绘制车辆状态标志,动态 + // 由于初始化时xxx_last_mode默认为0,所以此处对应UI也应该设为0时对应的UI,防止模式不变的情况下无法置位flag,导致UI无法刷新 + UICharDraw(&UI_State_dyn[0], "sd0", UI_Graph_ADD, 8, UI_Color_Main, 15, 2, 270, 750, "zeroforce"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[0]); + UICharDraw(&UI_State_dyn[1], "sd1", UI_Graph_ADD, 8, UI_Color_Yellow, 15, 2, 270, 700, "zeroforce"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[1]); + UICharDraw(&UI_State_dyn[2], "sd2", UI_Graph_ADD, 8, UI_Color_Orange, 15, 2, 270, 650, "off"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[2]); + UICharDraw(&UI_State_dyn[3], "sd3", UI_Graph_ADD, 8, UI_Color_Pink, 15, 2, 270, 600, "off"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[3]); + UICharDraw(&UI_State_dyn[4], "sd4", UI_Graph_ADD, 8, UI_Color_Pink, 15, 2, 270, 550, "open "); + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[4]); + + // 底盘功率显示,静态 + UICharDraw(&UI_State_sta[5], "ss5", UI_Graph_ADD, 7, UI_Color_Green, 18, 2, 620, 230, "Power:"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_sta[5]); + // 能量条框 + UIRectangleDraw(&UI_Energy[0], "ss6", UI_Graph_ADD, 7, UI_Color_Green, 2, 720, 140, 1220, 180); + UIGraphRefresh(&referee_recv_info->referee_id, 1, UI_Energy[0]); + + // 底盘功率显示,动态 + UIFloatDraw(&UI_Energy[1], "sd5", UI_Graph_ADD, 8, UI_Color_Green, 18, 2, 2, 750, 230, 24000); + // 能量条初始状态 + UILineDraw(&UI_Energy[2], "sd6", UI_Graph_ADD, 8, UI_Color_Pink, 30, 720, 160, 1020, 160); + UIGraphRefresh(&referee_recv_info->referee_id, 2, UI_Energy[1], UI_Energy[2]); +} + +// 测试用函数,实现模式自动变化,用于检查该任务和裁判系统是否连接正常 +static uint8_t count = 0; +static uint16_t count1 = 0; +static void RobotModeTest(Referee_Interactive_info_t *_Interactive_data) // 测试用函数,实现模式自动变化 +{ + count++; + if (count >= 50) + { + count = 0; + count1++; + } + switch (count1 % 4) + { + case 0: + { + _Interactive_data->chassis_mode = CHASSIS_ZERO_FORCE; + _Interactive_data->gimbal_mode = GIMBAL_ZERO_FORCE; + _Interactive_data->shoot_mode = SHOOT_ON; + _Interactive_data->friction_mode = FRICTION_ON; + _Interactive_data->lid_mode = LID_OPEN; + _Interactive_data->Chassis_Power_Data.chassis_power_mx += 3.5; + if (_Interactive_data->Chassis_Power_Data.chassis_power_mx >= 18) + _Interactive_data->Chassis_Power_Data.chassis_power_mx = 0; + break; + } + case 1: + { + _Interactive_data->chassis_mode = CHASSIS_ROTATE; + _Interactive_data->gimbal_mode = GIMBAL_FREE_MODE; + _Interactive_data->shoot_mode = SHOOT_OFF; + _Interactive_data->friction_mode = FRICTION_OFF; + _Interactive_data->lid_mode = LID_CLOSE; + break; + } + case 2: + { + _Interactive_data->chassis_mode = CHASSIS_NO_FOLLOW; + _Interactive_data->gimbal_mode = GIMBAL_GYRO_MODE; + _Interactive_data->shoot_mode = SHOOT_ON; + _Interactive_data->friction_mode = FRICTION_ON; + _Interactive_data->lid_mode = LID_OPEN; + break; + } + case 3: + { + _Interactive_data->chassis_mode = CHASSIS_FOLLOW_GIMBAL_YAW; + _Interactive_data->gimbal_mode = GIMBAL_ZERO_FORCE; + _Interactive_data->shoot_mode = SHOOT_OFF; + _Interactive_data->friction_mode = FRICTION_OFF; + _Interactive_data->lid_mode = LID_CLOSE; + break; + } + default: + break; + } +} + +static void MyUIRefresh(referee_info_t *referee_recv_info, Referee_Interactive_info_t *_Interactive_data) +{ + UIChangeCheck(_Interactive_data); + // chassis + if (_Interactive_data->Referee_Interactive_Flag.chassis_flag == 1) + { + switch (_Interactive_data->chassis_mode) + { + case CHASSIS_ZERO_FORCE: + UICharDraw(&UI_State_dyn[0], "sd0", UI_Graph_Change, 8, UI_Color_Main, 15, 2, 270, 750, "zeroforce"); + break; + case CHASSIS_ROTATE: + UICharDraw(&UI_State_dyn[0], "sd0", UI_Graph_Change, 8, UI_Color_Main, 15, 2, 270, 750, "rotate "); + // 此处注意字数对齐问题,字数相同才能覆盖掉 + break; + case CHASSIS_NO_FOLLOW: + UICharDraw(&UI_State_dyn[0], "sd0", UI_Graph_Change, 8, UI_Color_Main, 15, 2, 270, 750, "nofollow "); + break; + case CHASSIS_FOLLOW_GIMBAL_YAW: + UICharDraw(&UI_State_dyn[0], "sd0", UI_Graph_Change, 8, UI_Color_Main, 15, 2, 270, 750, "follow "); + break; + } + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[0]); + _Interactive_data->Referee_Interactive_Flag.chassis_flag = 0; + } + // gimbal + if (_Interactive_data->Referee_Interactive_Flag.gimbal_flag == 1) + { + switch (_Interactive_data->gimbal_mode) + { + case GIMBAL_ZERO_FORCE: + { + UICharDraw(&UI_State_dyn[1], "sd1", UI_Graph_Change, 8, UI_Color_Yellow, 15, 2, 270, 700, "zeroforce"); + break; + } + case GIMBAL_FREE_MODE: + { + UICharDraw(&UI_State_dyn[1], "sd1", UI_Graph_Change, 8, UI_Color_Yellow, 15, 2, 270, 700, "free "); + break; + } + case GIMBAL_GYRO_MODE: + { + UICharDraw(&UI_State_dyn[1], "sd1", UI_Graph_Change, 8, UI_Color_Yellow, 15, 2, 270, 700, "gyro "); + break; + } + } + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[1]); + _Interactive_data->Referee_Interactive_Flag.gimbal_flag = 0; + } + // shoot + if (_Interactive_data->Referee_Interactive_Flag.shoot_flag == 1) + { + UICharDraw(&UI_State_dyn[2], "sd2", UI_Graph_Change, 8, UI_Color_Pink, 15, 2, 270, 650, _Interactive_data->shoot_mode == SHOOT_ON ? "on " : "off"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[2]); + _Interactive_data->Referee_Interactive_Flag.shoot_flag = 0; + } + // friction + if (_Interactive_data->Referee_Interactive_Flag.friction_flag == 1) + { + UICharDraw(&UI_State_dyn[3], "sd3", UI_Graph_Change, 8, UI_Color_Pink, 15, 2, 270, 600, _Interactive_data->friction_mode == FRICTION_ON ? "on " : "off"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[3]); + _Interactive_data->Referee_Interactive_Flag.friction_flag = 0; + } + // lid + if (_Interactive_data->Referee_Interactive_Flag.lid_flag == 1) + { + UICharDraw(&UI_State_dyn[4], "sd4", UI_Graph_Change, 8, UI_Color_Pink, 15, 2, 270, 550, _Interactive_data->lid_mode == LID_OPEN ? "open " : "close"); + UICharRefresh(&referee_recv_info->referee_id, UI_State_dyn[4]); + _Interactive_data->Referee_Interactive_Flag.lid_flag = 0; + } + // power + if (_Interactive_data->Referee_Interactive_Flag.Power_flag == 1) + { + UIFloatDraw(&UI_Energy[1], "sd5", UI_Graph_Change, 8, UI_Color_Green, 18, 2, 2, 750, 230, _Interactive_data->Chassis_Power_Data.chassis_power_mx * 1000); + UILineDraw(&UI_Energy[2], "sd6", UI_Graph_Change, 8, UI_Color_Pink, 30, 720, 160, (uint32_t)750 + _Interactive_data->Chassis_Power_Data.chassis_power_mx * 30, 160); + UIGraphRefresh(&referee_recv_info->referee_id, 2, UI_Energy[1], UI_Energy[2]); + _Interactive_data->Referee_Interactive_Flag.Power_flag = 0; + } +} + +/** + * @brief 模式切换检测,模式发生切换时,对flag置位 + * @param Referee_Interactive_info_t *_Interactive_data + * @retval none + * @attention + */ +static void UIChangeCheck(Referee_Interactive_info_t *_Interactive_data) +{ + if (_Interactive_data->chassis_mode != _Interactive_data->chassis_last_mode) + { + _Interactive_data->Referee_Interactive_Flag.chassis_flag = 1; + _Interactive_data->chassis_last_mode = _Interactive_data->chassis_mode; + } + + if (_Interactive_data->gimbal_mode != _Interactive_data->gimbal_last_mode) + { + _Interactive_data->Referee_Interactive_Flag.gimbal_flag = 1; + _Interactive_data->gimbal_last_mode = _Interactive_data->gimbal_mode; + } + + if (_Interactive_data->shoot_mode != _Interactive_data->shoot_last_mode) + { + _Interactive_data->Referee_Interactive_Flag.shoot_flag = 1; + _Interactive_data->shoot_last_mode = _Interactive_data->shoot_mode; + } + + if (_Interactive_data->friction_mode != _Interactive_data->friction_last_mode) + { + _Interactive_data->Referee_Interactive_Flag.friction_flag = 1; + _Interactive_data->friction_last_mode = _Interactive_data->friction_mode; + } + + if (_Interactive_data->lid_mode != _Interactive_data->lid_last_mode) + { + _Interactive_data->Referee_Interactive_Flag.lid_flag = 1; + _Interactive_data->lid_last_mode = _Interactive_data->lid_mode; + } + + if (_Interactive_data->Chassis_Power_Data.chassis_power_mx != _Interactive_data->Chassis_last_Power_Data.chassis_power_mx) + { + _Interactive_data->Referee_Interactive_Flag.Power_flag = 1; + _Interactive_data->Chassis_last_Power_Data.chassis_power_mx = _Interactive_data->Chassis_Power_Data.chassis_power_mx; + } +} diff --git a/modules/referee/referee_task.h b/modules/referee/referee_task.h new file mode 100644 index 0000000..1eec04b --- /dev/null +++ b/modules/referee/referee_task.h @@ -0,0 +1,25 @@ +#ifndef REFEREE_H +#define REFEREE_H + +#include "rm_referee.h" +#include "robot_def.h" + +/** + * @brief 初始化裁判系统交互任务(UI和多机通信) + * + */ +referee_info_t *UITaskInit(UART_HandleTypeDef *referee_usart_handle, Referee_Interactive_info_t *UI_data); + +/** + * @brief 在referee task之前调用,添加在freertos.c中 + * + */ +void MyUIInit(); + +/** + * @brief 裁判系统交互任务(UI和多机通信) + * + */ +void UITask(); + +#endif // REFEREE_H diff --git a/modules/referee/rm_referee.c b/modules/referee/rm_referee.c new file mode 100644 index 0000000..2743d7d --- /dev/null +++ b/modules/referee/rm_referee.c @@ -0,0 +1,149 @@ +/** + * @file rm_referee.C + * @author kidneygood (you@domain.com) + * @brief + * @version 0.1 + * @date 2022-11-18 + * + * @copyright Copyright (c) 2022 + * + */ + +#include "rm_referee.h" +#include "string.h" +#include "crc_ref.h" +#include "bsp_usart.h" +#include "task.h" +#include "daemon.h" +#include "bsp_log.h" +#include "cmsis_os.h" + +#define RE_RX_BUFFER_SIZE 255u // 裁判系统接收缓冲区大小 + +static USARTInstance *referee_usart_instance; // 裁判系统串口实例 +static DaemonInstance *referee_daemon; // 裁判系统守护进程 +static referee_info_t referee_info; // 裁判系统数据 + +/** + * @brief 读取裁判数据,中断中读取保证速度 + * @param buff: 读取到的裁判系统原始数据 + * @retval 是否对正误判断做处理 + * @attention 在此判断帧头和CRC校验,无误再写入数据,不重复判断帧头 + */ +static void JudgeReadData(uint8_t *buff) +{ + uint16_t judge_length; // 统计一帧数据长度 + if (buff == NULL) // 空数据包,则不作任何处理 + return; + + // 写入帧头数据(5-byte),用于判断是否开始存储裁判数据 + memcpy(&referee_info.FrameHeader, buff, LEN_HEADER); + + // 判断帧头数据(0)是否为0xA5 + if (buff[SOF] == REFEREE_SOF) + { + // 帧头CRC8校验 + if (Verify_CRC8_Check_Sum(buff, LEN_HEADER) == TRUE) + { + // 统计一帧数据长度(byte),用于CR16校验 + judge_length = buff[DATA_LENGTH] + LEN_HEADER + LEN_CMDID + LEN_TAIL; + // 帧尾CRC16校验 + if (Verify_CRC16_Check_Sum(buff, judge_length) == TRUE) + { + // 2个8位拼成16位int + referee_info.CmdID = (buff[6] << 8 | buff[5]); + // 解析数据命令码,将数据拷贝到相应结构体中(注意拷贝数据的长度) + // 第8个字节开始才是数据 data=7 + switch (referee_info.CmdID) + { + case ID_game_state: // 0x0001 + memcpy(&referee_info.GameState, (buff + DATA_Offset), LEN_game_state); + break; + case ID_game_result: // 0x0002 + memcpy(&referee_info.GameResult, (buff + DATA_Offset), LEN_game_result); + break; + case ID_game_robot_survivors: // 0x0003 + memcpy(&referee_info.GameRobotHP, (buff + DATA_Offset), LEN_game_robot_HP); + break; + case ID_event_data: // 0x0101 + memcpy(&referee_info.EventData, (buff + DATA_Offset), LEN_event_data); + break; + case ID_supply_projectile_action: // 0x0102 + memcpy(&referee_info.SupplyProjectileAction, (buff + DATA_Offset), LEN_supply_projectile_action); + break; + case ID_game_robot_state: // 0x0201 + memcpy(&referee_info.GameRobotState, (buff + DATA_Offset), LEN_game_robot_state); + break; + case ID_power_heat_data: // 0x0202 + memcpy(&referee_info.PowerHeatData, (buff + DATA_Offset), LEN_power_heat_data); + break; + case ID_game_robot_pos: // 0x0203 + memcpy(&referee_info.GameRobotPos, (buff + DATA_Offset), LEN_game_robot_pos); + break; + case ID_buff_musk: // 0x0204 + memcpy(&referee_info.BuffMusk, (buff + DATA_Offset), LEN_buff_musk); + break; + case ID_aerial_robot_energy: // 0x0205 + memcpy(&referee_info.AerialRobotEnergy, (buff + DATA_Offset), LEN_aerial_robot_energy); + break; + case ID_robot_hurt: // 0x0206 + memcpy(&referee_info.RobotHurt, (buff + DATA_Offset), LEN_robot_hurt); + break; + case ID_shoot_data: // 0x0207 + memcpy(&referee_info.ShootData, (buff + DATA_Offset), LEN_shoot_data); + break; + case ID_student_interactive: // 0x0301 syhtodo接收代码未测试 + memcpy(&referee_info.ReceiveData, (buff + DATA_Offset), LEN_receive_data); + break; + } + } + } + // 首地址加帧长度,指向CRC16下一字节,用来判断是否为0xA5,从而判断一个数据包是否有多帧数据 + if (*(buff + sizeof(xFrameHeader) + LEN_CMDID + referee_info.FrameHeader.DataLength + LEN_TAIL) == 0xA5) + { // 如果一个数据包出现了多帧数据,则再次调用解析函数,直到所有数据包解析完毕 + JudgeReadData(buff + sizeof(xFrameHeader) + LEN_CMDID + referee_info.FrameHeader.DataLength + LEN_TAIL); + } + } +} + +/*裁判系统串口接收回调函数,解析数据 */ +static void RefereeRxCallback() +{ + DaemonReload(referee_daemon); + JudgeReadData(referee_usart_instance->recv_buff); +} +// 裁判系统丢失回调函数,重新初始化裁判系统串口 +static void RefereeLostCallback(void *arg) +{ + USARTServiceInit(referee_usart_instance); + LOGWARNING("[rm_ref] lost referee data"); +} + +/* 裁判系统通信初始化 */ +referee_info_t *RefereeInit(UART_HandleTypeDef *referee_usart_handle) +{ + USART_Init_Config_s conf; + conf.module_callback = RefereeRxCallback; + conf.usart_handle = referee_usart_handle; + conf.recv_buff_size = RE_RX_BUFFER_SIZE; // mx 255(u8) + referee_usart_instance = USARTRegister(&conf); + + Daemon_Init_Config_s daemon_conf = { + .callback = RefereeLostCallback, + .owner_id = referee_usart_instance, + .reload_count = 30, // 0.3s没有收到数据,则认为丢失,重启串口接收 + }; + referee_daemon = DaemonRegister(&daemon_conf); + + return &referee_info; +} + +/** + * @brief 裁判系统数据发送函数 + * @param + */ +void RefereeSend(uint8_t *send, uint16_t tx_len) +{ + USARTSend(referee_usart_instance, send, tx_len, USART_TRANSFER_DMA); + osDelay(115); +} diff --git a/modules/referee/rm_referee.h b/modules/referee/rm_referee.h new file mode 100644 index 0000000..e935e94 --- /dev/null +++ b/modules/referee/rm_referee.h @@ -0,0 +1,100 @@ +#ifndef RM_REFEREE_H +#define RM_REFEREE_H + +#include "usart.h" +#include "referee_protocol.h" +#include "robot_def.h" +#include "bsp_usart.h" +#include "FreeRTOS.h" + +extern uint8_t UI_Seq; + +#pragma pack(1) +typedef struct +{ + uint8_t Robot_Color; // 机器人颜色 + uint16_t Robot_ID; // 本机器人ID + uint16_t Cilent_ID; // 本机器人对应的客户端ID + uint16_t Receiver_Robot_ID; // 机器人车间通信时接收者的ID,必须和本机器人同颜色 +} referee_id_t; + +// 此结构体包含裁判系统接收数据以及UI绘制与机器人车间通信的相关信息 +typedef struct +{ + referee_id_t referee_id; + + xFrameHeader FrameHeader; // 接收到的帧头信息 + uint16_t CmdID; + ext_game_state_t GameState; // 0x0001 + ext_game_result_t GameResult; // 0x0002 + ext_game_robot_HP_t GameRobotHP; // 0x0003 + ext_event_data_t EventData; // 0x0101 + ext_supply_projectile_action_t SupplyProjectileAction; // 0x0102 + ext_game_robot_state_t GameRobotState; // 0x0201 + ext_power_heat_data_t PowerHeatData; // 0x0202 + ext_game_robot_pos_t GameRobotPos; // 0x0203 + ext_buff_musk_t BuffMusk; // 0x0204 + aerial_robot_energy_t AerialRobotEnergy; // 0x0205 + ext_robot_hurt_t RobotHurt; // 0x0206 + ext_shoot_data_t ShootData; // 0x0207 + + // 自定义交互数据的接收 + Communicate_ReceiveData_t ReceiveData; + + uint8_t init_flag; + +} referee_info_t; + +// 模式是否切换标志位,0为未切换,1为切换,static定义默认为0 +typedef struct +{ + uint32_t chassis_flag : 1; + uint32_t gimbal_flag : 1; + uint32_t shoot_flag : 1; + uint32_t lid_flag : 1; + uint32_t friction_flag : 1; + uint32_t Power_flag : 1; +} Referee_Interactive_Flag_t; + +// 此结构体包含UI绘制与机器人车间通信的需要的其他非裁判系统数据 +typedef struct +{ + Referee_Interactive_Flag_t Referee_Interactive_Flag; + // 为UI绘制以及交互数据所用 + chassis_mode_e chassis_mode; // 底盘模式 + gimbal_mode_e gimbal_mode; // 云台模式 + shoot_mode_e shoot_mode; // 发射模式设置 + friction_mode_e friction_mode; // 摩擦轮关闭 + lid_mode_e lid_mode; // 弹舱盖打开 + Chassis_Power_Data_s Chassis_Power_Data; // 功率控制 + + // 上一次的模式,用于flag判断 + chassis_mode_e chassis_last_mode; + gimbal_mode_e gimbal_last_mode; + shoot_mode_e shoot_last_mode; + friction_mode_e friction_last_mode; + lid_mode_e lid_last_mode; + Chassis_Power_Data_s Chassis_last_Power_Data; + +} Referee_Interactive_info_t; + +#pragma pack() + +/** + * @brief 裁判系统通信初始化,该函数会初始化裁判系统串口,开启中断 + * + * @param referee_usart_handle 串口handle,C板一般用串口6 + * @return referee_info_t* 返回裁判系统反馈的数据,包括热量/血量/状态等 + */ +referee_info_t *RefereeInit(UART_HandleTypeDef *referee_usart_handle); + +/** + * @brief UI绘制和交互数的发送接口,由UI绘制任务和多机通信函数调用 + * @note 内部包含了一个实时系统的延时函数,这是因为裁判系统接收CMD数据至高位10Hz + * + * @param send 发送数据首地址 + * @param tx_len 发送长度 + */ +void RefereeSend(uint8_t *send, uint16_t tx_len); + +#endif // !REFEREE_H diff --git a/modules/remote/remote.md b/modules/remote/remote.md new file mode 100644 index 0000000..e6ac73a --- /dev/null +++ b/modules/remote/remote.md @@ -0,0 +1,85 @@ +remote_control + neozng1@hnu.edu.cn
+``` +/*************************发射机DT7*************************** + * * + * ----------------------------------------------------- * + * | (上-1) (上-1) | * + * |SW_L|(中-3) SW_R|(中-3) | * + * | (下-2) (下-2) | * + * | | * + * | | ^ | | ^ | | * + * | | 3 |左摇杆 右摇杆| 1 | | * + * | --- --- --- --- | * + * |< 2> < 0>| * + * | --- --- --- --- | * + * | | | | | | * + * | | | | | | * + * | | * + * ----------------------------------------------------- * + * * + **************************遥控器信息************************** + *域 通道0 通道1 通道2 通道3 S1 S2 * + *偏移 0 11 22 33 44 46 * + *长度(bit) 11 11 11 11 2 2 * + *符号位 无 无 无 无 无 无 * + *范围 ***********最大值1684********* *最大值3* * + * * 中间值1024 * *最小值1* * + * ***********最小值364********** * + *功能 1:上 1:上 * + * 2:下 2:下 * + * 3:中 3:中 * + * * + ***************************鼠标信息*************************** + *域 鼠标x轴 鼠标y轴 鼠标z轴 鼠标左键 鼠标右键* + *偏移 48 64 80 86 94 * + *长度 16 16 16 8 8 * + *符号位 有 有 有 无 无 * + *范围 ******最大值32767***** ***最大值1*** * + * * 最小值-32768 * ***最小值0*** * + * ******静止值0********* * + *功能 ***鼠标在XYZ轴的移动速度*** *鼠标左右键是否按下* + * * 负值表示往左移动 * * 0:没按下 * + * ***正值表示往右移动******** *****1:按下********* + * * + * * + ***************************键盘信息*************************** + *域 按键 * + *偏移 102 * + *长度 16 * + *符号位 无 * + *范围 位值标识 * + *功能 每个按键对应一个bit * + * Bit 0:W键 * + * Bit 1:S键 * + * Bit 2:A键 * + * Bit 3:D键 * + * Bit 4:Shift键 * + * Bit 5:Ctrl键 * + * Bit 6:Q键 * + * Bit 7:E键 * + * Bit 8:R键 * + * Bit 9:F键 * + * Bit10:G键 * + * Bit11:Z键 * + * Bit12:X键 * + * Bit13:C键 * + * Bit14:V键 * + * Bit15:B键 * + **************************************************************/ +``` + + +目前的映射: + +拨轮向下打到底进入紧急停止模式(后续改为关闭遥控器停止,利用daemon; daemon已经模块完成);拨轮向上打开启摩擦轮,超过一半开始发射(速度环,连发) + +左侧开关: +- 上:键鼠控制 +- 中:视觉控制(没有识别到目标的时候仍然可以使用遥控器控制云台) +- 下:遥控器控制 + +右侧开关: +- 上:弹舱开 +- 中:底盘云台分离(底盘不旋转,全向移动) +- 下:底盘跟随云台 diff --git a/modules/remote/remote_control.c b/modules/remote/remote_control.c new file mode 100644 index 0000000..0949f6d --- /dev/null +++ b/modules/remote/remote_control.c @@ -0,0 +1,138 @@ +#include "remote_control.h" +#include "string.h" +#include "bsp_usart.h" +#include "memory.h" +#include "stdlib.h" +#include "daemon.h" +#include "bsp_log.h" + +#define REMOTE_CONTROL_FRAME_SIZE 18u // 遥控器接收的buffer大小 + +// 遥控器数据 +static RC_ctrl_t rc_ctrl[2]; //[0]:当前数据TEMP,[1]:上一次的数据LAST.用于按键持续按下和切换的判断 +static uint8_t rc_init_flag = 0; // 遥控器初始化标志位 + +// 遥控器拥有的串口实例,因为遥控器是单例,所以这里只有一个,就不封装了 +static USARTInstance *rc_usart_instance; +static DaemonInstance *rc_daemon_instance; + +/** + * @brief 矫正遥控器摇杆的值,超过660或者小于-660的值都认为是无效值,置0 + * + */ +static void RectifyRCjoystick() +{ + for (uint8_t i = 0; i < 5; ++i) + if (abs(*(&rc_ctrl[TEMP].rc.rocker_l_ + i)) > 660) + *(&rc_ctrl[TEMP].rc.rocker_l_ + i) = 0; +} + +/** + * @brief 遥控器数据解析 + * + * @param sbus_buf 接收buffer + */ +static void sbus_to_rc(const uint8_t *sbus_buf) +{ + // 摇杆,直接解算时减去偏置 + rc_ctrl[TEMP].rc.rocker_r_ = ((sbus_buf[0] | (sbus_buf[1] << 8)) & 0x07ff) - RC_CH_VALUE_OFFSET; //!< Channel 0 + rc_ctrl[TEMP].rc.rocker_r1 = (((sbus_buf[1] >> 3) | (sbus_buf[2] << 5)) & 0x07ff) - RC_CH_VALUE_OFFSET; //!< Channel 1 + rc_ctrl[TEMP].rc.rocker_l_ = (((sbus_buf[2] >> 6) | (sbus_buf[3] << 2) | (sbus_buf[4] << 10)) & 0x07ff) - RC_CH_VALUE_OFFSET; //!< Channel 2 + rc_ctrl[TEMP].rc.rocker_l1 = (((sbus_buf[4] >> 1) | (sbus_buf[5] << 7)) & 0x07ff) - RC_CH_VALUE_OFFSET; //!< Channel 3 + rc_ctrl[TEMP].rc.dial = ((sbus_buf[16] | (sbus_buf[17] << 8)) & 0x07FF) - RC_CH_VALUE_OFFSET; + rc_ctrl[TEMP].rc.rocker_l_= rc_ctrl[TEMP].rc.rocker_l_+3; + // 左侧拨轮 + RectifyRCjoystick(); + // 开关,0左1右 + rc_ctrl[TEMP].rc.switch_right = ((sbus_buf[5] >> 4) & 0x0003); //!< Switch right + rc_ctrl[TEMP].rc.switch_left = ((sbus_buf[5] >> 4) & 0x000C) >> 2; //!< Switch left + + // 鼠标解析 + rc_ctrl[TEMP].mouse.x = (sbus_buf[6] | (sbus_buf[7] << 8)); //!< Mouse X axis + rc_ctrl[TEMP].mouse.y = (sbus_buf[8] | (sbus_buf[9] << 8)); //!< Mouse Y axis + rc_ctrl[TEMP].mouse.press_l = sbus_buf[12]; //!< Mouse Left Is Press ? + rc_ctrl[TEMP].mouse.press_r = sbus_buf[13]; //!< Mouse Right Is Press ? + + // 位域的按键值解算,直接memcpy即可,注意小端低字节在前,即lsb在第一位,msb在最后 + *(uint16_t *)&rc_ctrl[TEMP].key[KEY_PRESS] = (uint16_t)(sbus_buf[14] | (sbus_buf[15] << 8)); + if (rc_ctrl[TEMP].key[KEY_PRESS].ctrl) // ctrl键按下 + rc_ctrl[TEMP].key[KEY_PRESS_WITH_CTRL] = rc_ctrl[TEMP].key[KEY_PRESS]; + else + memset(&rc_ctrl[TEMP].key[KEY_PRESS_WITH_CTRL], 0, sizeof(Key_t)); + if (rc_ctrl[TEMP].key[KEY_PRESS].shift) // shift键按下 + rc_ctrl[TEMP].key[KEY_PRESS_WITH_SHIFT] = rc_ctrl[TEMP].key[KEY_PRESS]; + else + memset(&rc_ctrl[TEMP].key[KEY_PRESS_WITH_SHIFT], 0, sizeof(Key_t)); + + uint16_t key_now = rc_ctrl[TEMP].key[KEY_PRESS].keys, // 当前按键是否按下 + key_last = rc_ctrl[LAST].key[KEY_PRESS].keys, // 上一次按键是否按下 + key_with_ctrl = rc_ctrl[TEMP].key[KEY_PRESS_WITH_CTRL].keys, // 当前ctrl组合键是否按下 + key_with_shift = rc_ctrl[TEMP].key[KEY_PRESS_WITH_SHIFT].keys, // 当前shift组合键是否按下 + key_last_with_ctrl = rc_ctrl[LAST].key[KEY_PRESS_WITH_CTRL].keys, // 上一次ctrl组合键是否按下 + key_last_with_shift = rc_ctrl[LAST].key[KEY_PRESS_WITH_SHIFT].keys; // 上一次shift组合键是否按下 + + for (uint16_t i = 0, j = 0x1; i < 16; j <<= 1, i++) + { + if (i == 4 || i == 5) // 4,5位为ctrl和shift,直接跳过 + continue; + // 如果当前按键按下,上一次按键没有按下,且ctrl和shift组合键没有按下,则按键按下计数加1(检测到上升沿) + if ((key_now & j) && !(key_last & j) && !(key_with_ctrl & j) && !(key_with_shift & j)) + rc_ctrl[TEMP].key_count[KEY_PRESS][i]++; + // 当前ctrl组合键按下,上一次ctrl组合键没有按下,则ctrl组合键按下计数加1(检测到上升沿) + if ((key_with_ctrl & j) && !(key_last_with_ctrl & j)) + rc_ctrl[TEMP].key_count[KEY_PRESS_WITH_CTRL][i]++; + // 当前shift组合键按下,上一次shift组合键没有按下,则shift组合键按下计数加1(检测到上升沿) + if ((key_with_shift & j) && !(key_last_with_shift & j)) + rc_ctrl[TEMP].key_count[KEY_PRESS_WITH_SHIFT][i]++; + } + + memcpy(&rc_ctrl[LAST], &rc_ctrl[TEMP], sizeof(RC_ctrl_t)); // 保存上一次的数据,用于按键持续按下和切换的判断 +} + +/** + * @brief 对sbus_to_rc的简单封装,用于注册到bsp_usart的回调函数中 + * + */ +static void RemoteControlRxCallback() +{ + DaemonReload(rc_daemon_instance); // 先喂狗 + sbus_to_rc(rc_usart_instance->recv_buff); // 进行协议解析 +} + +/** + * @brief 遥控器离线的回调函数,注册到守护进程中,串口掉线时调用 + * + */ +static void RCLostCallback(void *id) +{ + memset(rc_ctrl, 0, sizeof(rc_ctrl)); // 清空遥控器数据 + USARTServiceInit(rc_usart_instance); // 尝试重新启动接收 + LOGWARNING("[rc] remote control lost"); +} + +RC_ctrl_t *RemoteControlInit(UART_HandleTypeDef *rc_usart_handle) +{ + USART_Init_Config_s conf; + conf.module_callback = RemoteControlRxCallback; + conf.usart_handle = rc_usart_handle; + conf.recv_buff_size = REMOTE_CONTROL_FRAME_SIZE; + rc_usart_instance = USARTRegister(&conf); + + // 进行守护进程的注册,用于定时检查遥控器是否正常工作 + Daemon_Init_Config_s daemon_conf = { + .reload_count = 10, // 100ms未收到数据视为离线,遥控器的接收频率实际上是1000/14Hz(大约70Hz) + .callback = RCLostCallback, + .owner_id = NULL, // 只有1个遥控器,不需要owner_id + }; + rc_daemon_instance = DaemonRegister(&daemon_conf); + + rc_init_flag = 1; + return rc_ctrl; +} + +uint8_t RemoteControlIsOnline() +{ + if (rc_init_flag) + return DaemonIsOnline(rc_daemon_instance); + return 0; +} \ No newline at end of file diff --git a/modules/remote/remote_control.h b/modules/remote/remote_control.h new file mode 100644 index 0000000..c12f810 --- /dev/null +++ b/modules/remote/remote_control.h @@ -0,0 +1,133 @@ +/** + * @file remote_control.h + * @author DJI 2016 + * @author modified by neozng + * @brief 遥控器模块定义头文件 + * @version beta + * @date 2022-11-01 + * + * @copyright Copyright (c) 2016 DJI corp + * @copyright Copyright (c) 2022 HNU YueLu EC all rights reserved + * + */ +#ifndef REMOTE_CONTROL_H +#define REMOTE_CONTROL_H + +#include+#include "main.h" +#include "usart.h" + +// 用于遥控器数据读取,遥控器数据是一个大小为2的数组 +#define LAST 1 +#define TEMP 0 + +// 获取按键操作 +#define KEY_PRESS 0 +#define KEY_STATE 1 +#define KEY_PRESS_WITH_CTRL 1 +#define KEY_PRESS_WITH_SHIFT 2 + +// 检查接收值是否出错 +#define RC_CH_VALUE_MIN ((uint16_t)364) +#define RC_CH_VALUE_OFFSET ((uint16_t)1024) +#define RC_CH_VALUE_MAX ((uint16_t)1684) + +/* ----------------------- RC Switch Definition----------------------------- */ +#define RC_SW_UP ((uint16_t)1) // 开关向上时的值 +#define RC_SW_MID ((uint16_t)3) // 开关中间时的值 +#define RC_SW_DOWN ((uint16_t)2) // 开关向下时的值 +// 三个判断开关状态的宏 +#define switch_is_down(s) (s == RC_SW_DOWN) +#define switch_is_mid(s) (s == RC_SW_MID) +#define switch_is_up(s) (s == RC_SW_UP) + +/* ----------------------- PC Key Definition-------------------------------- */ +// 对应key[x][0~16],获取对应的键;例如通过key[KEY_PRESS][Key_W]获取W键是否按下,后续改为位域后删除 +#define Key_W 0 +#define Key_S 1 +#define Key_D 2 +#define Key_A 3 +#define Key_Shift 4 +#define Key_Ctrl 5 +#define Key_Q 6 +#define Key_E 7 +#define Key_R 8 +#define Key_F 9 +#define Key_G 10 +#define Key_Z 11 +#define Key_X 12 +#define Key_C 13 +#define Key_V 14 +#define Key_B 15 + +/* ----------------------- Data Struct ------------------------------------- */ +// 待测试的位域结构体,可以极大提升解析速度 +typedef union +{ + struct // 用于访问键盘状态 + { + uint16_t w : 1; + uint16_t s : 1; + uint16_t d : 1; + uint16_t a : 1; + uint16_t shift : 1; + uint16_t ctrl : 1; + uint16_t q : 1; + uint16_t e : 1; + uint16_t r : 1; + uint16_t f : 1; + uint16_t g : 1; + uint16_t z : 1; + uint16_t x : 1; + uint16_t c : 1; + uint16_t v : 1; + uint16_t b : 1; + }; + uint16_t keys; // 用于memcpy而不需要进行强制类型转换 +} Key_t; + +// @todo 当前结构体嵌套过深,需要进行优化 +typedef struct +{ + struct + { + int16_t rocker_l_; // 左水平 + int16_t rocker_l1; // 左竖直 + int16_t rocker_r_; // 右水平 + int16_t rocker_r1; // 右竖直 + int16_t dial; // 侧边拨轮 + + uint8_t switch_left; // 左侧开关 + uint8_t switch_right; // 右侧开关 + } rc; + struct + { + int16_t x; + int16_t y; + uint8_t press_l; + uint8_t press_r; + } mouse; + + Key_t key[3]; // 改为位域后的键盘索引,空间减少8倍,速度增加16~倍 + + uint8_t key_count[3][16]; +} RC_ctrl_t; + +/* ------------------------- Internal Data ----------------------------------- */ + +/** + * @brief 初始化遥控器,该函数会将遥控器注册到串口 + * + * @attention 注意分配正确的串口硬件,遥控器在C板上使用USART3 + * + */ +RC_ctrl_t *RemoteControlInit(UART_HandleTypeDef *rc_usart_handle); + +/** + * @brief 检查遥控器是否在线,若尚未初始化也视为离线 + * + * @return uint8_t 1:在线 0:离线 + */ +uint8_t RemoteControlIsOnline(); + +#endif diff --git a/modules/standard_cmd/standard_cmd.md b/modules/standard_cmd/standard_cmd.md new file mode 100644 index 0000000..010a341 --- /dev/null +++ b/modules/standard_cmd/standard_cmd.md @@ -0,0 +1,16 @@ +# 标准命令 + +这是一个体力活,也是一个艺术品。请把不同的控制命令module进行封装,以转化成标准的消息类型,包括云台角度速度,底盘速度,发射频率是否发射等信息,供RobotCMD应用或其他应用使用。通过这种方式,开发者可以更专注于cmd命令的编写,而不需要为每台机器人/不同的控制器编写命令转换。 + +是否将下面的模块都放到standard_cmd文件夹下?似乎没有必要。 + +## remote control + +## master machine + +## ps handle + +## key and mouse + +## 图传链路 +图传链路的数据解析似乎和键鼠是同一套协议,不过走的是串口,可能需要额外添加支持模块 \ No newline at end of file diff --git a/modules/standard_cmd/std_cmd.c b/modules/standard_cmd/std_cmd.c new file mode 100644 index 0000000..e69de29 diff --git a/modules/standard_cmd/std_cmd.h b/modules/standard_cmd/std_cmd.h new file mode 100644 index 0000000..e69de29 diff --git a/modules/super_cap/super_cap.c b/modules/super_cap/super_cap.c new file mode 100644 index 0000000..eb86749 --- /dev/null +++ b/modules/super_cap/super_cap.c @@ -0,0 +1,44 @@ +/* + * @Descripttion: + * @version: + * @Author: Chenfu + * @Date: 2022-12-02 21:32:47 + * @LastEditTime: 2022-12-05 15:29:49 + */ +#include "super_cap.h" +#include "memory.h" +#include "stdlib.h" + +static SuperCapInstance *super_cap_instance = NULL; // 可以由app保存此指针 + +static void SuperCapRxCallback(CANInstance *_instance) +{ + uint8_t *rxbuff; + SuperCap_Msg_s *Msg; + rxbuff = _instance->rx_buff; + Msg = &super_cap_instance->cap_msg; + Msg->vol = (uint16_t)(rxbuff[0] << 8 | rxbuff[1]); + Msg->current = (uint16_t)(rxbuff[2] << 8 | rxbuff[3]); + Msg->power = (uint16_t)(rxbuff[4] << 8 | rxbuff[5]); +} + +SuperCapInstance *SuperCapInit(SuperCap_Init_Config_s *supercap_config) +{ + super_cap_instance = (SuperCapInstance *)malloc(sizeof(SuperCapInstance)); + memset(super_cap_instance, 0, sizeof(SuperCapInstance)); + + supercap_config->can_config.can_module_callback = SuperCapRxCallback; + super_cap_instance->can_ins = CANRegister(&supercap_config->can_config); + return super_cap_instance; +} + +void SuperCapSend(SuperCapInstance *instance, uint8_t *data) +{ + memcpy(instance->can_ins->tx_buff, data, 8); + CANTransmit(instance->can_ins,1); +} + +SuperCap_Msg_s SuperCapGet(SuperCapInstance *instance) +{ + return instance->cap_msg; +} \ No newline at end of file diff --git a/modules/super_cap/super_cap.h b/modules/super_cap/super_cap.h new file mode 100644 index 0000000..81c5f8e --- /dev/null +++ b/modules/super_cap/super_cap.h @@ -0,0 +1,51 @@ +/* + * @Descripttion: + * @version: + * @Author: Chenfu + * @Date: 2022-12-02 21:32:47 + * @LastEditTime: 2022-12-05 15:25:46 + */ +#ifndef SUPER_CAP_H +#define SUPER_CAP_H + +#include "bsp_can.h" + +#pragma pack(1) +typedef struct +{ + uint16_t vol; // 电压 + uint16_t current; // 电流 + uint16_t power; // 功率 +} SuperCap_Msg_s; +#pragma pack() + +/* 超级电容实例 */ +typedef struct +{ + CANInstance *can_ins; // CAN实例 + SuperCap_Msg_s cap_msg; // 超级电容信息 +} SuperCapInstance; + +/* 超级电容初始化配置 */ +typedef struct +{ + CAN_Init_Config_s can_config; +} SuperCap_Init_Config_s; + +/** + * @brief 初始化超级电容 + * + * @param supercap_config 超级电容初始化配置 + * @return SuperCapInstance* 超级电容实例指针 + */ +SuperCapInstance *SuperCapInit(SuperCap_Init_Config_s *supercap_config); + +/** + * @brief 发送超级电容控制信息 + * + * @param instance 超级电容实例 + * @param data 超级电容控制信息 + */ +void SuperCapSend(SuperCapInstance *instance, uint8_t *data); + +#endif // !SUPER_CAP_Hd diff --git a/modules/super_cap/super_cap.md b/modules/super_cap/super_cap.md new file mode 100644 index 0000000..5f70f63 --- /dev/null +++ b/modules/super_cap/super_cap.md @@ -0,0 +1,54 @@ + +# super_can + +## 代码结构 + +.h中放置的是数据定义和外部接口,以及协议的定义和宏,.c中包含一些私有函数。 + +## 外部接口 + +```c +SuperCapInstance *SuperCapInit(SuperCap_Init_Config_s* supercap_config); +void SuperCapSend(SuperCapInstance *instance, uint8_t *data); +``` +## 私有函数和变量 + +```c +static SuperCapInstance *super_cap_instance = NULL; +static uint8_t *rxbuff; +static void SuperCapRxCallback(can_instance *_instance) +``` + +`SuperCapRxCallback()`是super cap初始化can实例时的回调函数,用于can接收中断,进行协议解析。 + +## 使用范例 + +初始化时设置如下: + +```c +SuperCap_Init_Config_s capconfig = { + .can_config = { + .can_handle = &hcan1, + .rx_id = 0x301, + .tx_id = 0x302 + }, + .recv_data_len = 4*sizeof(uint16_t), + .send_data_len = sizeof(uint8_t) + }; +SuperCapInstance *ins =SuperCapInit(&capconfig); +``` + + +发送通过`SuperCapSend()`,建议使用强制类型转换: + +```c +uint16_t tx = 0x321; +SuperCapSend(ins, (uint8_t*)&tx); +``` + diff --git a/modules/unicomm/unicomm.c b/modules/unicomm/unicomm.c new file mode 100644 index 0000000..e69de29 diff --git a/modules/unicomm/unicomm.h b/modules/unicomm/unicomm.h new file mode 100644 index 0000000..e69de29 diff --git a/modules/unicomm/unicomm.md b/modules/unicomm/unicomm.md new file mode 100644 index 0000000..0a46e46 --- /dev/null +++ b/modules/unicomm/unicomm.md @@ -0,0 +1,9 @@ +# univsersal communication + +@todo + +unicomm旨在为通信提供一套标准的协议接口,屏蔽底层的硬件差异,使得上层应用可以定制通信协议,包括包长度/可变帧长/帧头尾/校验方式等。 + +不论底层具体使用的是什么硬件接口,实际上每一帧传输完并把数据放在缓冲区之后,就没有任何区别了。 此模块实际上就是对缓冲区的rawdata进行操作,包括查找帧头,计算包长度,校验错误等。 + +完成之后,可以将module/can_comm、视觉的通信协议seasky_protocol和master_process等移除,把原使用了cancomm的应用迁移到此模块。 diff --git a/modules/vofa/vofa.c b/modules/vofa/vofa.c new file mode 100644 index 0000000..298bbcf --- /dev/null +++ b/modules/vofa/vofa.c @@ -0,0 +1,33 @@ +/* + * @Descripttion: + * @version: + * @Author: Chenfu + * @Date: 2022-12-05 12:39:07 + * @LastEditTime: 2022-12-05 14:15:53 + */ +#include "vofa.h" + +/*VOFA浮点协议*/ +void vofa_justfloat_output(float *data, uint8_t num , UART_HandleTypeDef *huart ) +{ + static uint8_t i = 0; + send_float temp[num]; //定义缓冲区数组 + uint8_t send_data[4 * num + 4]; //定义通过串口传出去的数组,数量是所传数据的字节数加上4个字节的尾巴 + for (i = 0; i < num; i++) + { + temp[i].float_t = data[i]; //将所传数据移到缓冲区数组 + } + for (i = 0; i < num; i++) + { + send_data[4 * i] = temp[i].uint8_t[0]; + send_data[4 * i + 1] = temp[i].uint8_t[1]; + send_data[4 * i + 2] = temp[i].uint8_t[2]; + send_data[4 * i + 3] = temp[i].uint8_t[3]; //将缓冲区数组内的浮点型数据转成4个字节的无符号整型,之后传到要通过串口传出的数组里 + } + send_data[4 * num] = 0x00; + send_data[4 * num + 1] = 0x00; + send_data[4 * num + 2] = 0x80; + send_data[4 * num + 3] = 0x7f; //加上协议要求的4个尾巴 + + HAL_UART_Transmit(huart, (uint8_t *)send_data, 4 * num + 4, 100); +} diff --git a/modules/vofa/vofa.h b/modules/vofa/vofa.h new file mode 100644 index 0000000..a6c9dd3 --- /dev/null +++ b/modules/vofa/vofa.h @@ -0,0 +1,21 @@ +/* + * @Descripttion: + * @version: + * @Author: Chenfu + * @Date: 2022-12-05 12:39:18 + * @LastEditTime: 2022-12-05 13:37:36 + */ +#ifndef VOFA_H +#define VOFA_H +#include +#include "bsp_usart.h" +#include "usart.h" + +typedef union +{ + float float_t; + uint8_t uint8_t[4]; +} send_float; +void vofa_justfloat_output(float *data, uint8_t num , UART_HandleTypeDef *huart); + +#endif // !1#define \ No newline at end of file diff --git a/modules/vofa/vofa.md b/modules/vofa/vofa.md new file mode 100644 index 0000000..8782609 --- /dev/null +++ b/modules/vofa/vofa.md @@ -0,0 +1,3 @@ +# vofa + +**除非迫不得已,否则强烈不推荐使用vofa进行调试。应通过bsp_log输出日志,或使用ozone可视化。** \ No newline at end of file diff --git a/openocd_dap.cfg b/openocd_dap.cfg new file mode 100644 index 0000000..2ff8684 --- /dev/null +++ b/openocd_dap.cfg @@ -0,0 +1,13 @@ +# 选择调试器为jlink + +source [find interface/cmsis-dap.cfg] +# source [find interface/jlink.cfg] #使用cmsis-dap硬件进行调试,注意其他地方也要更改 +# OpenOCD作为GDB和硬件调试器的桥梁(为硬件提供抽象,把接口给GDB),支持多种硬件调试器. +# OpenOCD会自动在其根目录的share/openocd/scripts/interface里面寻找对应的配置文件 + +# 选择接口为SWD +transport select swd + +# 选择目标芯片 +source [find target/stm32f4x.cfg] +# OpenOCD会自动在其根目录的share/openocd/scripts/target里面寻找对应的配置文件 \ No newline at end of file diff --git a/openocd_jlink.cfg b/openocd_jlink.cfg new file mode 100644 index 0000000..310a8ba --- /dev/null +++ b/openocd_jlink.cfg @@ -0,0 +1,13 @@ +# 选择调试器为jlink + +source [find interface/jlink.cfg] +# source [find interface/jlink.cfg] #使用jlink硬件进行调试,注意其他地方也要更改 +# OpenOCD作为GDB和硬件调试器的桥梁(为硬件提供抽象,把接口给GDB),支持多种硬件调试器. +# OpenOCD会自动在其根目录的share/openocd/scripts/interface里面寻找对应的配置文件 + +# 选择接口为SWD +transport select swd + +# 选择目标芯片 +source [find target/stm32f4x.cfg] +# OpenOCD会自动在其根目录的share/openocd/scripts/target里面寻找对应的配置文件 \ No newline at end of file diff --git a/startup_stm32f407xx.s b/startup_stm32f407xx.s new file mode 100644 index 0000000..3b99b6b --- /dev/null +++ b/startup_stm32f407xx.s @@ -0,0 +1,505 @@ +/** + ****************************************************************************** + * @file startup_stm32f407xx.s + * @author MCD Application Team + * @brief STM32F407xx Devices vector table for GCC based toolchains. + * This module performs: + * - Set the initial SP + * - Set the initial PC == Reset_Handler, + * - Set the vector table entries with the exceptions ISR address + * - Branches to main in the C library (which eventually + * calls main()). + * After Reset the Cortex-M4 processor is in Thread mode, + * priority is Privileged, and the Stack is set to Main. + ****************************************************************************** + * @attention + * + * Copyright (c) 2017 STMicroelectronics. + * All rights reserved. + * + * This software is licensed under terms that can be found in the LICENSE file + * in the root directory of this software component. + * If no LICENSE file comes with this software, it is provided AS-IS. + * + ****************************************************************************** + */ + + .syntax unified + .cpu cortex-m4 + .fpu softvfp + .thumb + +.global g_pfnVectors +.global Default_Handler + +/* start address for the initialization values of the .data section. +defined in linker script */ +.word _sidata +/* start address for the .data section. defined in linker script */ +.word _sdata +/* end address for the .data section. defined in linker script */ +.word _edata +/* start address for the .bss section. defined in linker script */ +.word _sbss +/* end address for the .bss section. defined in linker script */ +.word _ebss +/* stack used for SystemInit_ExtMemCtl; always internal RAM used */ + +/** + * @brief This is the code that gets called when the processor first + * starts execution following a reset event. Only the absolutely + * necessary set is performed, after which the application + * supplied main() routine is called. + * @param None + * @retval : None +*/ + + .section .text.Reset_Handler + .weak Reset_Handler + .type Reset_Handler, %function +Reset_Handler: + ldr sp, =_estack /* set stack pointer */ + +/* Copy the data segment initializers from flash to SRAM */ + ldr r0, =_sdata + ldr r1, =_edata + ldr r2, =_sidata + movs r3, #0 + b LoopCopyDataInit + +CopyDataInit: + ldr r4, [r2, r3] + str r4, [r0, r3] + adds r3, r3, #4 + +LoopCopyDataInit: + adds r4, r0, r3 + cmp r4, r1 + bcc CopyDataInit + +/* Zero fill the bss segment. */ + ldr r2, =_sbss + ldr r4, =_ebss + movs r3, #0 + b LoopFillZerobss + +FillZerobss: + str r3, [r2] + adds r2, r2, #4 + +LoopFillZerobss: + cmp r2, r4 + bcc FillZerobss + +/* Call the clock system initialization function.*/ + bl SystemInit +/* Call static constructors */ + bl __libc_init_array +/* Call the application's entry point.*/ + bl main + bx lr +.size Reset_Handler, .-Reset_Handler + +/** + * @brief This is the code that gets called when the processor receives an + * unexpected interrupt. This simply enters an infinite loop, preserving + * the system state for examination by a debugger. + * @param None + * @retval None +*/ + .section .text.Default_Handler,"ax",%progbits +Default_Handler: +Infinite_Loop: + b Infinite_Loop + .size Default_Handler, .-Default_Handler +/****************************************************************************** +* +* The minimal vector table for a Cortex M3. Note that the proper constructs +* must be placed on this to ensure that it ends up at physical address +* 0x0000.0000. +* +*******************************************************************************/ + .section .isr_vector,"a",%progbits + .type g_pfnVectors, %object + .size g_pfnVectors, .-g_pfnVectors + + +g_pfnVectors: + .word _estack + .word Reset_Handler + .word NMI_Handler + .word HardFault_Handler + .word MemManage_Handler + .word BusFault_Handler + .word UsageFault_Handler + .word 0 + .word 0 + .word 0 + .word 0 + .word SVC_Handler + .word DebugMon_Handler + .word 0 + .word PendSV_Handler + .word SysTick_Handler + + /* External Interrupts */ + .word WWDG_IRQHandler /* Window WatchDog */ + .word PVD_IRQHandler /* PVD through EXTI Line detection */ + .word TAMP_STAMP_IRQHandler /* Tamper and TimeStamps through the EXTI line */ + .word RTC_WKUP_IRQHandler /* RTC Wakeup through the EXTI line */ + .word FLASH_IRQHandler /* FLASH */ + .word RCC_IRQHandler /* RCC */ + .word EXTI0_IRQHandler /* EXTI Line0 */ + .word EXTI1_IRQHandler /* EXTI Line1 */ + .word EXTI2_IRQHandler /* EXTI Line2 */ + .word EXTI3_IRQHandler /* EXTI Line3 */ + .word EXTI4_IRQHandler /* EXTI Line4 */ + .word DMA1_Stream0_IRQHandler /* DMA1 Stream 0 */ + .word DMA1_Stream1_IRQHandler /* DMA1 Stream 1 */ + .word DMA1_Stream2_IRQHandler /* DMA1 Stream 2 */ + .word DMA1_Stream3_IRQHandler /* DMA1 Stream 3 */ + .word DMA1_Stream4_IRQHandler /* DMA1 Stream 4 */ + .word DMA1_Stream5_IRQHandler /* DMA1 Stream 5 */ + .word DMA1_Stream6_IRQHandler /* DMA1 Stream 6 */ + .word ADC_IRQHandler /* ADC1, ADC2 and ADC3s */ + .word CAN1_TX_IRQHandler /* CAN1 TX */ + .word CAN1_RX0_IRQHandler /* CAN1 RX0 */ + .word CAN1_RX1_IRQHandler /* CAN1 RX1 */ + .word CAN1_SCE_IRQHandler /* CAN1 SCE */ + .word EXTI9_5_IRQHandler /* External Line[9:5]s */ + .word TIM1_BRK_TIM9_IRQHandler /* TIM1 Break and TIM9 */ + .word TIM1_UP_TIM10_IRQHandler /* TIM1 Update and TIM10 */ + .word TIM1_TRG_COM_TIM11_IRQHandler /* TIM1 Trigger and Commutation and TIM11 */ + .word TIM1_CC_IRQHandler /* TIM1 Capture Compare */ + .word TIM2_IRQHandler /* TIM2 */ + .word TIM3_IRQHandler /* TIM3 */ + .word TIM4_IRQHandler /* TIM4 */ + .word I2C1_EV_IRQHandler /* I2C1 Event */ + .word I2C1_ER_IRQHandler /* I2C1 Error */ + .word I2C2_EV_IRQHandler /* I2C2 Event */ + .word I2C2_ER_IRQHandler /* I2C2 Error */ + .word SPI1_IRQHandler /* SPI1 */ + .word SPI2_IRQHandler /* SPI2 */ + .word USART1_IRQHandler /* USART1 */ + .word USART2_IRQHandler /* USART2 */ + .word USART3_IRQHandler /* USART3 */ + .word EXTI15_10_IRQHandler /* External Line[15:10]s */ + .word RTC_Alarm_IRQHandler /* RTC Alarm (A and B) through EXTI Line */ + .word OTG_FS_WKUP_IRQHandler /* USB OTG FS Wakeup through EXTI line */ + .word TIM8_BRK_TIM12_IRQHandler /* TIM8 Break and TIM12 */ + .word TIM8_UP_TIM13_IRQHandler /* TIM8 Update and TIM13 */ + .word TIM8_TRG_COM_TIM14_IRQHandler /* TIM8 Trigger and Commutation and TIM14 */ + .word TIM8_CC_IRQHandler /* TIM8 Capture Compare */ + .word DMA1_Stream7_IRQHandler /* DMA1 Stream7 */ + .word FSMC_IRQHandler /* FSMC */ + .word SDIO_IRQHandler /* SDIO */ + .word TIM5_IRQHandler /* TIM5 */ + .word SPI3_IRQHandler /* SPI3 */ + .word UART4_IRQHandler /* UART4 */ + .word UART5_IRQHandler /* UART5 */ + .word TIM6_DAC_IRQHandler /* TIM6 and DAC1&2 underrun errors */ + .word TIM7_IRQHandler /* TIM7 */ + .word DMA2_Stream0_IRQHandler /* DMA2 Stream 0 */ + .word DMA2_Stream1_IRQHandler /* DMA2 Stream 1 */ + .word DMA2_Stream2_IRQHandler /* DMA2 Stream 2 */ + .word DMA2_Stream3_IRQHandler /* DMA2 Stream 3 */ + .word DMA2_Stream4_IRQHandler /* DMA2 Stream 4 */ + .word ETH_IRQHandler /* Ethernet */ + .word ETH_WKUP_IRQHandler /* Ethernet Wakeup through EXTI line */ + .word CAN2_TX_IRQHandler /* CAN2 TX */ + .word CAN2_RX0_IRQHandler /* CAN2 RX0 */ + .word CAN2_RX1_IRQHandler /* CAN2 RX1 */ + .word CAN2_SCE_IRQHandler /* CAN2 SCE */ + .word OTG_FS_IRQHandler /* USB OTG FS */ + .word DMA2_Stream5_IRQHandler /* DMA2 Stream 5 */ + .word DMA2_Stream6_IRQHandler /* DMA2 Stream 6 */ + .word DMA2_Stream7_IRQHandler /* DMA2 Stream 7 */ + .word USART6_IRQHandler /* USART6 */ + .word I2C3_EV_IRQHandler /* I2C3 event */ + .word I2C3_ER_IRQHandler /* I2C3 error */ + .word OTG_HS_EP1_OUT_IRQHandler /* USB OTG HS End Point 1 Out */ + .word OTG_HS_EP1_IN_IRQHandler /* USB OTG HS End Point 1 In */ + .word OTG_HS_WKUP_IRQHandler /* USB OTG HS Wakeup through EXTI */ + .word OTG_HS_IRQHandler /* USB OTG HS */ + .word DCMI_IRQHandler /* DCMI */ + .word 0 /* CRYP crypto */ + .word HASH_RNG_IRQHandler /* Hash and Rng */ + .word FPU_IRQHandler /* FPU */ + + +/******************************************************************************* +* +* Provide weak aliases for each Exception handler to the Default_Handler. +* As they are weak aliases, any function with the same name will override +* this definition. +* +*******************************************************************************/ + .weak NMI_Handler + .thumb_set NMI_Handler,Default_Handler + + .weak HardFault_Handler + .thumb_set HardFault_Handler,Default_Handler + + .weak MemManage_Handler + .thumb_set MemManage_Handler,Default_Handler + + .weak BusFault_Handler + .thumb_set BusFault_Handler,Default_Handler + + .weak UsageFault_Handler + .thumb_set UsageFault_Handler,Default_Handler + + .weak SVC_Handler + .thumb_set SVC_Handler,Default_Handler + + .weak DebugMon_Handler + .thumb_set DebugMon_Handler,Default_Handler + + .weak PendSV_Handler + .thumb_set PendSV_Handler,Default_Handler + + .weak SysTick_Handler + .thumb_set SysTick_Handler,Default_Handler + + .weak WWDG_IRQHandler + .thumb_set WWDG_IRQHandler,Default_Handler + + .weak PVD_IRQHandler + .thumb_set PVD_IRQHandler,Default_Handler + + .weak TAMP_STAMP_IRQHandler + .thumb_set TAMP_STAMP_IRQHandler,Default_Handler + + .weak RTC_WKUP_IRQHandler + .thumb_set RTC_WKUP_IRQHandler,Default_Handler + + .weak FLASH_IRQHandler + .thumb_set FLASH_IRQHandler,Default_Handler + + .weak RCC_IRQHandler + .thumb_set RCC_IRQHandler,Default_Handler + + .weak EXTI0_IRQHandler + .thumb_set EXTI0_IRQHandler,Default_Handler + + .weak EXTI1_IRQHandler + .thumb_set EXTI1_IRQHandler,Default_Handler + + .weak EXTI2_IRQHandler + .thumb_set EXTI2_IRQHandler,Default_Handler + + .weak EXTI3_IRQHandler + .thumb_set EXTI3_IRQHandler,Default_Handler + + .weak EXTI4_IRQHandler + .thumb_set EXTI4_IRQHandler,Default_Handler + + .weak DMA1_Stream0_IRQHandler + .thumb_set DMA1_Stream0_IRQHandler,Default_Handler + + .weak DMA1_Stream1_IRQHandler + .thumb_set DMA1_Stream1_IRQHandler,Default_Handler + + .weak DMA1_Stream2_IRQHandler + .thumb_set DMA1_Stream2_IRQHandler,Default_Handler + + .weak DMA1_Stream3_IRQHandler + .thumb_set DMA1_Stream3_IRQHandler,Default_Handler + + .weak DMA1_Stream4_IRQHandler + .thumb_set DMA1_Stream4_IRQHandler,Default_Handler + + .weak DMA1_Stream5_IRQHandler + .thumb_set DMA1_Stream5_IRQHandler,Default_Handler + + .weak DMA1_Stream6_IRQHandler + .thumb_set DMA1_Stream6_IRQHandler,Default_Handler + + .weak ADC_IRQHandler + .thumb_set ADC_IRQHandler,Default_Handler + + .weak CAN1_TX_IRQHandler + .thumb_set CAN1_TX_IRQHandler,Default_Handler + + .weak CAN1_RX0_IRQHandler + .thumb_set CAN1_RX0_IRQHandler,Default_Handler + + .weak CAN1_RX1_IRQHandler + .thumb_set CAN1_RX1_IRQHandler,Default_Handler + + .weak CAN1_SCE_IRQHandler + .thumb_set CAN1_SCE_IRQHandler,Default_Handler + + .weak EXTI9_5_IRQHandler + .thumb_set EXTI9_5_IRQHandler,Default_Handler + + .weak TIM1_BRK_TIM9_IRQHandler + .thumb_set TIM1_BRK_TIM9_IRQHandler,Default_Handler + + .weak TIM1_UP_TIM10_IRQHandler + .thumb_set TIM1_UP_TIM10_IRQHandler,Default_Handler + + .weak TIM1_TRG_COM_TIM11_IRQHandler + .thumb_set TIM1_TRG_COM_TIM11_IRQHandler,Default_Handler + + .weak TIM1_CC_IRQHandler + .thumb_set TIM1_CC_IRQHandler,Default_Handler + + .weak TIM2_IRQHandler + .thumb_set TIM2_IRQHandler,Default_Handler + + .weak TIM3_IRQHandler + .thumb_set TIM3_IRQHandler,Default_Handler + + .weak TIM4_IRQHandler + .thumb_set TIM4_IRQHandler,Default_Handler + + .weak I2C1_EV_IRQHandler + .thumb_set I2C1_EV_IRQHandler,Default_Handler + + .weak I2C1_ER_IRQHandler + .thumb_set I2C1_ER_IRQHandler,Default_Handler + + .weak I2C2_EV_IRQHandler + .thumb_set I2C2_EV_IRQHandler,Default_Handler + + .weak I2C2_ER_IRQHandler + .thumb_set I2C2_ER_IRQHandler,Default_Handler + + .weak SPI1_IRQHandler + .thumb_set SPI1_IRQHandler,Default_Handler + + .weak SPI2_IRQHandler + .thumb_set SPI2_IRQHandler,Default_Handler + + .weak USART1_IRQHandler + .thumb_set USART1_IRQHandler,Default_Handler + + .weak USART2_IRQHandler + .thumb_set USART2_IRQHandler,Default_Handler + + .weak USART3_IRQHandler + .thumb_set USART3_IRQHandler,Default_Handler + + .weak EXTI15_10_IRQHandler + .thumb_set EXTI15_10_IRQHandler,Default_Handler + + .weak RTC_Alarm_IRQHandler + .thumb_set RTC_Alarm_IRQHandler,Default_Handler + + .weak OTG_FS_WKUP_IRQHandler + .thumb_set OTG_FS_WKUP_IRQHandler,Default_Handler + + .weak TIM8_BRK_TIM12_IRQHandler + .thumb_set TIM8_BRK_TIM12_IRQHandler,Default_Handler + + .weak TIM8_UP_TIM13_IRQHandler + .thumb_set TIM8_UP_TIM13_IRQHandler,Default_Handler + + .weak TIM8_TRG_COM_TIM14_IRQHandler + .thumb_set TIM8_TRG_COM_TIM14_IRQHandler,Default_Handler + + .weak TIM8_CC_IRQHandler + .thumb_set TIM8_CC_IRQHandler,Default_Handler + + .weak DMA1_Stream7_IRQHandler + .thumb_set DMA1_Stream7_IRQHandler,Default_Handler + + .weak FSMC_IRQHandler + .thumb_set FSMC_IRQHandler,Default_Handler + + .weak SDIO_IRQHandler + .thumb_set SDIO_IRQHandler,Default_Handler + + .weak TIM5_IRQHandler + .thumb_set TIM5_IRQHandler,Default_Handler + + .weak SPI3_IRQHandler + .thumb_set SPI3_IRQHandler,Default_Handler + + .weak UART4_IRQHandler + .thumb_set UART4_IRQHandler,Default_Handler + + .weak UART5_IRQHandler + .thumb_set UART5_IRQHandler,Default_Handler + + .weak TIM6_DAC_IRQHandler + .thumb_set TIM6_DAC_IRQHandler,Default_Handler + + .weak TIM7_IRQHandler + .thumb_set TIM7_IRQHandler,Default_Handler + + .weak DMA2_Stream0_IRQHandler + .thumb_set DMA2_Stream0_IRQHandler,Default_Handler + + .weak DMA2_Stream1_IRQHandler + .thumb_set DMA2_Stream1_IRQHandler,Default_Handler + + .weak DMA2_Stream2_IRQHandler + .thumb_set DMA2_Stream2_IRQHandler,Default_Handler + + .weak DMA2_Stream3_IRQHandler + .thumb_set DMA2_Stream3_IRQHandler,Default_Handler + + .weak DMA2_Stream4_IRQHandler + .thumb_set DMA2_Stream4_IRQHandler,Default_Handler + + .weak ETH_IRQHandler + .thumb_set ETH_IRQHandler,Default_Handler + + .weak ETH_WKUP_IRQHandler + .thumb_set ETH_WKUP_IRQHandler,Default_Handler + + .weak CAN2_TX_IRQHandler + .thumb_set CAN2_TX_IRQHandler,Default_Handler + + .weak CAN2_RX0_IRQHandler + .thumb_set CAN2_RX0_IRQHandler,Default_Handler + + .weak CAN2_RX1_IRQHandler + .thumb_set CAN2_RX1_IRQHandler,Default_Handler + + .weak CAN2_SCE_IRQHandler + .thumb_set CAN2_SCE_IRQHandler,Default_Handler + + .weak OTG_FS_IRQHandler + .thumb_set OTG_FS_IRQHandler,Default_Handler + + .weak DMA2_Stream5_IRQHandler + .thumb_set DMA2_Stream5_IRQHandler,Default_Handler + + .weak DMA2_Stream6_IRQHandler + .thumb_set DMA2_Stream6_IRQHandler,Default_Handler + + .weak DMA2_Stream7_IRQHandler + .thumb_set DMA2_Stream7_IRQHandler,Default_Handler + + .weak USART6_IRQHandler + .thumb_set USART6_IRQHandler,Default_Handler + + .weak I2C3_EV_IRQHandler + .thumb_set I2C3_EV_IRQHandler,Default_Handler + + .weak I2C3_ER_IRQHandler + .thumb_set I2C3_ER_IRQHandler,Default_Handler + + .weak OTG_HS_EP1_OUT_IRQHandler + .thumb_set OTG_HS_EP1_OUT_IRQHandler,Default_Handler + + .weak OTG_HS_EP1_IN_IRQHandler + .thumb_set OTG_HS_EP1_IN_IRQHandler,Default_Handler + + .weak OTG_HS_WKUP_IRQHandler + .thumb_set OTG_HS_WKUP_IRQHandler,Default_Handler + + .weak OTG_HS_IRQHandler + .thumb_set OTG_HS_IRQHandler,Default_Handler + + .weak DCMI_IRQHandler + .thumb_set DCMI_IRQHandler,Default_Handler + + .weak HASH_RNG_IRQHandler + .thumb_set HASH_RNG_IRQHandler,Default_Handler + + .weak FPU_IRQHandler + .thumb_set FPU_IRQHandler,Default_Handler diff --git a/stm32.jflash b/stm32.jflash new file mode 100644 index 0000000..d9c38ea --- /dev/null +++ b/stm32.jflash @@ -0,0 +1,82 @@ + AppVersion = 72202 + FileVersion = 2 +[GENERAL] + aATEModuleSel[10] = 0,0,0,0,0,0,0,0,0,0 + ConnectMode = 0 + CurrentFile = "" + DataFileSAddr = 0x00000000 + GUIMode = 0 + HostName = "" + TargetIF = 1 + USBPort = 0 + USBSerialNo = 0x00000000 + UseATEModuleSelection = 0 +[JTAG] + IRLen = 0 + MultipleTargets = 0 + NumDevices = 0 + Speed0 = 4000 + Speed1 = 4000 + TAP_Number = 0 + UseAdaptive0 = 0 + UseAdaptive1 = 0 + UseMaxSpeed0 = 0 + UseMaxSpeed1 = 0 +[CPU] + NumInitSteps = 1 + InitStep0_Action = "Reset" + InitStep0_Value0 = 0x00000000 + InitStep0_Value1 = 0x00000000 + InitStep0_Comment = "Reset and halt target" + NumExitSteps = 0 + UseScriptFile = 0 + ScriptFile = "" + UseRAM = 1 + RAMAddr = 0x20000000 + RAMSize = 0x00020000 + CheckCoreID = 1 + CoreID = 0x4BA00477 + CoreIDMask = 0x0F000FFF + UseAutoSpeed = 0x00000001 + ClockSpeed = 0x00000000 + EndianMode = 0 + ChipName = "ST STM32F407IG" +[FLASH] + aRangeSel[1] = 0-11 + BankName = "Internal flash" + BankSelMode = 1 + BaseAddr = 0x08000000 + NumBanks = 1 +[PRODUCTION] + AutoPerformsDisconnect = 0 + AutoPerformsErase = 1 + AutoPerformsProgram = 1 + AutoPerformsSecure = 0 + AutoPerformsStartApp = 0 + AutoPerformsUnsecure = 0 + AutoPerformsVerify = 1 + EnableFixedVTref = 0 + EnableTargetPower = 0 + EraseType = 1 + FixedVTref = 0x00000CE4 + MonitorVTref = 0 + MonitorVTrefMax = 0x0000157C + MonitorVTrefMin = 0x000003E8 + OverrideTimeouts = 0 + ProgramSN = 0 + SerialFile = "" + SNAddr = 0x00000000 + SNInc = 0x00000001 + SNLen = 0x00000004 + SNListFile = "" + SNValue = 0x00000001 + StartAppType = 0 + TargetPowerDelay = 0x00000014 + TimeoutErase = 0x00003A98 + TimeoutProgram = 0x00002710 + TimeoutVerify = 0x00002710 + VerifyType = 1 +[PERFORMANCE] + DisableSkipBlankDataOnProgram = 0x00000000 + PerfromBlankCheckPriorEraseChip = 0x00000001 + PerfromBlankCheckPriorEraseSelectedSectors = 0x00000001 diff --git a/task.ps1 b/task.ps1 new file mode 100644 index 0000000..d5f0b9e --- /dev/null +++ b/task.ps1 @@ -0,0 +1,64 @@ +# 推荐安装powershell7 以获得更好的shell体验! +# 可以添加task.json,或在makefile中增加伪构建目标然后运行make xxx + +JLinkGDBServer: + + $(Q)JLinkGDBServer -select USB -device $(CHIP) \ + + -endian little -if SWD -speed 4000 -noir -LocalhostOnly + + + +debug: + + $(Q)make + + $(Q)echo target remote localhost\:2331 > gdb.gdb + + $(Q)echo monitor reset >> gdb.gdb + + $(Q)echo monitor halt >> gdb.gdb + + $(Q)echo load >> gdb.gdb + + $(Q)echo b main >> gdb.gdb + + $(Q)echo - >> gdb.gdb + + $(Q)echo c >> gdb.gdb + + $(Q)-$(GDB) $(BUILD)/$(TARGET).elf --command=gdb.gdb + + $(Q)$(RM) gdb.gdb + +debug_ozone: + $(Q)ozone ./debug_ozone.jdebug + + +download: + + $(Q)make + + $(Q)echo "h" > jlink.jlink + + $(Q)echo "loadfile" $(BUILD)/$(TARGET).hex >> jlink.jlink + + $(Q)echo "r" >> jlink.jlink + + $(Q)echo "qc" >> jlink.jlink + + $(Q)$(JLINKEXE) -device $(CHIP) -Speed 4000 -IF SWD -CommanderScript jlink.jlink + + $(Q)$(RM) jlink.jlink + + + +reset: + + $(Q)echo "r" >> jlink.jlink + + $(Q)echo "qc" >> jlink.jlink + + $(Q)$(JLINKEXE) -device $(CHIP) -Speed 4000 -IF SWD -CommanderScript jlink.jlink + + $(Q)$(RM) jlink.jlink \ No newline at end of file