无法在STM32F072RBT6上连接/配置USART

时间:2015-12-08 22:05:34

标签: serial-port arm stm32 usart

我正在尝试将STM32F072RBT6模块连接到pc并通过USART发送数据。我对此很陌生,我不了解一些事情。不幸的是,这个模块没有可用的例子。我用usb线连接stm和pc。这是我的代码:

GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStructure;

void send_char(char c)
{
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
USART_SendData(USART2, c);
}

void send_string(const char* s) 
{
while (*s)
    send_char(*s++);
}

GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStructure;
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

GPIO_StructInit(&GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_Init(GPIOA, &GPIO_InitStruct);
//GPIO_PinAFConfig(GPIOA, GPIO_PinSource2,GPIO_AF_1);  //tried this too


GPIO_InitStruct.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
//GPIO_PinAFConfig(GPIOA, GPIO_PinSource3,GPIO_AF_1);

我读到Rx引脚需要配置为浮动输入,但没有 这样的模式设置。我还尝试使用GPIO_Mode_AF并注释了PinAFConfig。

GPIO_Init(GPIOA, &GPIO_InitStruct);
USART_StructInit(&USART_InitStructure);
USART_InitStructure.USART_BaudRate = 9600;              
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;   
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_WordLength=USART_WordLength_8b;       
USART_Init(USART2, &USART_InitStructure);

USART_Cmd(USART2, ENABLE);

while (1) {
    send_string("Hello world!\r\n");
}

}

我试图在teraterm中看到任何结果。我注意到当我意外地触摸了针板时,终端上出现了一些字符。这是一个连接有效但我配置错误的标志吗? 我也尝试用USART1和它的引脚做这个,但什么都没发生。你能

吗?

1 个答案:

答案 0 :(得分:0)

有例子

e.g。 Projects/STM32F072RB-Nucleo/Examples/UART下的STM32CubeF0

虽然他们使用的是USART1,但你必须对它们进行一些调整。

如果没有例子

然后您可以使用STM32CubeMX生成一个。使用MCU启动项目,单击USART2(左侧)旁边的三角形,选择Mode Asynchronous,然后使用Project / Generate Code,就可以了。