stm32f103c8t6串口2发送AT+LOCATION=1指令给EC01g,解析缓冲区的经纬度数据,stm32库函数版本的代码
时间: 2023-12-06 18:39:50 浏览: 90
stm32串口缓冲区源码
以下是使用stm32库函数版本的代码,实现通过串口2发送AT指令给EC01g模块,并解析缓冲区中的经纬度数据:
```c
#include "stm32f10x.h"
#include <stdio.h>
#include <string.h>
#define GPS_BUFFER_SIZE 128
char gps_buffer[GPS_BUFFER_SIZE];
uint8_t gps_buffer_index = 0;
void USART2_IRQHandler(void)
{
if (USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)
{
char c = USART_ReceiveData(USART2);
gps_buffer[gps_buffer_index++] = c;
if (gps_buffer_index >= GPS_BUFFER_SIZE)
{
gps_buffer_index = 0;
}
}
}
void USART2_SendString(char *str)
{
while (*str)
{
USART_SendData(USART2, *str++);
while (USART_GetFlagStatus(USART2, USART_FLAG_TXE) == RESET);
}
}
void USART2_SendATCommand(char *cmd)
{
USART2_SendString("AT+");
USART2_SendString(cmd);
USART2_SendString("\r\n");
}
int main(void)
{
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_InitTypeDef GPIO_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_DeInit(USART2);
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);
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
USART_Cmd(USART2, ENABLE);
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
while (1)
{
USART2_SendATCommand("LOCATION=1");
Delay(1000);
if (strstr(gps_buffer, "+LOCATION:") != NULL)
{
char *p = strstr(gps_buffer, ",");
if (p != NULL)
{
float latitude = atof(p + 1);
p = strstr(p + 1, ",");
if (p != NULL)
{
float longitude = atof(p + 1);
printf("Latitude: %f, Longitude: %f\n", latitude, longitude);
}
}
}
memset(gps_buffer, 0, GPS_BUFFER_SIZE);
gps_buffer_index = 0;
Delay(5000);
}
}
```
在上述代码中,使用USART2发送AT指令给EC01g模块,并使用USART2接收EC01g模块返回的数据,其中使用了中断接收方式。
在接收到EC01g模块返回的数据后,使用`strstr()`函数查找缓冲区中是否包含"+LOCATION:"字段,如果有,则解析经纬度数据并打印出来。在解析经纬度数据时,使用了`atof()`函数将字符串转换为浮点数。
需要注意的是,在使用`atof()`函数时,需要包含头文件`<stdlib.h>`。另外,在本例中使用了一个自定义的延时函数`Delay()`,需要自行实现。
阅读全文