STM32103c8t6读取JY901S的代码
时间: 2023-07-03 19:32:20 浏览: 382
以下是一个基于HAL库的STM32读取JY901S的示例代码:
```c
#include "stm32f1xx_hal.h"
#include <stdio.h>
UART_HandleTypeDef huart1;
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_USART1_UART_Init();
uint8_t buf[11]; // 接收缓冲区,JY901S每次返回11个字节的数据
while (1)
{
HAL_UART_Transmit(&huart1, "a5 5a 01 02 00 00 03 06", 16, 100); // 向JY901S发送请求数据的指令
HAL_Delay(100); // 等待一段时间,让JY901S有足够的时间返回数据
if (HAL_UART_Receive(&huart1, buf, 11, 100) == HAL_OK) // 从串口接收数据
{
printf("AccX: %d, AccY: %d, AccZ: %d\r\n", (int16_t)(buf[1]<<8|buf[0]), (int16_t)(buf[3]<<8|buf[2]), (int16_t)(buf[5]<<8|buf[4]));
// 解析数据,并输出加速度计的x、y、z三轴数据
}
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
Error_Handler();
}
}
static void MX_USART1_UART_Init(void)
{
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
}
static void MX_GPIO_Init(void)
{
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = GPIO_PIN_9|GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
```
这段代码使用了UART1作为与JY901S进行通信的接口,每次发送请求数据的指令后等待100毫秒,然后从串口接收返回的数据并解析,最后输出加速度计的x、y、z三轴数据。其中,JY901S每次返回11个字节的数据,需要根据具体的数据格式进行解析。
阅读全文