ch32v003记录2,串口通信例程
···#include “ch32v00x.h”#include stdio.h/* 发送一个字符 */void uart_putc(char ch){while (USART_GetFlagStatus(USART1, USART_FLAG_TC) RESET);USART_SendData(USART1, ch);}/* 接收一个字符阻塞 */char uart_getc(void){while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) RESET);return (char)USART_ReceiveData(USART1);}/* UART 初始化 */void uart_init(uint32_t baudrate){GPIO_InitTypeDef GPIO_InitStructure {0};USART_InitTypeDef USART_InitStructure {0};/* ① 使能外设时钟 */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD | RCC_APB2Periph_USART1, ENABLE); /* ② 配置 GPIO * PD5 — USART1_TX (复用推挽输出, 10MHz) * PD6 — USART1_RX (浮空输入) */ // TX — PD5 pin8 GPIO_InitStructure.GPIO_Pin GPIO_Pin_5; GPIO_InitStructure.GPIO_Speed GPIO_Speed_10MHz; GPIO_InitStructure.GPIO_Mode GPIO_Mode_AF_PP; GPIO_Init(GPIOD, GPIO_InitStructure); // RX — PD6 pin1 GPIO_InitStructure.GPIO_Pin GPIO_Pin_6; GPIO_InitStructure.GPIO_Mode GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOD, GPIO_InitStructure); /* ③ 配置 USART1 参数 */ USART_InitStructure.USART_BaudRate baudrate; USART_InitStructure.USART_WordLength USART_WordLength_8b; USART_InitStructure.USART_StopBits USART_StopBits_1; USART_InitStructure.USART_Parity USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART1, USART_InitStructure); /* ④ 使能 USART1 */ USART_Cmd(USART1, ENABLE);}/* 主函数 */int main(void){uint8_t rx_buf[5];/* 系统时钟默认 HSI 24MHz如有需要可另行配置 */ SystemInit(); uart_init(115200); printf(CH32V003J4M6 UART Test——Hello!\r\n); printf(waiting 5 bytes...\r\n); while (1) { for (int i 0; i 5; i) { rx_buf[i] uart_getc(); } printf(Recv 5 bytes: ); for (int i 0; i 5; i) { uart_putc(rx_buf[i]); } printf(\r\n); }}···pin1.和pin8要注意的是叫tx和rx的互换
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2574013.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!