打印

我的串口只能发送不能接收,大家看看什么问题?

[复制链接]
417|0
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
王将|  楼主 | 2018-7-11 20:54 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
#include "usart.h"

void Init_NVIC(void);

void Init_USART(void)
{
GPIO_InitTypeDefGPIO_InitStructure;
USART_InitTypeDefUSART_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9,GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10GPIO_AF_USART1);
//TX引脚初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//RX引脚初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//初始化串口
USART_InitStructure.USART_BaudRate = 115200;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_Mode = USART_Mode_Rx|USART_Mode_Tx;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;

USART_Init(USART1,&USART_InitStructure);
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//使能串口接收中断
USART_Cmd(USART1,ENABLE);
Init_NVIC();
}

void Init_NVIC(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_Init(&NVIC_InitStructure);
}
/********************************发送一个字符************************************/
void Usart_SendByte(USART_TypeDef* pUSARTx, uint8_t ch)
{
USART_SendData(pUSARTx, ch);
while(USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET);
}

/********************************发送字符串************************************/
void Usart_SendString(USART_TypeDef* pUSARTx, char *str)
{
unsigned int k = 0;
do
{
Usart_SendByte(pUSARTx,*(str+k));
k++;
}
while(*(str+k) != '\0')
while(USART_GetFlagStatus(pUSARTx, USART_FLAG_TXE) == RESET)
{}/等待发送完成,
}

void USART1_IRQHandler()
{
uint8_t UC;
if(USART_GetITStatus(USART1,USART_IT_RXNE) != RESET)
{
UC = USART_ReceiveData(USART1);
USART_SendData(USART1,UC);
}


//重定向c库函数printf到串口,重定向后可使用printf函数
int fputc(int ch, FILE *f)
{
/* 发送一个字节数据到串口 */
USART_SendData(DEBUG_USART, (uint8_t) ch);
/* 等待发送完毕 */
while (USART_GetFlagStatus(DEBUG_USART, USART_FLAG_TXE) == RESET);return (ch);
}

//重定向c库函数scanf到串口,重写向后可使用scanf、getchar等函数
int fgetc(FILE *f)
{
/* 等待串口输入数据 */
while (USART_GetFlagStatus(DEBUG_USART, USART_FLAG_RXNE) == RESET);

return (int)USART_ReceiveData(DEBUG_USART);
}

使用特权

评论回复

相关帖子

发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

419

主题

419

帖子

0

粉丝