新手上路
- 积分
- 35
- 金钱
- 35
- 注册时间
- 2020-1-1
- 在线时间
- 6 小时
|
1金钱
今天学习了USART发送、接收数据及使用中断。一开始尝试发送数据,电脑端接收正常,但在尝试接收数据却出现乱码。为找到原因,我写了一段USART1发送从电脑端接收到的数据,并控制LED的代码,我尝试从电脑端发送0x00、0x01,但接收到的数据什么都有,每次上电都不一样,比如:6C 74 D4 74 3C 74 ……
代码如下,请各位大神帮忙分析分析!
void RCC_Config(void);
void UART_Config(void);
void NVIC_Config(void);
void GPIO_Config(void);
void delay(void);
void Exchange_LED0(void);
int main()
{
RCC_Config();
GPIO_Config();
UART_Config();
NVIC_Config();
GPIO_WriteBit(GPIOB, GPIO_Pin_5, Bit_RESET);
while(1)
{
delay();
}
}
void RCC_Config()
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOE, ENABLE);
}
void GPIO_Config()
{
GPIO_InitTypeDef GPIO_InitStructure;
//USART1_TX GPIOA.9
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//USART1_RX GPIOA.10
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//LED0 GPIOB.5
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//LED1 GPIOE.5
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOE, &GPIO_InitStructure);
}
void UART_Config()
{
USART_DeInit(USART1);
USART_InitTypeDef USART_InitStructure;
USART_InitStructure.USART_BaudRate = 9600;
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);
USART_Cmd(USART1, ENABLE);
}
void NVIC_Config()
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x02;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}
void delay(void)
{
int i = 0x1FFFFF;
while(i--);
}
void USART1_IRQHandler(void)
{
if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
{
USART_ClearITPendingBit(USART1, USART_IT_RXNE);
uint16_t data = USART_ReceiveData(USART1);
switch(data)
{
case 0x00:
GPIO_WriteBit(GPIOE, GPIO_Pin_5, Bit_SET);
break;
case 0x01:
GPIO_WriteBit(GPIOE, GPIO_Pin_5, Bit_RESET);
break;
}
Exchange_LED0();
USART_SendData(USART1, data);
}
}
void Exchange_LED0()
{
uint8_t status = GPIO_ReadOutputDataBit(GPIOB, GPIO_Pin_5);
if(status == Bit_SET)
status = Bit_RESET;
else
status = Bit_SET;
GPIO_WriteBit(GPIOB, GPIO_Pin_5, (BitAction)status);
}
|
|