美好的一天。
我正在尝试从Stm32 std库运行UART示例脚本,但似乎不起作用。
我正在使用这样的板:
通过USART1上传固件。
USART初始化代码:
#include <stm32f10x.h>
#include <misc.h>
volatile char received_string[MAX_STRLEN+1];
void Delay(__IO uint32_t nCount) {
while(nCount--) {
}
}
void init_USART1(uint32_t baudrate){
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStruct);
USART_InitStruct.USART_BaudRate = baudrate;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStruct);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void USART_puts(USART_TypeDef* USARTx, volatile char *s){
while(*s){
while( !(USARTx->SR & 0x00000040) );
USART_SendData(USARTx, *s);
*s++;
}
}
int main(void) {
init_USART1(9600); // initialize USART1 @ 9600 baud
USART_puts(USART1, "Init complete! Hello World!\r\n"); // just send a message to indicate that it works
while (1){
/*
* You can do whatever you want in here
*/
}
}
void USART1_IRQHandler(void){
// check if the USART1 receive interrupt flag was set
if( USART_GetITStatus(USART1, USART_IT_RXNE) ){
static uint8_t cnt = 0; // this counter is used to determine the string length
char t = USART1->DR; // the character from the USART1 data register is saved in t
// check if the received character is not the LF character (used to determine end of string)
// or the if the maximum string length has been been reached
if( (t != '\n') && (cnt < MAX_STRLEN) ){
received_string[cnt] = t;
cnt++;
}
else{ // otherwise reset the character counter and print the received string
cnt = 0;
USART_puts(USART1, received_string);
}
}
}
在未启用NVIC的情况下,USART1端口正在工作。
最佳答案
您可以尝试将USART_puts()函数更改为:
void USART_puts(USART_TypeDef* USARTx, volatile char *s){
while(*s)
{
while(USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET);// Wait the set of TXE
USART_SendData(USART1, *(s++));
while(USART_GetFlagStatus(USART1, USART_FLAG_TC) == RESET);// Wait the end of transmit
}
}
关于c - stm32f103c8t6 USART1中断不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43541797/