stm32f103c8t6串口2发送AT+LOCATION=1指令给EC01g,并解析GPS数据,stm32库函数版本的代码
时间: 2023-12-06 17:39:44 浏览: 99
以下是使用STM32库函数版本的代码,使用USART2发送AT指令,接收EC01G模块返回的GPS数据并进行解析:
```c
#include "stm32f10x.h"
#include <stdio.h>
#include <string.h>
#define GPS_BUFF_SIZE 256
uint8_t gps_buff[GPS_BUFF_SIZE];
uint8_t gps_index = 0;
void USART2_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA, &GPIO_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(USART2, &USART_InitStructure);
USART_Cmd(USART2, ENABLE);
}
void USART2_SendString(char *str)
{
while (*str)
{
USART_SendData(USART2, *str++);
while (USART_GetFlagStatus(USART2, USART_FLAG_TC) == RESET);
}
}
void USART2_IRQHandler(void)
{
if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
{
uint8_t data = USART_ReceiveData(USART2);
if (data == '$') // GPS数据的起始符
{
gps_index = 0;
}
gps_buff[gps_index++] = data;
if (data == '\n') // GPS数据的结束符
{
gps_buff[gps_index] = '\0';
if (strstr((const char *)gps_buff, "$GPRMC") != NULL) // 解析GPRMC语句
{
char *token = strtok((char *)gps_buff, ",");
uint8_t i = 0;
while (token != NULL)
{
switch (i++)
{
case 1: // 时间
printf("Time: %s\n", token);
break;
case 3: // 纬度
printf("Latitude: %s\n", token);
break;
case 4: // 纬度方向
printf("Latitude direction: %s\n", token);
break;
case 5: // 经度
printf("Longitude: %s\n", token);
break;
case 6: // 经度方向
printf("Longitude direction: %s\n", token);
break;
default:
break;
}
token = strtok(NULL, ",");
}
}
}
}
}
int main(void)
{
USART2_Init();
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
NVIC_EnableIRQ(USART2_IRQn);
USART2_SendString("AT+GPS=1\r\n"); // 发送获取GPS数据的指令
while (1);
}
```
在上面的代码中,我们首先使用`USART2_Init`函数初始化USART2串口,然后使用`USART2_SendString`函数向EC01G模块发送指令。在串口接收中断处理函数`USART2_IRQHandler`中,我们使用`gps_buff`数组保存接收到的GPS数据,当接收到完整的GPRMC语句时,使用`strtok`函数对其进行解析并输出时间、纬度、经度等信息。
需要注意的是,在使用USART2发送AT指令之前,需要先配置EC01G模块的波特率等参数。
阅读全文