RT-Thread 正点原子阿波罗STM32F429IGT6 USB虚拟串口(从机)(SLAVE)
一、硬件环境
阿波罗USB虚拟串口(USB_SLAVE),硬件连接上为VCC、GND、USB_D+(PA11)、USB_D-(PA12);其中USB的电源需要经过PCF8574进行控制,但经过实际测试,该芯片USB_PWR默认即为高电平输出;
二、软件配置
①、创建RT-Thread工程;
②、打开CubeMX;
2.1打开时钟
2.2选择USB_OTG_FS的Mode为Device_Only
2.3 选择USB_DEVICE的Class For FS IP为VPC
2.4时钟设置,这里的时钟设置必须为48MHz
2.5勾选不生成main()
③、在项目中,找到cubemx文件夹,将 usbd_conf.c文件中的void HAL_PCD_MspInit(PCD_HandleTypeDef* pcdHandle)复制到board.c下;并将cubemx目录下没用的文件进行删除;
④、board.h中打开配置
⑤、stm32f4xx_hal_conf_bak.h中打开HAL_PCD_MODULE_ENABLED
⑥、在RT_Thread Setting 中进行相关参数设置,并保存;
⑦、更新main.c文件如下:
1 #include <rtthread.h> 2 3 #define DBG_TAG "main" 4 #define DBG_LVL DBG_LOG 5 #include <rtdbg.h> 6 7 /* 用于接收消息的信号量 */ 8 static struct rt_semaphore rx_sem; 9 static rt_device_t serial; 10 11 /* 接收数据回调函数 */ 12 static rt_err_t uart_input(rt_device_t dev, rt_size_t size) 13 14 { 15 /*串口接收到数据后产生中断,调用此回调函数,然后发送接收信号量 */ 16 rt_sem_release(&rx_sem); 17 return RT_EOK; 18 } 19 20 static void serial_thread_entry(void* parameter) 21 { 22 char ch; 23 while (1) 24 { 25 /* 从串口读取一个字节的数据,没有读取到则等待接收信号量 */ 26 while (rt_device_read(serial, 0, &ch, 1) != 1) 27 { 28 /* 阻塞等待接收信号量,等到信号量后再次读取数据 */ 29 rt_sem_take(&rx_sem, RT_WAITING_FOREVER); 30 } 31 /* 读取到的数据通过串口错位输出 */ 32 rt_kprintf("%c",ch); 33 rt_device_write(serial, 0, &ch, 1); 34 } 35 } 36 37 char *buf = "SUNWARD\r\n"; 38 char *ch = RT_NULL; 39 40 int main(void) 41 { 42 serial = rt_device_find("vcom"); 43 if (!serial) 44 { 45 rt_kprintf("find failed0!"); 46 return RT_ERROR; 47 } 48 49 rt_device_init(serial); 50 51 if (rt_device_open(serial, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX) != RT_EOK) 52 { 53 rt_kprintf("rt_device_open failed!"); 54 } 55 56 //初始化信号量 57 rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO); 58 59 // 设置接收回调函数 60 rt_device_set_rx_indicate(serial, uart_input); 61 62 rt_thread_t thread = rt_thread_create("serial", serial_thread_entry, RT_NULL, 1024, 10, 100); 63 64 if (thread != RT_NULL) 65 { 66 67 rt_thread_startup(thread); 68 } 69 70 while (1) 71 { 72 rt_device_write(serial, 0, buf, rt_strlen(buf)); 73 rt_kprintf("Hello RT-Thread!\r\n"); 74 rt_thread_mdelay(1000); 75 } 76 return RT_EOK; 77 }
⑧、此时在设备管理器中可看到device驱动设备
⑨、打开串口助手,勾选DTR;通过USB虚拟串口可正常收发数据;
本文来自博客园,作者:伽椰子真可爱,转载请注明原文链接:https://www.cnblogs.com/jiayezi/p/17522839.html