|
我使用的是普中科技STM32-PZ6806L开发板,在学习USART章节的时候,想使用蓝牙(HC-42)通过单片机与我电脑通信,但是在测试USART2的时候遇到了bug,编写的程序与给的例程区别不大,但编译通过后,烧到板子上时,并不能正常收发字符串。usart2.c代码如下,望解答:
- #include "usart.h"
- int fputc(int ch,FILE *p) //函数默认的,在使用printf函数时自动调用
- {
- USART_SendData(USART2,(u8)ch);
- while(USART_GetFlagStatus(USART2,USART_FLAG_TC)==RESET);
- return ch;
- }
- void USART2_Init(u32 bound)
- {
- //GPIO端口设置
- GPIO_InitTypeDef GPIO_InitStructure;
- USART_InitTypeDef USART_InitStructure;
- NVIC_InitTypeDef NVIC_InitStructure;
-
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
- RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); //打开时钟
- RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
-
- /* 配置GPIO的模式和IO口 */
- GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2;//TX //串口输出PA2
- GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
- GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; //复用推挽输出
- GPIO_Init(GPIOA,&GPIO_InitStructure); // 初始化串口输入IO
- GPIO_InitStructure.GPIO_Pin=GPIO_Pin_3;//RX //串口输入PA3
- GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING; //模拟输入
- GPIO_Init(GPIOA,&GPIO_InitStructure); // 初始化GPIO
-
-
- //USART2 初始化设置
- USART_InitStructure.USART_BaudRate = bound;//波特率设置
- USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
- 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(USART2, &USART_InitStructure); //初始化串口2
-
- USART_Cmd(USART2, ENABLE); //使能串口2
-
- USART_ClearFlag(USART2, USART_FLAG_TC);
-
- USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);//开启相关中断
- //Usart2 NVIC 配置
- NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;//串口2中断通道
- NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3;//抢占优先级3
- NVIC_InitStructure.NVIC_IRQChannelSubPriority =3; //子优先级3
- NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
- NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器
复制代码 main.c如下:
- #include "system.h"
- #include "SysTick.h"
- #include "led.h"
- #include "usart.h"
- int main()
- {
- u8 i=0;
- char str[]="收到!";
- SysTick_Init(72);
- NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //中断优先级分组 分2组
- LED_Init();
- USART2_Init(9600);
-
- while(1)
- {
- i++;
- if(i%20==0)
- {
- led1=!led1;
-
- printf("%s\r\n",str); //输出字符串str
-
- }
- delay_ms(10);
- }
- }
复制代码
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|