接线
GPS
- V(VCC)插在 STM32 3.3V引脚
- G(GND)插在 STM32 G(DNG)引脚
- R(RX)空
- T(TX)空
注意现在先不要插GPS R(RX) T(TX)引脚
TTL
- TTL RX 插在 STM32 A9 引脚
- TTL TX 插在 STM32 A10 引脚
代码示例
#include "stm32f10x.h"
#include "stdio.h"
#include "string.h"
#define BAUDRATE 38400
#define UART1_RX_PIN GPIO_Pin_10
#define UART1_TX_PIN GPIO_Pin_9
void USART1_Init(void);
void USART1_PrintChar(uint8_t ch);
void USART1_PrintString(const char *str);
void USART1_IRQHandler(void)
{
if (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == SET)
{
// 读取接收到的数据
uint8_t data = USART_ReceiveData(USART1);
// 打印数据到串口
USART1_PrintString("ABCD:");
USART1_PrintChar(data);
}
}
int main(void)
{
// 初始化USART1
USART1_Init();
while (1)
{
}
}
void USART1_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = UART1_TX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = UART1_RX_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_InitStructure);
USART_InitStructure.USART_BaudRate = BAUDRATE;
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_ITConfig(USART1, USART_IT_RXNE, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART1, ENABLE);
}
void USART1_PrintChar(uint8_t ch)
{
USART_SendData(USART1, ch);
while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)
{
}
}
void USART1_PrintString(const char *str)
{
while (*str)
{
USART1_PrintChar(*str++);
}
}
- 将上面的代码编程到STM32板子上打开串口工具选择38400波特率
- 将GPS的T(TX)插到A10引脚
- 将GPS的R(RX)插到A9引脚
- 打开串口,按一下STM32板子上的按钮即可