本代码 基于楼主上一贴发表 帖子构建的工程:https://www.stmcu.org.cn/module/forum/thread-598980-1-1.html
[url=CUBEMX 简单创建 FREERTOS 和RTX 工程,顺便讨论一处代码 https://www.stmcu.org.cn/module/foru ... 980&fromuid=1888292 (出处: 意法半导体STM32/STM8技术社区)]CUBEMX 简单创建 FREERTOS 和RTX 工程,顺便讨论一处代码 https://www.stmcu.org.cn/module/foru ... 980&fromuid=1888292 (出处: 意法半导体STM32/STM8技术社区)[/url]
添加了一个 os_usart.c的 文件
内容
如下
- #include "stm32f0xx_hal.h"
- #include "cmsis_os.h"
- #include "stdio.h"
- extern UART_HandleTypeDef huart2;
- osSemaphoreId usart_sem;
- #define Buffersize 10
- struct usart_buf_t
- {
- char buffer[Buffersize];
- int rx_index;
- int save_index;
- }usart_buf;
- void os_usart_init()
- {
- usart_sem =osSemaphoreCreate(0,1);
- usart_buf.rx_index=0;
- usart_buf.save_index=0;
- osSemaphoreWait(usart_sem,osWaitForever);
-
- HAL_NVIC_SetPriority(USART2_IRQn, 0, 1);
- HAL_NVIC_EnableIRQ(USART2_IRQn);
- __HAL_UART_ENABLE_IT(&huart2, UART_IT_RXNE);
- }
- void USART2_IRQHandler()
- {
- if((__HAL_UART_GET_IT(&huart2, UART_IT_RXNE) != RESET) && (__HAL_UART_GET_IT_SOURCE(&huart2, UART_IT_RXNE) != RESET))
- {
- usart_buf.buffer[usart_buf.rx_index++]=huart2.Instance->RDR;
- if(usart_buf.rx_index==Buffersize)usart_buf.rx_index=0;
- if(usart_buf.rx_index==usart_buf.save_index)
- {
- usart_buf.save_index++;
- if(usart_buf.save_index==Buffersize)usart_buf.save_index=0;
- }
- osSemaphoreRelease(usart_sem);
- /* Clear RXNE interrupt flag */
- __HAL_UART_SEND_REQ(&huart2, UART_RXDATA_FLUSH_REQUEST);
- }
- }
- static unsigned int usart_timeout=osWaitForever;
- void Set_usart_timeout(int timeout)
- {
- usart_timeout=timeout;
- }
- int fgetc(FILE*f)
- {
- int ch;
- if(usart_buf.rx_index!=usart_buf.save_index)
- {
- ch=usart_buf.buffer[usart_buf.save_index++];
- if(usart_buf.save_index==Buffersize)
- {
- usart_buf.save_index=0;
- }
- return ch;
- }
- else
- {
- if(osSemaphoreWait(usart_sem,usart_timeout)==osOK)
- {
- return fgetc(f);
- }
- else
- {
- return 0;
- }
- }
- }
- int fputc(int ch,FILE*f)
- {
- while(!(huart2.Instance->ISR&UART_FLAG_TXE));
- huart2.Instance->TDR=ch;
- }
复制代码
下面是主函数 增加内容
作用为 通过scanf 扫描串口 数据到 i
将收到数据 以0x-- 16进制 打印
使用 超级终端 运行程序 键盘输入 10 Enter 可见超级中端 输出0xa
scanf阻塞 程序运行的过程中 仍然看见 072 LED闪烁
如此可见 使用OS 接收串口比 没有OS的优势~~
例如 用这种方式操作 GSM模块 printf("AT+XX");
发送 AT指令之后
用scanf 接收模块回复
在此过程中 你的设备仍然可以通过其他线程 响应 按键或者 更新屏幕 显示~~
|
不知道 你有没有研究过 HAL 的 中断 API
运行机制是这样的 设置buffer地址和 需要接收的 数据 数量(这个是重点)!
然后会从 串口发送一个字节出去 HAL称之为 DUMMY_DATA 这不是 所希望的吧?
然后 需要所设置的 数量 数据接收完毕 才运行 callback函数 显然 通信过程中不知道需要接收多少字节?
总不能设置为1吧? 那HAL又相对于 自己写个中断函数 又显得臃肿了 很多~~
HAL 库的 中断接收 是 主动调用的
也就是主动接收
我这里需要被动接收的
上一贴的 地址在 帖子 顶端呀
不太懂,估计楼主也是个小白。