增加RS485接口的测温传感器代码

This commit is contained in:
2026-08-26 10:04:53 +08:00
parent 6b544b7ddd
commit f50f6c6ece
984 changed files with 422893 additions and 9 deletions
+52
View File
@@ -0,0 +1,52 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file adc.h
* @brief This file contains all the function prototypes for
* the adc.c file
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __ADC_H__
#define __ADC_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
extern ADC_HandleTypeDef hadc1;
/* USER CODE BEGIN Private defines */
#define ADCCONVERTEDVALUES_BUFFER_SIZE ((uint32_t) 3)
/* USER CODE END Private defines */
void MX_ADC1_Init(void);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /* __ADC_H__ */
+52
View File
@@ -0,0 +1,52 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file dma.h
* @brief This file contains all the function prototypes for
* the dma.c file
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __DMA_H__
#define __DMA_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* DMA memory to memory transfer handles -------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
void MX_DMA_Init(void);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /* __DMA_H__ */
+49
View File
@@ -0,0 +1,49 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file gpio.h
* @brief This file contains all the function prototypes for
* the gpio.c file
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __GPIO_H__
#define __GPIO_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* USER CODE BEGIN Private defines */
#define GPIO_PIN_HEATER GPIO_PIN_11
/* USER CODE END Private defines */
void MX_GPIO_Init(void);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /*__ GPIO_H__ */
+52
View File
@@ -0,0 +1,52 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file iwdg.h
* @brief This file contains all the function prototypes for
* the iwdg.c file
******************************************************************************
* @attention
*
* Copyright (c) 2025 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __IWDG_H__
#define __IWDG_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
extern IWDG_HandleTypeDef hiwdg;
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
void MX_IWDG_Init(void);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /* __IWDG_H__ */
+74
View File
@@ -0,0 +1,74 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.h
* @brief : Header for main.c file.
* This file contains the common defines of the application.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32g0xx_hal.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void Error_Handler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
/* Private defines -----------------------------------------------------------*/
#define HEAT3_Pin GPIO_PIN_7
#define HEAT3_GPIO_Port GPIOA
#define HEAT2_Pin GPIO_PIN_8
#define HEAT2_GPIO_Port GPIOA
#define HEAT1_Pin GPIO_PIN_11
#define HEAT1_GPIO_Port GPIOA
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
#ifdef __cplusplus
}
#endif
#endif /* __MAIN_H */
+351
View File
@@ -0,0 +1,351 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32g0xx_hal_conf.h
* @author MCD Application Team
* @brief HAL configuration file.
******************************************************************************
* @attention
*
* Copyright (c) 2018 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef STM32G0xx_HAL_CONF_H
#define STM32G0xx_HAL_CONF_H
#ifdef __cplusplus
extern "C" {
#endif
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* ########################## Module Selection ############################## */
/**
* @brief This is the list of modules to be used in the HAL driver
*/
#define HAL_MODULE_ENABLED
#define HAL_ADC_MODULE_ENABLED
/* #define HAL_CEC_MODULE_ENABLED */
/* #define HAL_COMP_MODULE_ENABLED */
/* #define HAL_CRC_MODULE_ENABLED */
/* #define HAL_CRYP_MODULE_ENABLED */
/* #define HAL_DAC_MODULE_ENABLED */
/* #define HAL_EXTI_MODULE_ENABLED */
/* #define HAL_FDCAN_MODULE_ENABLED */
/* #define HAL_HCD_MODULE_ENABLED */
/* #define HAL_I2C_MODULE_ENABLED */
/* #define HAL_I2S_MODULE_ENABLED */
#define HAL_IWDG_MODULE_ENABLED
/* #define HAL_IRDA_MODULE_ENABLED */
/* #define HAL_LPTIM_MODULE_ENABLED */
/* #define HAL_PCD_MODULE_ENABLED */
/* #define HAL_RNG_MODULE_ENABLED */
/* #define HAL_RTC_MODULE_ENABLED */
/* #define HAL_SMARTCARD_MODULE_ENABLED */
/* #define HAL_SMBUS_MODULE_ENABLED */
/* #define HAL_SPI_MODULE_ENABLED */
/* #define HAL_TIM_MODULE_ENABLED */
#define HAL_UART_MODULE_ENABLED
/* #define HAL_USART_MODULE_ENABLED */
/* #define HAL_WWDG_MODULE_ENABLED */
#define HAL_GPIO_MODULE_ENABLED
#define HAL_EXTI_MODULE_ENABLED
#define HAL_DMA_MODULE_ENABLED
#define HAL_RCC_MODULE_ENABLED
#define HAL_FLASH_MODULE_ENABLED
#define HAL_PWR_MODULE_ENABLED
#define HAL_CORTEX_MODULE_ENABLED
/* ########################## Register Callbacks selection ############################## */
/**
* @brief This is the list of modules where register callback can be used
*/
#define USE_HAL_ADC_REGISTER_CALLBACKS 0u
#define USE_HAL_CEC_REGISTER_CALLBACKS 0u
#define USE_HAL_COMP_REGISTER_CALLBACKS 0u
#define USE_HAL_CRYP_REGISTER_CALLBACKS 0u
#define USE_HAL_DAC_REGISTER_CALLBACKS 0u
#define USE_HAL_FDCAN_REGISTER_CALLBACKS 0u
#define USE_HAL_HCD_REGISTER_CALLBACKS 0u
#define USE_HAL_I2C_REGISTER_CALLBACKS 0u
#define USE_HAL_I2S_REGISTER_CALLBACKS 0u
#define USE_HAL_IRDA_REGISTER_CALLBACKS 0u
#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0u
#define USE_HAL_PCD_REGISTER_CALLBACKS 0u
#define USE_HAL_RNG_REGISTER_CALLBACKS 0u
#define USE_HAL_RTC_REGISTER_CALLBACKS 0u
#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0u
#define USE_HAL_SPI_REGISTER_CALLBACKS 0u
#define USE_HAL_TIM_REGISTER_CALLBACKS 0u
#define USE_HAL_UART_REGISTER_CALLBACKS 0u
#define USE_HAL_USART_REGISTER_CALLBACKS 0u
#define USE_HAL_WWDG_REGISTER_CALLBACKS 0u
/* ########################## Oscillator Values adaptation ####################*/
/**
* @brief Adjust the value of External High Speed oscillator (HSE) used in your application.
* This value is used by the RCC HAL module to compute the system frequency
* (when HSE is used as system clock source, directly or through the PLL).
*/
#if !defined (HSE_VALUE)
#define HSE_VALUE (8000000UL) /*!< Value of the External oscillator in Hz */
#endif /* HSE_VALUE */
#if !defined (HSE_STARTUP_TIMEOUT)
#define HSE_STARTUP_TIMEOUT (100UL) /*!< Time out for HSE start up, in ms */
#endif /* HSE_STARTUP_TIMEOUT */
/**
* @brief Internal High Speed oscillator (HSI) value.
* This value is used by the RCC HAL module to compute the system frequency
* (when HSI is used as system clock source, directly or through the PLL).
*/
#if !defined (HSI_VALUE)
#define HSI_VALUE (16000000UL) /*!< Value of the Internal oscillator in Hz*/
#endif /* HSI_VALUE */
#if defined(STM32G0C1xx) || defined(STM32G0B1xx) || defined(STM32G0B0xx)
/**
* @brief Internal High Speed oscillator (HSI48) value for USB FS, SDMMC and RNG.
* This internal oscillator is mainly dedicated to provide a high precision clock to
* the USB peripheral by means of a special Clock Recovery System (CRS) circuitry.
* When the CRS is not used, the HSI48 RC oscillator runs on it default frequency
* which is subject to manufacturing process variations.
*/
#if !defined (HSI48_VALUE)
#define HSI48_VALUE 48000000U /*!< Value of the Internal High Speed oscillator for USB FS/SDMMC/RNG in Hz.
The real value my vary depending on manufacturing process variations.*/
#endif /* HSI48_VALUE */
#endif
/**
* @brief Internal Low Speed oscillator (LSI) value.
*/
#if !defined (LSI_VALUE)
#define LSI_VALUE (32000UL) /*!< LSI Typical Value in Hz*/
#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz
The real value may vary depending on the variations
in voltage and temperature.*/
/**
* @brief External Low Speed oscillator (LSE) value.
* This value is used by the UART, RTC HAL module to compute the system frequency
*/
#if !defined (LSE_VALUE)
#define LSE_VALUE (32768UL) /*!< Value of the External oscillator in Hz*/
#endif /* LSE_VALUE */
#if !defined (LSE_STARTUP_TIMEOUT)
#define LSE_STARTUP_TIMEOUT (5000UL) /*!< Time out for LSE start up, in ms */
#endif /* LSE_STARTUP_TIMEOUT */
/**
* @brief External clock source for I2S1 peripheral
* This value is used by the RCC HAL module to compute the I2S1 clock source
* frequency.
*/
#if !defined (EXTERNAL_I2S1_CLOCK_VALUE)
#define EXTERNAL_I2S1_CLOCK_VALUE (12288000UL) /*!< Value of the I2S1 External clock source in Hz*/
#endif /* EXTERNAL_I2S1_CLOCK_VALUE */
#if defined(STM32G0C1xx) || defined(STM32G0B1xx) || defined(STM32G0B0xx)
/**
* @brief External clock source for I2S2 peripheral
* This value is used by the RCC HAL module to compute the I2S2 clock source
* frequency.
*/
#if !defined (EXTERNAL_I2S2_CLOCK_VALUE)
#define EXTERNAL_I2S2_CLOCK_VALUE 48000U /*!< Value of the I2S2 External clock source in Hz*/
#endif /* EXTERNAL_I2S2_CLOCK_VALUE */
#endif
/* Tip: To avoid modifying this file each time you need to use different HSE,
=== you can define the HSE value in your toolchain compiler preprocessor. */
/* ########################### System Configuration ######################### */
/**
* @brief This is the HAL system configuration section
*/
#define VDD_VALUE (3300UL) /*!< Value of VDD in mv */
#define TICK_INT_PRIORITY 3U /*!< tick interrupt priority */
#define USE_RTOS 0U
#define PREFETCH_ENABLE 1U
#define INSTRUCTION_CACHE_ENABLE 1U
/* ################## SPI peripheral configuration ########################## */
/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver
* Activated: CRC code is present inside driver
* Deactivated: CRC code cleaned from driver
*/
#define USE_SPI_CRC 0U
/* ################## CRYP peripheral configuration ########################## */
#define USE_HAL_CRYP_SUSPEND_RESUME 1U
/* ########################## Assert Selection ############################## */
/**
* @brief Uncomment the line below to expanse the "assert_param" macro in the
* HAL drivers code
*/
/* #define USE_FULL_ASSERT 1U */
/* Includes ------------------------------------------------------------------*/
/**
* @brief Include modules header file
*/
#ifdef HAL_RCC_MODULE_ENABLED
#include "stm32g0xx_hal_rcc.h"
#endif /* HAL_RCC_MODULE_ENABLED */
#ifdef HAL_GPIO_MODULE_ENABLED
#include "stm32g0xx_hal_gpio.h"
#endif /* HAL_GPIO_MODULE_ENABLED */
#ifdef HAL_DMA_MODULE_ENABLED
#include "stm32g0xx_hal_dma.h"
#endif /* HAL_DMA_MODULE_ENABLED */
#ifdef HAL_CORTEX_MODULE_ENABLED
#include "stm32g0xx_hal_cortex.h"
#endif /* HAL_CORTEX_MODULE_ENABLED */
#ifdef HAL_ADC_MODULE_ENABLED
#include "stm32g0xx_hal_adc.h"
#include "stm32g0xx_hal_adc_ex.h"
#endif /* HAL_ADC_MODULE_ENABLED */
#ifdef HAL_CEC_MODULE_ENABLED
#include "stm32g0xx_hal_cec.h"
#endif /* HAL_CEC_MODULE_ENABLED */
#ifdef HAL_COMP_MODULE_ENABLED
#include "stm32g0xx_hal_comp.h"
#endif /* HAL_COMP_MODULE_ENABLED */
#ifdef HAL_CRC_MODULE_ENABLED
#include "stm32g0xx_hal_crc.h"
#endif /* HAL_CRC_MODULE_ENABLED */
#ifdef HAL_CRYP_MODULE_ENABLED
#include "stm32g0xx_hal_cryp.h"
#endif /* HAL_CRYP_MODULE_ENABLED */
#ifdef HAL_DAC_MODULE_ENABLED
#include "stm32g0xx_hal_dac.h"
#endif /* HAL_DAC_MODULE_ENABLED */
#ifdef HAL_EXTI_MODULE_ENABLED
#include "stm32g0xx_hal_exti.h"
#endif /* HAL_EXTI_MODULE_ENABLED */
#ifdef HAL_FLASH_MODULE_ENABLED
#include "stm32g0xx_hal_flash.h"
#endif /* HAL_FLASH_MODULE_ENABLED */
#ifdef HAL_FDCAN_MODULE_ENABLED
#include "stm32g0xx_hal_fdcan.h"
#endif /* HAL_FDCAN_MODULE_ENABLED */
#ifdef HAL_HCD_MODULE_ENABLED
#include "stm32g0xx_hal_hcd.h"
#endif /* HAL_HCD_MODULE_ENABLED */
#ifdef HAL_I2C_MODULE_ENABLED
#include "stm32g0xx_hal_i2c.h"
#endif /* HAL_I2C_MODULE_ENABLED */
#ifdef HAL_I2S_MODULE_ENABLED
#include "stm32g0xx_hal_i2s.h"
#endif /* HAL_I2S_MODULE_ENABLED */
#ifdef HAL_IRDA_MODULE_ENABLED
#include "stm32g0xx_hal_irda.h"
#endif /* HAL_IRDA_MODULE_ENABLED */
#ifdef HAL_IWDG_MODULE_ENABLED
#include "stm32g0xx_hal_iwdg.h"
#endif /* HAL_IWDG_MODULE_ENABLED */
#ifdef HAL_LPTIM_MODULE_ENABLED
#include "stm32g0xx_hal_lptim.h"
#endif /* HAL_LPTIM_MODULE_ENABLED */
#ifdef HAL_PCD_MODULE_ENABLED
#include "stm32g0xx_hal_pcd.h"
#endif /* HAL_PCD_MODULE_ENABLED */
#ifdef HAL_PWR_MODULE_ENABLED
#include "stm32g0xx_hal_pwr.h"
#endif /* HAL_PWR_MODULE_ENABLED */
#ifdef HAL_RNG_MODULE_ENABLED
#include "stm32g0xx_hal_rng.h"
#endif /* HAL_RNG_MODULE_ENABLED */
#ifdef HAL_RTC_MODULE_ENABLED
#include "stm32g0xx_hal_rtc.h"
#endif /* HAL_RTC_MODULE_ENABLED */
#ifdef HAL_SMARTCARD_MODULE_ENABLED
#include "stm32g0xx_hal_smartcard.h"
#endif /* HAL_SMARTCARD_MODULE_ENABLED */
#ifdef HAL_SMBUS_MODULE_ENABLED
#include "stm32g0xx_hal_smbus.h"
#endif /* HAL_SMBUS_MODULE_ENABLED */
#ifdef HAL_SPI_MODULE_ENABLED
#include "stm32g0xx_hal_spi.h"
#endif /* HAL_SPI_MODULE_ENABLED */
#ifdef HAL_TIM_MODULE_ENABLED
#include "stm32g0xx_hal_tim.h"
#endif /* HAL_TIM_MODULE_ENABLED */
#ifdef HAL_UART_MODULE_ENABLED
#include "stm32g0xx_hal_uart.h"
#endif /* HAL_UART_MODULE_ENABLED */
#ifdef HAL_USART_MODULE_ENABLED
#include "stm32g0xx_hal_usart.h"
#endif /* HAL_USART_MODULE_ENABLED */
#ifdef HAL_WWDG_MODULE_ENABLED
#include "stm32g0xx_hal_wwdg.h"
#endif /* HAL_WWDG_MODULE_ENABLED */
/* Exported macro ------------------------------------------------------------*/
#ifdef USE_FULL_ASSERT
/**
* @brief The assert_param macro is used for functions parameters check.
* @param expr If expr is false, it calls assert_failed function
* which reports the name of the source file and the source
* line number of the call that failed.
* If expr is true, it returns no value.
* @retval None
*/
#define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__))
/* Exported functions ------------------------------------------------------- */
void assert_failed(uint8_t *file, uint32_t line);
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
#ifdef __cplusplus
}
#endif
#endif /* STM32G0xx_HAL_CONF_H */
+64
View File
@@ -0,0 +1,64 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32g0xx_it.h
* @brief This file contains the headers of the interrupt handlers.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32G0xx_IT_H
#define __STM32G0xx_IT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void NMI_Handler(void);
void HardFault_Handler(void);
void SVC_Handler(void);
void PendSV_Handler(void);
void SysTick_Handler(void);
void DMA1_Channel1_IRQHandler(void);
void USART1_IRQHandler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
#ifdef __cplusplus
}
#endif
#endif /* __STM32G0xx_IT_H */
+55
View File
@@ -0,0 +1,55 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file usart.h
* @brief This file contains all the function prototypes for
* the usart.c file
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __USART_H__
#define __USART_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
extern UART_HandleTypeDef huart1;
extern UART_HandleTypeDef huart2;
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
void MX_USART1_UART_Init(void);
void MX_USART2_UART_Init(void);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /* __USART_H__ */
+203
View File
@@ -0,0 +1,203 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file adc.c
* @brief This file provides code for the configuration
* of the ADC instances.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "adc.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;
/* ADC1 init function */
void MX_ADC1_Init(void)
{
/* USER CODE BEGIN ADC1_Init 0 */
/* USER CODE END ADC1_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC1_Init 1 */
/* USER CODE END ADC1_Init 1 */
/** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
*/
hadc1.Instance = ADC1;
hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
hadc1.Init.Resolution = ADC_RESOLUTION_12B;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
hadc1.Init.EOCSelection = ADC_EOC_SEQ_CONV;
hadc1.Init.LowPowerAutoWait = DISABLE;
hadc1.Init.LowPowerAutoPowerOff = ENABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.NbrOfConversion = 4;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
hadc1.Init.DMAContinuousRequests = DISABLE;
hadc1.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN;
hadc1.Init.SamplingTimeCommon1 = ADC_SAMPLETIME_12CYCLES_5;
hadc1.Init.SamplingTimeCommon2 = ADC_SAMPLETIME_12CYCLES_5;
hadc1.Init.OversamplingMode = ENABLE;
hadc1.Init.Oversampling.Ratio = ADC_OVERSAMPLING_RATIO_64;
hadc1.Init.Oversampling.RightBitShift = ADC_RIGHTBITSHIFT_6;
hadc1.Init.Oversampling.TriggeredMode = ADC_TRIGGEREDMODE_SINGLE_TRIGGER;
hadc1.Init.TriggerFrequencyMode = ADC_TRIGGER_FREQ_HIGH;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLINGTIME_COMMON_1;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_4;
sConfig.Rank = ADC_REGULAR_RANK_2;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_5;
sConfig.Rank = ADC_REGULAR_RANK_3;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_6;
sConfig.Rank = ADC_REGULAR_RANK_4;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */
/* USER CODE END ADC1_Init 2 */
}
void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
if(adcHandle->Instance==ADC1)
{
/* USER CODE BEGIN ADC1_MspInit 0 */
/* USER CODE END ADC1_MspInit 0 */
/** Initializes the peripherals clocks
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
PeriphClkInit.AdcClockSelection = RCC_ADCCLKSOURCE_PLLADC;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
/* ADC1 clock enable */
__HAL_RCC_ADC_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**ADC1 GPIO Configuration
PA0 ------> ADC1_IN0
PA4 ------> ADC1_IN4
PA5 ------> ADC1_IN5
PA6 ------> ADC1_IN6
*/
GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* ADC1 DMA Init */
/* ADC1 Init */
hdma_adc1.Instance = DMA1_Channel1;
hdma_adc1.Init.Request = DMA_REQUEST_ADC1;
hdma_adc1.Init.Direction = DMA_PERIPH_TO_MEMORY;
hdma_adc1.Init.PeriphInc = DMA_PINC_DISABLE;
hdma_adc1.Init.MemInc = DMA_MINC_ENABLE;
hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD;
hdma_adc1.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD;
hdma_adc1.Init.Mode = DMA_NORMAL;
hdma_adc1.Init.Priority = DMA_PRIORITY_LOW;
if (HAL_DMA_Init(&hdma_adc1) != HAL_OK)
{
Error_Handler();
}
__HAL_LINKDMA(adcHandle,DMA_Handle,hdma_adc1);
/* USER CODE BEGIN ADC1_MspInit 1 */
/* USER CODE END ADC1_MspInit 1 */
}
}
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle)
{
if(adcHandle->Instance==ADC1)
{
/* USER CODE BEGIN ADC1_MspDeInit 0 */
/* USER CODE END ADC1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_ADC_CLK_DISABLE();
/**ADC1 GPIO Configuration
PA0 ------> ADC1_IN0
PA4 ------> ADC1_IN4
PA5 ------> ADC1_IN5
PA6 ------> ADC1_IN6
*/
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_0|GPIO_PIN_4|GPIO_PIN_5|GPIO_PIN_6);
/* ADC1 DMA DeInit */
HAL_DMA_DeInit(adcHandle->DMA_Handle);
/* USER CODE BEGIN ADC1_MspDeInit 1 */
/* USER CODE END ADC1_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
+55
View File
@@ -0,0 +1,55 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file dma.c
* @brief This file provides code for the configuration
* of all the requested memory to memory DMA transfers.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "dma.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/*----------------------------------------------------------------------------*/
/* Configure DMA */
/*----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/**
* Enable DMA controller clock
*/
void MX_DMA_Init(void)
{
/* DMA controller clock enable */
__HAL_RCC_DMA1_CLK_ENABLE();
/* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 1, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
}
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
+85
View File
@@ -0,0 +1,85 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file gpio.c
* @brief This file provides code for the configuration
* of all used GPIO pins.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "gpio.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/*----------------------------------------------------------------------------*/
/* Configure GPIO */
/*----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/** Configure pins as
* Analog
* Input
* Output
* EVENT_OUT
* EXTI
*/
void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_9, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOA, HEAT3_Pin|HEAT2_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(HEAT1_GPIO_Port, HEAT1_Pin, GPIO_PIN_SET);
/*Configure GPIO pin : PB9 */
GPIO_InitStruct.Pin = GPIO_PIN_9;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : PAPin PAPin */
GPIO_InitStruct.Pin = HEAT3_Pin|HEAT2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pin : PtPin */
GPIO_InitStruct.Pin = HEAT1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_PULLDOWN;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(HEAT1_GPIO_Port, &GPIO_InitStruct);
}
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
+56
View File
@@ -0,0 +1,56 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file iwdg.c
* @brief This file provides code for the configuration
* of the IWDG instances.
******************************************************************************
* @attention
*
* Copyright (c) 2025 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "iwdg.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
IWDG_HandleTypeDef hiwdg;
/* IWDG init function */
void MX_IWDG_Init(void)
{
/* USER CODE BEGIN IWDG_Init 0 */
/* USER CODE END IWDG_Init 0 */
/* USER CODE BEGIN IWDG_Init 1 */
/* USER CODE END IWDG_Init 1 */
hiwdg.Instance = IWDG;
hiwdg.Init.Prescaler = IWDG_PRESCALER_32;
hiwdg.Init.Window = 4095;
hiwdg.Init.Reload = 1000;
if (HAL_IWDG_Init(&hiwdg) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN IWDG_Init 2 */
/* USER CODE END IWDG_Init 2 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
+505
View File
@@ -0,0 +1,505 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dma.h"
#include "iwdg.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include <string.h> // 用于memset函数
//#include "modbus_core_crc.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
uint8_t gucAddr = 0x10;
#define SLAVE_ADDR gucAddr // Modbus从机地址
//#define SLAVE_ADDR 0x11 // Modbus从机地址
#define DEEP_REG_ADDR 0x0000 // 液位 0,1,2,3
#define TEMP_REG_ADDR 0x0001 // 油温 *10
#define REGNUM_01 0x01 // 温度
#define REGNUM_02 0x02 // 温度
#define T_HEARTER 10000 // 加热时间 ms
#define T_COOLER 10000 // 冷却时间 ms
uint8_t modbusRxBuf[16]; // Modbus接收缓冲匿
uint8_t modbusTxBuf[16]; // Modbus发鿁缓冲区
volatile uint8_t rxFlag = 0; // 接收完成标志
static uint16_t temp;
static uint16_t level;
//uint8_t UART1_Rx_flg = 0;
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
static float thermistor[4];
static uint16_t adc_value[4];
uint16_t temp_value[4];
float tem_compare[4];
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
static uint8_t uartRecvCnt = 0;
static uint32_t ulUartRecvTime = 0;
void get_level(void);
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART1){
HAL_UART_Receive_IT(huart, modbusRxBuf, 1); // 重新启动接收
}
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
if(huart->Instance == USART1){
if(uartRecvCnt == 0 && modbusRxBuf[0] != SLAVE_ADDR){
HAL_UART_Receive_IT(huart, modbusRxBuf, 1); // 非本机地￿?,重置接￿?
return;
}
if(++uartRecvCnt >= 8){ // 接收￿?8字节,触发处￿?
uartRecvCnt = 0;
rxFlag = 1; // 设置接收完成标志
}
HAL_UART_Receive_IT(huart, &modbusRxBuf[uartRecvCnt], 1); // 继续接收下一个字￿?
ulUartRecvTime = 0;
}
}
uint16_t CRC16(uint8_t *buf, int len)
{
uint16_t crc = 0xFFFF;
for(int pos=0; pos<len; pos++){
crc ^= (uint16_t)buf[pos];
for(int i=8; i!=0; i--){
if((crc & 0x0001) != 0){
crc >>= 1;
crc ^= 0xA001; // Modbus CRC多项￿?
}else{
crc >>= 1;
}
}
}
return crc;
}
void AppendCRC(uint8_t* buf, uint8_t len)
{
uint16_t crc = CRC16(buf, len);
buf[len] = crc & 0xFF; // 低字节在剿
buf[len+1] = crc >> 8; // 高字节在吿
}
void Process_Modbus(void)
{
//printf("modbusr\r\n");
/* 第一层地坿过滤 */
if(modbusRxBuf[0] != SLAVE_ADDR) return; // 非本机地坿,直接忽畿
//printf("addr ok\r\n");
/* 第二层CRC验证 */
uint16_t crc = CRC16(modbusRxBuf, 6);
if(*(uint16_t*)&modbusRxBuf[6] != crc) return; // CRC校验失败,忽畿
//printf("crc ok\r\n");
switch(modbusRxBuf[1]){ // 根据功能码处琿
case 0x03: // 读保持寄存器
if(*(uint16_t*)&modbusRxBuf[3] == DEEP_REG_ADDR) // 棿查寄存器地址
{
uint16_t regnum = (modbusRxBuf[4] << 8) | modbusRxBuf[5];
if(regnum == 0x01)
{
modbusTxBuf[0] = SLAVE_ADDR; // 从机地址
modbusTxBuf[1] = 0x03; // 功能砿
modbusTxBuf[2] = 0x02; // 返回字节敿(2字节)
uint16_t deep = level; //
modbusTxBuf[3] = deep >> 8; // 高字芿
modbusTxBuf[4] = deep & 0xFF; // 低字芿
AppendCRC(modbusTxBuf, 5); // 添加CRC校验
HAL_UART_Transmit(&huart1, modbusTxBuf, 7, 100); // 发鿿7字节响应
}
if(regnum == 0x02)
{
modbusTxBuf[0] = SLAVE_ADDR; // 从机地址
modbusTxBuf[1] = 0x03; // 功能砿
modbusTxBuf[2] = 0x04; // 返回字节敿(2字节)
uint16_t deep = level; // 模拟温度倿(实际应从传感器读叿)
modbusTxBuf[3] = deep >> 8; // 高字芿
modbusTxBuf[4] = deep & 0xFF; // 低字芿
uint16_t temp = temp_value[3]; // 模拟温度倿(实际应从传感器读叿)
modbusTxBuf[5] = temp >> 8; // 高字芿
modbusTxBuf[6] = temp & 0xFF; // 低字芿
AppendCRC(modbusTxBuf, 7); // 添加CRC校验
HAL_UART_Transmit(&huart1, modbusTxBuf, 9, 100); // 发鿿7字节响应
}
}
if(*(uint16_t*)&modbusRxBuf[3] == TEMP_REG_ADDR) // 棿查寄存器地坿
{
modbusTxBuf[0] = SLAVE_ADDR; // 从机地址
modbusTxBuf[1] = 0x03; // 功能砿
modbusTxBuf[2] = 0x02; // 返回字节敿(2字节)
uint16_t temp = temp_value[3]; // 模拟温度倿(实际应从传感器读叿)
modbusTxBuf[3] = temp >> 8; // 高字芿
modbusTxBuf[4] = temp & 0xFF; // 低字芿
AppendCRC(modbusTxBuf, 5); // 添加CRC校验
HAL_UART_Transmit(&huart1, modbusTxBuf, 7, 100); // 发鿿7字节响应
}
break;
// 可以添加其他功能码处琿
}
memset(modbusTxBuf, 0, sizeof(modbusTxBuf)); // 清空发鿁缓冲区
}
//re_def
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1, 0xffff);
return ch;
}
//count temp
static float getTemp(float Rt)
{
const float Rp = 10000.0; ///< 10K NTC
const float T2 = (273.15+25.0); ///< 10K NTC
const float Bx = 3950.0; ///< 10K NTC
const float Ka = 273.15; ///< 10K NTC
float Temp = 0.0f;
Temp = Rt / Rp;
Temp = log(Temp);
Temp /=Bx;
Temp += (1 / T2);
Temp = 1 / Temp;
Temp -= Ka;
return Temp;
}
void readTemp(void)
{
float vol[4] = {0,0,0,0};
HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_value, 4);
HAL_Delay(1);
// printf("readTemp %d,%d,%d,%d\r\n",adc_value[0],adc_value[1],adc_value[2],adc_value[3]);
for(int i=0 ; i<4 ;i++)
{
vol[i] = ((float)adc_value[i]/4095);
vol[i] = vol[i]*3.3 ;
thermistor[i] = (10000*vol[i])/(3.3-vol[i]);
temp_value[i]=(floor)(getTemp(thermistor[i])*10);
}
HAL_ADC_Stop_DMA(&hadc1);
}
const int iSampleNum = 15;
/*
通过温度变化计算油位
@param tempBuf 温度缓冲区
@return 1: 油位没过 0: 油位空缺
*/
int calculate(uint16_t *tempBuf)
{
for (int i = 0; i < iSampleNum; i++)
{
printf("%d ",tempBuf[i]);
}
printf("%d", tempBuf[iSampleNum - 1] - tempBuf[0]);
printf("\r\n");
if ((tempBuf[iSampleNum - 1] > tempBuf[0]) && (tempBuf[iSampleNum - 1] - tempBuf[0] <= 40))
{
return 1;
}
return 0;
}
void check_level(void)
{
static int iLevelBuf[3] = {0};
static int iCheckIndex = 0;
static uint16_t usIndex = 0;
static uint32_t ulTick = 0;
static uint16_t ausTempBuf[4][iSampleNum] = {0};
switch(iCheckIndex){
case 0:
HAL_GPIO_WritePin(HEAT1_GPIO_Port, HEAT1_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(HEAT2_GPIO_Port, HEAT2_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(HEAT3_GPIO_Port, HEAT3_Pin,GPIO_PIN_RESET);
break;
case 1:
HAL_GPIO_WritePin(HEAT1_GPIO_Port, HEAT1_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(HEAT2_GPIO_Port, HEAT2_Pin,GPIO_PIN_SET);
HAL_GPIO_WritePin(HEAT3_GPIO_Port, HEAT3_Pin,GPIO_PIN_RESET);
break;
case 2:
HAL_GPIO_WritePin(HEAT1_GPIO_Port, HEAT1_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(HEAT2_GPIO_Port, HEAT2_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(HEAT3_GPIO_Port, HEAT3_Pin,GPIO_PIN_SET);
break;
}
if(HAL_GetTick() < ulTick + 1000) return;
ulTick = HAL_GetTick();
readTemp();
// printf("%d,%d,%d,%d\r\n",temp_value[0],temp_value[1],temp_value[2],temp_value[3]);
ausTempBuf[0][usIndex] = temp_value[0];
ausTempBuf[1][usIndex] = temp_value[1];
ausTempBuf[2][usIndex] = temp_value[2];
ausTempBuf[3][usIndex] = temp_value[3];
usIndex++;
if(usIndex >= iSampleNum)
{
printf("calculate %d\r\n", iCheckIndex);
iLevelBuf[iCheckIndex] = calculate(ausTempBuf[iCheckIndex + 1]);
if (iLevelBuf[0] && iLevelBuf[1] && iLevelBuf[2])
{
level = 3;
} else if (iLevelBuf[0] && iLevelBuf[1])
{
level = 2;
} else if (iLevelBuf[0])
{
level = 1;
} else
{
level = 0;
}
temp = 0;
for(int i=0 ; i<iSampleNum;i++)
{
temp += ausTempBuf[0][i];
}
temp /= iSampleNum;
printf("temp %d,level %d\r\n", temp, level);
usIndex = 0;
iCheckIndex++;
if(iCheckIndex >= 3) iCheckIndex = 0;
}
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_DMA_Init();
MX_ADC1_Init();
MX_USART2_UART_Init();
MX_USART1_UART_Init();
MX_IWDG_Init();
/* USER CODE BEGIN 2 */
//Set GPIO NMOS COLSE
HAL_GPIO_WritePin(HEAT1_GPIO_Port, HEAT1_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(HEAT2_GPIO_Port, HEAT2_Pin,GPIO_PIN_RESET);
HAL_GPIO_WritePin(HEAT3_GPIO_Port, HEAT3_Pin,GPIO_PIN_RESET);
HAL_UART_Receive_IT(&huart1, modbusRxBuf, 1); // 重新启动接收
HAL_IWDG_Refresh(&hiwdg);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
HAL_IWDG_Refresh(&hiwdg);
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
ulUartRecvTime++;
if ((uartRecvCnt > 0) && (ulUartRecvTime > 3)) {
HAL_UART_AbortReceive_IT(&huart1);
uartRecvCnt = 0;
HAL_UART_Receive_IT(&huart1, modbusRxBuf, 1); // 重新启动接收
}
if(rxFlag){ // 棿查是否接收到完整Modbus数据帿
rxFlag = 0; // 清除标志
printf("modbusRxBuf ");
for (size_t i = 0; i < 8; i++)
{
printf("%02X ", modbusRxBuf[i]);
}
printf("\r\n");
Process_Modbus(); // 处理Modbus命令
}
HAL_Delay(1);
check_level();
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSIDiv = RCC_HSI_DIV1;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.LSIState = RCC_LSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1;
RCC_OscInitStruct.PLL.PLLN = 8;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV11;
RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
View File
+81
View File
@@ -0,0 +1,81 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32g0xx_hal_msp.c
* @brief This file provides code for the MSP Initialization
* and de-Initialization codes.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN Define */
/* USER CODE END Define */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN Macro */
/* USER CODE END Macro */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* External functions --------------------------------------------------------*/
/* USER CODE BEGIN ExternalFunctions */
/* USER CODE END ExternalFunctions */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void)
{
/* USER CODE BEGIN MspInit 0 */
/* USER CODE END MspInit 0 */
__HAL_RCC_SYSCFG_CLK_ENABLE();
__HAL_RCC_PWR_CLK_ENABLE();
/* System interrupt init*/
/* USER CODE BEGIN MspInit 1 */
/* USER CODE END MspInit 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
+175
View File
@@ -0,0 +1,175 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32g0xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32g0xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern DMA_HandleTypeDef hdma_adc1;
extern UART_HandleTypeDef huart1;
/* USER CODE BEGIN EV */
/* USER CODE END EV */
/******************************************************************************/
/* Cortex-M0+ Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
while (1)
{
}
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_HardFault_IRQn 0 */
/* USER CODE END W1_HardFault_IRQn 0 */
}
}
/**
* @brief This function handles System service call via SWI instruction.
*/
void SVC_Handler(void)
{
/* USER CODE BEGIN SVC_IRQn 0 */
/* USER CODE END SVC_IRQn 0 */
/* USER CODE BEGIN SVC_IRQn 1 */
/* USER CODE END SVC_IRQn 1 */
}
/**
* @brief This function handles Pendable request for system service.
*/
void PendSV_Handler(void)
{
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32G0xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32g0xx.s). */
/******************************************************************************/
/**
* @brief This function handles DMA1 channel 1 interrupt.
*/
void DMA1_Channel1_IRQHandler(void)
{
/* USER CODE BEGIN DMA1_Channel1_IRQn 0 */
/* USER CODE END DMA1_Channel1_IRQn 0 */
HAL_DMA_IRQHandler(&hdma_adc1);
/* USER CODE BEGIN DMA1_Channel1_IRQn 1 */
/* USER CODE END DMA1_Channel1_IRQn 1 */
}
/**
* @brief This function handles USART1 global interrupt / USART1 wake-up interrupt through EXTI line 25.
*/
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
/* USER CODE END USART1_IRQn 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
+302
View File
@@ -0,0 +1,302 @@
/**
******************************************************************************
* @file system_stm32g0xx.c
* @author MCD Application Team
* @brief CMSIS Cortex-M0+ Device Peripheral Access Layer System Source File
*
* This file provides two functions and one global variable to be called from
* user application:
* - SystemInit(): This function is called at startup just after reset and
* before branch to main program. This call is made inside
* the "startup_stm32g0xx.s" file.
*
* - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
* by the user application to setup the SysTick
* timer or configure other parameters.
*
* - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
* be called whenever the core clock is changed
* during program execution.
*
* After each device reset the HSI (8 MHz then 16 MHz) is used as system clock source.
* Then SystemInit() function is called, in "startup_stm32g0xx.s" file, to
* configure the system clock before to branch to main program.
*
* This file configures the system clock as follows:
*=============================================================================
*-----------------------------------------------------------------------------
* System Clock source | HSI
*-----------------------------------------------------------------------------
* SYSCLK(Hz) | 16000000
*-----------------------------------------------------------------------------
* HCLK(Hz) | 16000000
*-----------------------------------------------------------------------------
* AHB Prescaler | 1
*-----------------------------------------------------------------------------
* APB Prescaler | 1
*-----------------------------------------------------------------------------
* HSI Division factor | 1
*-----------------------------------------------------------------------------
* PLL_M | 1
*-----------------------------------------------------------------------------
* PLL_N | 8
*-----------------------------------------------------------------------------
* PLL_P | 7
*-----------------------------------------------------------------------------
* PLL_Q | 2
*-----------------------------------------------------------------------------
* PLL_R | 2
*-----------------------------------------------------------------------------
* Require 48MHz for RNG | Disabled
*-----------------------------------------------------------------------------
*=============================================================================
******************************************************************************
* @attention
*
* Copyright (c) 2018-2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32g0xx_system
* @{
*/
/** @addtogroup STM32G0xx_System_Private_Includes
* @{
*/
#include "stm32g0xx.h"
#if !defined (HSE_VALUE)
#define HSE_VALUE (8000000UL) /*!< Value of the External oscillator in Hz */
#endif /* HSE_VALUE */
#if !defined (HSI_VALUE)
#define HSI_VALUE (16000000UL) /*!< Value of the Internal oscillator in Hz*/
#endif /* HSI_VALUE */
#if !defined (LSI_VALUE)
#define LSI_VALUE (32000UL) /*!< Value of LSI in Hz*/
#endif /* LSI_VALUE */
#if !defined (LSE_VALUE)
#define LSE_VALUE (32768UL) /*!< Value of LSE in Hz*/
#endif /* LSE_VALUE */
/**
* @}
*/
/** @addtogroup STM32G0xx_System_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @addtogroup STM32G0xx_System_Private_Defines
* @{
*/
/************************* Miscellaneous Configuration ************************/
/* Note: Following vector table addresses must be defined in line with linker
configuration. */
/*!< Uncomment the following line if you need to relocate the vector table
anywhere in Flash or Sram, else the vector table is kept at the automatic
remap of boot address selected */
/* #define USER_VECT_TAB_ADDRESS */
#if defined(USER_VECT_TAB_ADDRESS)
/*!< Uncomment the following line if you need to relocate your vector Table
in Sram else user remap will be done in Flash. */
/* #define VECT_TAB_SRAM */
#if defined(VECT_TAB_SRAM)
#define VECT_TAB_BASE_ADDRESS SRAM_BASE /*!< Vector Table base address field.
This value must be a multiple of 0x200. */
#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
#else
#define VECT_TAB_BASE_ADDRESS FLASH_BASE /*!< Vector Table base address field.
This value must be a multiple of 0x200. */
#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
#endif /* VECT_TAB_SRAM */
#endif /* USER_VECT_TAB_ADDRESS */
/******************************************************************************/
/**
* @}
*/
/** @addtogroup STM32G0xx_System_Private_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32G0xx_System_Private_Variables
* @{
*/
/* The SystemCoreClock variable is updated in three ways:
1) by calling CMSIS function SystemCoreClockUpdate()
2) by calling HAL API function HAL_RCC_GetHCLKFreq()
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
Note: If you use this function to configure the system clock; then there
is no need to call the 2 first functions listed above, since SystemCoreClock
variable is updated automatically.
*/
uint32_t SystemCoreClock = 16000000UL;
const uint32_t AHBPrescTable[16UL] = {0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 0UL, 1UL, 2UL, 3UL, 4UL, 6UL, 7UL, 8UL, 9UL};
const uint32_t APBPrescTable[8UL] = {0UL, 0UL, 0UL, 0UL, 1UL, 2UL, 3UL, 4UL};
/**
* @}
*/
/** @addtogroup STM32G0xx_System_Private_FunctionPrototypes
* @{
*/
/**
* @}
*/
/** @addtogroup STM32G0xx_System_Private_Functions
* @{
*/
/**
* @brief Setup the microcontroller system.
* @param None
* @retval None
*/
void SystemInit(void)
{
/* Configure the Vector Table location -------------------------------------*/
#if defined(USER_VECT_TAB_ADDRESS)
SCB->VTOR = VECT_TAB_BASE_ADDRESS | VECT_TAB_OFFSET; /* Vector Table Relocation */
#endif /* USER_VECT_TAB_ADDRESS */
}
/**
* @brief Update SystemCoreClock variable according to Clock Register Values.
* The SystemCoreClock variable contains the core clock (HCLK), it can
* be used by the user application to setup the SysTick timer or configure
* other parameters.
*
* @note Each time the core clock (HCLK) changes, this function must be called
* to update SystemCoreClock variable value. Otherwise, any configuration
* based on this variable will be incorrect.
*
* @note - The system frequency computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
*
* - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(**) / HSI division factor
*
* - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(***)
*
* - If SYSCLK source is LSI, SystemCoreClock will contain the LSI_VALUE
*
* - If SYSCLK source is LSE, SystemCoreClock will contain the LSE_VALUE
*
* - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(***)
* or HSI_VALUE(*) multiplied/divided by the PLL factors.
*
* (**) HSI_VALUE is a constant defined in stm32g0xx_hal_conf.h file (default value
* 16 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
*
* (***) HSE_VALUE is a constant defined in stm32g0xx_hal_conf.h file (default value
* 8 MHz), user has to ensure that HSE_VALUE is same as the real
* frequency of the crystal used. Otherwise, this function may
* have wrong result.
*
* - The result of this function could be not correct when using fractional
* value for HSE crystal.
*
* @param None
* @retval None
*/
void SystemCoreClockUpdate(void)
{
uint32_t tmp;
uint32_t pllvco;
uint32_t pllr;
uint32_t pllsource;
uint32_t pllm;
uint32_t hsidiv;
/* Get SYSCLK source -------------------------------------------------------*/
switch (RCC->CFGR & RCC_CFGR_SWS)
{
case RCC_CFGR_SWS_0: /* HSE used as system clock */
SystemCoreClock = HSE_VALUE;
break;
case (RCC_CFGR_SWS_1 | RCC_CFGR_SWS_0): /* LSI used as system clock */
SystemCoreClock = LSI_VALUE;
break;
case RCC_CFGR_SWS_2: /* LSE used as system clock */
SystemCoreClock = LSE_VALUE;
break;
case RCC_CFGR_SWS_1: /* PLL used as system clock */
/* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLLM) * PLLN
SYSCLK = PLL_VCO / PLLR
*/
pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC);
pllm = ((RCC->PLLCFGR & RCC_PLLCFGR_PLLM) >> RCC_PLLCFGR_PLLM_Pos) + 1UL;
if(pllsource == 0x03UL) /* HSE used as PLL clock source */
{
pllvco = (HSE_VALUE / pllm);
}
else /* HSI used as PLL clock source */
{
pllvco = (HSI_VALUE / pllm);
}
pllvco = pllvco * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> RCC_PLLCFGR_PLLN_Pos);
pllr = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> RCC_PLLCFGR_PLLR_Pos) + 1UL);
SystemCoreClock = pllvco/pllr;
break;
case 0x00000000U: /* HSI used as system clock */
default: /* HSI used as system clock */
hsidiv = (1UL << ((READ_BIT(RCC->CR, RCC_CR_HSIDIV))>> RCC_CR_HSIDIV_Pos));
SystemCoreClock = (HSI_VALUE/hsidiv);
break;
}
/* Compute HCLK clock frequency --------------------------------------------*/
/* Get HCLK prescaler */
tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos)];
/* HCLK clock frequency */
SystemCoreClock >>= tmp;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
+240
View File
@@ -0,0 +1,240 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file usart.c
* @brief This file provides code for the configuration
* of the USART instances.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "usart.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;
/* USART1 init function */
void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
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;
huart1.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart1.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart1.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_RS485Ex_Init(&huart1, UART_DE_POLARITY_HIGH, 0, 0) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetTxFifoThreshold(&huart1, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_SetRxFifoThreshold(&huart1, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
{
Error_Handler();
}
if (HAL_UARTEx_DisableFifoMode(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/* USART2 init function */
void MX_USART2_UART_Init(void)
{
/* USER CODE BEGIN USART2_Init 0 */
/* USER CODE END USART2_Init 0 */
/* USER CODE BEGIN USART2_Init 1 */
/* USER CODE END USART2_Init 1 */
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart2.Init.ClockPrescaler = UART_PRESCALER_DIV1;
huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART2_Init 2 */
/* USER CODE END USART2_Init 2 */
}
void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
if(uartHandle->Instance==USART1)
{
/* USER CODE BEGIN USART1_MspInit 0 */
/* USER CODE END USART1_MspInit 0 */
/** Initializes the peripherals clocks
*/
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;
PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_SYSCLK;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
/* USART1 clock enable */
__HAL_RCC_USART1_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**USART1 GPIO Configuration
PB7 ------> USART1_RX
PA12 [PA10] ------> USART1_DE
PB6 ------> USART1_TX
*/
GPIO_InitStruct.Pin = GPIO_PIN_7;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF0_USART1;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_12;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF1_USART1;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
GPIO_InitStruct.Pin = GPIO_PIN_6;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF0_USART1;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* USART1 interrupt Init */
HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(USART1_IRQn);
/* USER CODE BEGIN USART1_MspInit 1 */
/* USER CODE END USART1_MspInit 1 */
}
else if(uartHandle->Instance==USART2)
{
/* USER CODE BEGIN USART2_MspInit 0 */
/* USER CODE END USART2_MspInit 0 */
/* USART2 clock enable */
__HAL_RCC_USART2_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**USART2 GPIO Configuration
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF1_USART2;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* USER CODE BEGIN USART2_MspInit 1 */
/* USER CODE END USART2_MspInit 1 */
}
}
void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
{
if(uartHandle->Instance==USART1)
{
/* USER CODE BEGIN USART1_MspDeInit 0 */
/* USER CODE END USART1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USART1_CLK_DISABLE();
/**USART1 GPIO Configuration
PB7 ------> USART1_RX
PA12 [PA10] ------> USART1_DE
PB6 ------> USART1_TX
*/
HAL_GPIO_DeInit(GPIOB, GPIO_PIN_7|GPIO_PIN_6);
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_12);
/* USART1 interrupt Deinit */
HAL_NVIC_DisableIRQ(USART1_IRQn);
/* USER CODE BEGIN USART1_MspDeInit 1 */
/* USER CODE END USART1_MspDeInit 1 */
}
else if(uartHandle->Instance==USART2)
{
/* USER CODE BEGIN USART2_MspDeInit 0 */
/* USER CODE END USART2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USART2_CLK_DISABLE();
/**USART2 GPIO Configuration
PA2 ------> USART2_TX
PA3 ------> USART2_RX
*/
HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3);
/* USER CODE BEGIN USART2_MspDeInit 1 */
/* USER CODE END USART2_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
@@ -0,0 +1,64 @@
#include "modbus_core.h"
// send data callback pointer
SwSendDataCallBack modbusSendCallBack = NULL;
// rec data callback pointer
SwRecDataCallBack modbusRecCallBack = NULL;
/**
* @brief enable send data callback
* @param sendDataCallBack
*/
__attribute__((unused)) void Modbus_RegistrySendCallBack(SwSendDataCallBack sendDataCallBack) {
modbusSendCallBack = sendDataCallBack;
}
/**
* @brief enable rec data callback
* @param recDataCallBack
*/
__attribute__((unused)) void Modbus_RegistryRecCallBack(SwRecDataCallBack recDataCallBack) {
modbusRecCallBack = recDataCallBack;
}
uint16_t PackBoolArray(uint8_t *dst, const bool *data, uint16_t dataLen) {
uint8_t retLen = 0;
uint8_t curDat = 0;
uint8_t bitIdx = 0;
for (int i = 0; i < dataLen; ++i) {
if (data[i]) {
curDat |= (uint8_t) (1 << bitIdx);
}
if (++bitIdx == 8) {
dst[retLen++] = curDat;
curDat = 0;
bitIdx = 0;
}
}
if (bitIdx != 8) {
dst[retLen++] = curDat;
}
return retLen;
}
/**
* @brief bool to byte
* @param dst storge
* @param cnt change num
* @param data byte data
* @param dataLen data len
*/
void UnPackBool(bool *dst, uint16_t cnt, const uint8_t *data, uint16_t dataLen) {
// uint16_t retLen = 0;
uint8_t curDat = 0;
// uint8_t bitIdx = 0;
for (int i = 0; i < dataLen; ++i) {
curDat = data[i];
for (int j = 0; j < 8; ++j) {
if (cnt == 0) { return; };
*dst++ = (curDat & (1 << j)) != 0;
cnt--;
}
}
}
@@ -0,0 +1,263 @@
#include "modbus_core.h"
#include "slave_rtu.h"
#define FIX_MIN_DATA_LEN 8
typedef struct {
uint8_t slaveAddr;
uint8_t funcCode;
uint8_t regAddr;
uint8_t regNum;
uint8_t *data;
uint16_t dataLen;
} slave_packet_t;
static uint8_t slaveAddr = 1;
static uint8_t modbus_slave_buf[256] = {0};
static bool status_buf[256] = {0};
static slave_packet_t packet;
static void core_slave_data_parse(uint8_t *data, uint16_t len, slave_packet_t *ptr);
static uint16_t core_build_err_resp(uint8_t code, slave_packet_t *pkt, uint8_t *retData);
static uint8_t core_slave_read(uint8_t funcCode, uint16_t regAddr, uint16_t regNum, uint8_t *retData);
void Modbus_Poll_Init(uint8_t addr) {
slaveAddr = addr;
}
/**
* @brief ??crc
* @param retData
* @param len
* @return
*/
uint16_t add_crc(uint8_t *retData, uint16_t len) {
uint16_t crc = Modbus_Crc_Compute(modbus_slave_buf, len);
modbus_slave_buf[len++] = crc;
modbus_slave_buf[len++] = crc >> 8;
return len;
}
void Modbus_Poll(uint8_t *data, uint16_t len) {
if (len < FIX_MIN_DATA_LEN) return;
if (slaveAddr != data[0] || Modbus_Crc_Compute(data, len) != 0) return;
core_slave_data_parse(data, len, &packet);
uint16_t rspLen = 0;
uint8_t respCode = RSP_OK;
// ?????
switch (packet.funcCode) {
case ReadHoldReg: // 0x3
case ReadInputReg: // 0x4
modbus_slave_buf[rspLen++] = packet.slaveAddr;
modbus_slave_buf[rspLen++] = packet.funcCode;
modbus_slave_buf[rspLen++] = packet.regNum * 2;
respCode = core_slave_read(packet.funcCode, packet.regAddr, packet.regNum, modbus_slave_buf + rspLen);
if (respCode == RSP_OK) {
rspLen += (packet.regNum * 2);
rspLen = add_crc(modbus_slave_buf, rspLen);
}
break;
case ReadCoilState:
case ReadInputState:
// 01 01 00 01 00 01 AC 0A
// 01 01 00 01 00 0A ED CD
modbus_slave_buf[rspLen++] = packet.slaveAddr;
modbus_slave_buf[rspLen++] = packet.funcCode;
// ??????
if (packet.regNum % 8 == 0) {
modbus_slave_buf[rspLen++] = packet.regNum / 8;
} else {
modbus_slave_buf[rspLen++] = packet.regNum / 8 + 1;
}
if (packet.funcCode == ReadCoilState) {
respCode = Slave_ReadCoilState(packet.regAddr, packet.regNum, status_buf);
} else {
respCode = Slave_ReadInputState(packet.regAddr, packet.regNum, status_buf);
}
if (respCode == RSP_OK) {
uint16_t cnt = PackBoolArray(modbus_slave_buf + rspLen, status_buf, packet.regNum);;
rspLen += cnt;
rspLen = add_crc(modbus_slave_buf, rspLen);
}
break;
case WriteOneReg: // 0x06
respCode = Slave_WriteOneReg(packet.regAddr, modbus_u8_to_u16(packet.data[0], packet.data[1]));
if (respCode == RSP_OK) {
modbusSendCallBack(data, len);
return;
}
break;
case WriteMulReg: // 0x10
case WriteMulCoilsReg:
if (packet.funcCode == WriteMulCoilsReg) {
UnPackBool(status_buf, packet.regNum, packet.data, packet.dataLen);
respCode = Slave_WriteMulCoilsReg(packet.regAddr, packet.regNum, status_buf);
} else {
respCode = Slave_WriteMulReg(packet.regAddr, packet.regNum, packet.data);
}
if (respCode == RSP_OK) {
modbus_slave_buf[rspLen++] = packet.slaveAddr;
modbus_slave_buf[rspLen++] = packet.funcCode;
modbus_slave_buf[rspLen++] = packet.regAddr >> 8;
modbus_slave_buf[rspLen++] = packet.regAddr;
modbus_slave_buf[rspLen++] = packet.regNum >> 8;
modbus_slave_buf[rspLen++] = packet.regNum;
rspLen = add_crc(modbus_slave_buf, rspLen);
modbusSendCallBack(modbus_slave_buf, rspLen);
return;
}
break;
bool stat;
case WriteOneCoil:
stat = modbus_u8_to_u16(*packet.data, *(packet.data + 1)) == 0xFF;
respCode = Slave_WriteOneCoil(packet.regAddr, stat);
if (respCode == RSP_OK) {
modbusSendCallBack(modbus_slave_buf, rspLen);
return;
}
break;
}
// ????
if (respCode != RSP_OK) {
rspLen = core_build_err_resp(respCode, &packet, modbus_slave_buf);
}
modbusSendCallBack(modbus_slave_buf, rspLen);
}
/**
* @brief ??????
* @param funcCode
* @param regAddr
* @param regNum
* @param retData
* @return
*/
uint8_t core_slave_read(uint8_t funcCode, uint16_t regAddr, uint16_t regNum, uint8_t *retData) {
switch (funcCode) {
case ReadHoldReg:
return Slave_ReadHoldReg(packet.regAddr, packet.regNum, retData);
case ReadInputReg:
return Slave_ReadInputReg(packet.regAddr, packet.regNum, retData);
}
return 0;
}
/**
* @brief ????
* @param data
* @param len
* @param ptr
*/
static void core_slave_data_parse(uint8_t *data, uint16_t len, slave_packet_t *ptr) {
uint8_t idx = 0;
ptr->slaveAddr = data[idx++];
ptr->funcCode = data[idx++];
ptr->regAddr = modbus_u8_to_u16(data[idx++], data[idx++]);
switch (ptr->funcCode) {
case ReadHoldReg:
case ReadInputReg:
case ReadCoilState:
case ReadInputState:
ptr->regNum = modbus_u8_to_u16(data[idx++], data[idx++]);
break;
case WriteOneReg:
case WriteOneCoil:
ptr->data = data + idx;
ptr->dataLen = 2;
break;
case WriteMulReg:
case WriteMulCoilsReg:
ptr->regNum = modbus_u8_to_u16(data[idx++], data[idx++]);
ptr->dataLen = data[idx++];
ptr->data = data + idx;
break;
}
}
/**
* @brief
* @param code
* @param pkt
* @param retData
* @return
*/
static uint16_t core_build_err_resp(uint8_t code, slave_packet_t *pkt, uint8_t *retData) {
uint8_t idx = 0;
retData[idx++] = pkt->slaveAddr;
retData[idx++] = pkt->funcCode | 0x80;
retData[idx++] = 2;
uint16_t crc = Modbus_Crc_Compute(retData, idx);
retData[idx++] = crc;
retData[idx++] = crc >> 8;
return idx;
}
uint16_t reg_start_addr = 0x000;
uint8_t reg_buf[200] = {0, 1};
/**
* @brief ????
* @param regAddr
* @param regNum
* @param retData
* @return
*/
Slave_Rsp_Code Slave_ReadHoldReg(uint16_t regAddr, uint16_t regNum, uint8_t *retData) {
if (regAddr < reg_start_addr) {
return RSP_ERR_REG_ADDR;
} else {
memcpy(retData, reg_buf, regNum * 2);
return RSP_OK;
}
}/***************************************************************????********************************************************/
/**
* @brief ???????
* @param regAddr
* @param regNum
* @param retData
* @return
*/
Slave_Rsp_Code Slave_ReadInputReg(uint16_t regAddr, uint16_t regNum, uint8_t *retData) {
return 0;
}
Slave_Rsp_Code Slave_ReadCoilState(uint16_t regAddr, uint16_t num, bool *retData) {
printf("Slave_ReadCoilState reg: %X; num:%d\n", regAddr, num);
for (int i = 0; i < num; ++i) {
retData[i] = true;
}
return RSP_OK;
}
Slave_Rsp_Code Slave_ReadInputState(uint16_t regAddr, uint16_t regNum, bool *retData) {
printf("Slave_ReadInputState reg: %X; num:%d\n", regAddr, regNum);
return RSP_OK;
}
Slave_Rsp_Code Slave_WriteOneReg(uint16_t regAddr, uint16_t data) {
printf("reg: %X; val:%d\n", regAddr, data);
return RSP_ERR_REG_ADDR;
}
Slave_Rsp_Code Slave_WriteMulReg(uint16_t regAddr, uint16_t regNum, uint8_t *data) {
uint8_t idx = 0;
for (int i = 0; i < regNum; ++i) {
printf("val:%d\n", modbus_u8_to_u16(data[idx++], data[idx++]));
}
return RSP_OK;
}
Slave_Rsp_Code Slave_WriteMulCoilsReg(uint16_t regAddr, uint16_t regNum, bool *data) {
printf("Slave_WriteMulCoilsReg reg: %X; num:%d\n", regAddr, regNum);
return RSP_OK;
}
Slave_Rsp_Code Slave_WriteOneCoil(uint16_t regAddr, bool val) {
return RSP_ERR_REG_ADDR;
}
@@ -0,0 +1,55 @@
#include "modbus_core_crc.h"
static uint16_t crcTb[];
/**
* @brief Modbus crc count
* @param buf
* @param bufLen
* @return
*/
uint16_t Modbus_Crc_Compute( uint8_t *buf, uint16_t bufLen) {
uint8_t num;
uint16_t modbus16 = UINT16_MAX;
for (uint16_t index = 0; index < bufLen; ++index) {
num = (uint8_t) (modbus16 & UINT32_MAX);
modbus16 = (uint16_t) (((uint32_t) modbus16 >> 8) ^ crcTb[(num ^ buf[index]) & UINT8_MAX]);
}
return modbus16;
}
static uint16_t crcTb[] = {
0X0000, 0XC0C1, 0XC181, 0X0140, 0XC301, 0X03C0, 0X0280, 0XC241,
0XC601, 0X06C0, 0X0780, 0XC741, 0X0500, 0XC5C1, 0XC481, 0X0440,
0XCC01, 0X0CC0, 0X0D80, 0XCD41, 0X0F00, 0XCFC1, 0XCE81, 0X0E40,
0X0A00, 0XCAC1, 0XCB81, 0X0B40, 0XC901, 0X09C0, 0X0880, 0XC841,
0XD801, 0X18C0, 0X1980, 0XD941, 0X1B00, 0XDBC1, 0XDA81, 0X1A40,
0X1E00, 0XDEC1, 0XDF81, 0X1F40, 0XDD01, 0X1DC0, 0X1C80, 0XDC41,
0X1400, 0XD4C1, 0XD581, 0X1540, 0XD701, 0X17C0, 0X1680, 0XD641,
0XD201, 0X12C0, 0X1380, 0XD341, 0X1100, 0XD1C1, 0XD081, 0X1040,
0XF001, 0X30C0, 0X3180, 0XF141, 0X3300, 0XF3C1, 0XF281, 0X3240,
0X3600, 0XF6C1, 0XF781, 0X3740, 0XF501, 0X35C0, 0X3480, 0XF441,
0X3C00, 0XFCC1, 0XFD81, 0X3D40, 0XFF01, 0X3FC0, 0X3E80, 0XFE41,
0XFA01, 0X3AC0, 0X3B80, 0XFB41, 0X3900, 0XF9C1, 0XF881, 0X3840,
0X2800, 0XE8C1, 0XE981, 0X2940, 0XEB01, 0X2BC0, 0X2A80, 0XEA41,
0XEE01, 0X2EC0, 0X2F80, 0XEF41, 0X2D00, 0XEDC1, 0XEC81, 0X2C40,
0XE401, 0X24C0, 0X2580, 0XE541, 0X2700, 0XE7C1, 0XE681, 0X2640,
0X2200, 0XE2C1, 0XE381, 0X2340, 0XE101, 0X21C0, 0X2080, 0XE041,
0XA001, 0X60C0, 0X6180, 0XA141, 0X6300, 0XA3C1, 0XA281, 0X6240,
0X6600, 0XA6C1, 0XA781, 0X6740, 0XA501, 0X65C0, 0X6480, 0XA441,
0X6C00, 0XACC1, 0XAD81, 0X6D40, 0XAF01, 0X6FC0, 0X6E80, 0XAE41,
0XAA01, 0X6AC0, 0X6B80, 0XAB41, 0X6900, 0XA9C1, 0XA881, 0X6840,
0X7800, 0XB8C1, 0XB981, 0X7940, 0XBB01, 0X7BC0, 0X7A80, 0XBA41,
0XBE01, 0X7EC0, 0X7F80, 0XBF41, 0X7D00, 0XBDC1, 0XBC81, 0X7C40,
0XB401, 0X74C0, 0X7580, 0XB541, 0X7700, 0XB7C1, 0XB681, 0X7640,
0X7200, 0XB2C1, 0XB381, 0X7340, 0XB101, 0X71C0, 0X7080, 0XB041,
0X5000, 0X90C1, 0X9181, 0X5140, 0X9301, 0X53C0, 0X5280, 0X9241,
0X9601, 0X56C0, 0X5780, 0X9741, 0X5500, 0X95C1, 0X9481, 0X5440,
0X9C01, 0X5CC0, 0X5D80, 0X9D41, 0X5F00, 0X9FC1, 0X9E81, 0X5E40,
0X5A00, 0X9AC1, 0X9B81, 0X5B40, 0X9901, 0X59C0, 0X5880, 0X9841,
0X8801, 0X48C0, 0X4980, 0X8941, 0X4B00, 0X8BC1, 0X8A81, 0X4A40,
0X4E00, 0X8EC1, 0X8F81, 0X4F40, 0X8D01, 0X4DC0, 0X4C80, 0X8C41,
0X4400, 0X84C1, 0X8581, 0X4540, 0X8701, 0X47C0, 0X4680, 0X8641,
0X8201, 0X42C0, 0X4380, 0X8341, 0X4100, 0X81C1, 0X8081, 0X4040
};
+299
View File
@@ -0,0 +1,299 @@
#include "modbus_core.h"
#include "slave_rtu.h"
#include "main.h"
#define FIX_MIN_DATA_LEN 8
typedef struct {
uint8_t slaveAddr;
uint8_t funcCode;
uint8_t regAddr;
uint8_t regNum;
uint8_t *data;
uint16_t dataLen;
} slave_packet_t;
static uint8_t slaveAddr = 1;
static uint8_t modbus_slave_buf[256] = {0};
static bool status_buf[256] = {0};
static slave_packet_t packet;
static void core_slave_data_parse(uint8_t *data, uint16_t len, slave_packet_t *ptr);
static uint16_t core_build_err_resp(uint8_t code, slave_packet_t *pkt, uint8_t *retData);
static uint8_t core_slave_read(uint8_t funcCode, uint16_t regAddr, uint16_t regNum, uint8_t *retData);
void Modbus_Poll_Init(uint8_t addr) {
slaveAddr = addr;
}
/**
* @brief ??crc
* @param retData
* @param len
* @return
*/
uint16_t add_crc(uint8_t *retData, uint16_t len) {
uint16_t crc = Modbus_Crc_Compute(modbus_slave_buf, len);
modbus_slave_buf[len++] = crc;
modbus_slave_buf[len++] = crc >> 8;
return len;
}
void Modbus_Poll(uint8_t *data, uint16_t len) {
//two error return
if (len < FIX_MIN_DATA_LEN) return;//data to little
if (slaveAddr != data[0] || Modbus_Crc_Compute(data, len) != 0) return;//return error addr | error crc
//
core_slave_data_parse(data, len, &packet);
uint16_t rspLen = 0;
uint8_t respCode = RSP_OK;
switch (packet.funcCode) {
case ReadHoldReg: // 0x3
modbus_slave_buf[rspLen++] = packet.slaveAddr;
modbus_slave_buf[rspLen++] = packet.funcCode;
modbus_slave_buf[rspLen++] = packet.regNum * 2;
respCode = core_slave_read(packet.funcCode, packet.regAddr, packet.regNum, modbus_slave_buf + rspLen);
if (respCode == RSP_OK) {
rspLen += (packet.regNum * 2);
rspLen = add_crc(modbus_slave_buf, rspLen);
}
break;
case ReadInputReg: // 0x4
modbus_slave_buf[rspLen++] = packet.slaveAddr;
modbus_slave_buf[rspLen++] = packet.funcCode;
modbus_slave_buf[rspLen++] = packet.regNum * 2;
respCode = core_slave_read(packet.funcCode, packet.regAddr, packet.regNum, modbus_slave_buf + rspLen);
if (respCode == RSP_OK) {
rspLen += (packet.regNum * 2);
rspLen = add_crc(modbus_slave_buf, rspLen);
}
break;
case ReadCoilState:
case ReadInputState:
// 01 01 00 01 00 01 AC 0A
// 01 01 00 01 00 0A ED CD
modbus_slave_buf[rspLen++] = packet.slaveAddr;
modbus_slave_buf[rspLen++] = packet.funcCode;
// ??????
if (packet.regNum % 8 == 0) {
modbus_slave_buf[rspLen++] = packet.regNum / 8;
} else {
modbus_slave_buf[rspLen++] = packet.regNum / 8 + 1;
}
if (packet.funcCode == ReadCoilState) {
respCode = Slave_ReadCoilState(packet.regAddr, packet.regNum, status_buf);
} else {
respCode = Slave_ReadInputState(packet.regAddr, packet.regNum, status_buf);
}
if (respCode == RSP_OK) {
uint16_t cnt = PackBoolArray(modbus_slave_buf + rspLen, status_buf, packet.regNum);;
rspLen += cnt;
rspLen = add_crc(modbus_slave_buf, rspLen);
}
break;
case WriteOneReg: // 0x06
respCode = Slave_WriteOneReg(packet.regAddr, modbus_u8_to_u16(packet.data[0], packet.data[1]));
if (respCode == RSP_OK) {
modbusSendCallBack(data, len);
return;
}
break;
case WriteMulReg: // 0x10
case WriteMulCoilsReg:
if (packet.funcCode == WriteMulCoilsReg) {
UnPackBool(status_buf, packet.regNum, packet.data, packet.dataLen);
respCode = Slave_WriteMulCoilsReg(packet.regAddr, packet.regNum, status_buf);
} else {
respCode = Slave_WriteMulReg(packet.regAddr, packet.regNum, packet.data);
}
if (respCode == RSP_OK) {
modbus_slave_buf[rspLen++] = packet.slaveAddr;
modbus_slave_buf[rspLen++] = packet.funcCode;
modbus_slave_buf[rspLen++] = packet.regAddr >> 8;
modbus_slave_buf[rspLen++] = packet.regAddr;
modbus_slave_buf[rspLen++] = packet.regNum >> 8;
modbus_slave_buf[rspLen++] = packet.regNum;
rspLen = add_crc(modbus_slave_buf, rspLen);
modbusSendCallBack(modbus_slave_buf, rspLen);
return;
}
break;
bool stat;
case WriteOneCoil:
stat = modbus_u8_to_u16(*packet.data, *(packet.data + 1)) == 0xFF;
respCode = Slave_WriteOneCoil(packet.regAddr, stat);
if (respCode == RSP_OK) {
modbusSendCallBack(modbus_slave_buf, rspLen);
return;
}
break;
}
// ????
if (respCode != RSP_OK) {
rspLen = core_build_err_resp(respCode, &packet, modbus_slave_buf);
}
modbusSendCallBack(modbus_slave_buf, rspLen);
}
/**
* @brief ??????
* @param funcCode
* @param regAddr
* @param regNum
* @param retData
* @return
*/
uint8_t core_slave_read(uint8_t funcCode, uint16_t regAddr, uint16_t regNum, uint8_t *retData) {
switch (funcCode) {
//HoldReg pack
case ReadHoldReg:
return Slave_ReadHoldReg(packet.regAddr, packet.regNum, retData);
case ReadInputReg:
return Slave_ReadInputReg(packet.regAddr, packet.regNum, retData);
}
return 0;
}
/**
* @brief ????
* @param data
* @param len
* @param ptr
*/
static void core_slave_data_parse(uint8_t *data, uint16_t len, slave_packet_t *ptr) {
uint8_t idx = 0;
ptr->slaveAddr = data[idx++];
ptr->funcCode = data[idx++];
ptr->regAddr = modbus_u8_to_u16(data[idx++], data[idx++]);
switch (ptr->funcCode) {
case ReadHoldReg:
case ReadInputReg:
case ReadCoilState:
case ReadInputState:
ptr->regNum = modbus_u8_to_u16(data[idx++], data[idx++]);
break;
case WriteOneReg:
case WriteOneCoil:
ptr->data = data + idx;
ptr->dataLen = 2;
break;
case WriteMulReg:
case WriteMulCoilsReg:
ptr->regNum = modbus_u8_to_u16(data[idx++], data[idx++]);
ptr->dataLen = data[idx++];
ptr->data = data + idx;
break;
}
}
/**
* @brief
* @param code
* @param pkt
* @param retData
* @return
*/
static uint16_t core_build_err_resp(uint8_t code, slave_packet_t *pkt, uint8_t *retData) {
uint8_t idx = 0;
retData[idx++] = pkt->slaveAddr;
retData[idx++] = pkt->funcCode | 0x80;
retData[idx++] = 2;
uint16_t crc = Modbus_Crc_Compute(retData, idx);
retData[idx++] = crc;
retData[idx++] = crc >> 8;
return idx;
}
uint16_t reg_start_addr = 0x000;
//uint8_t reg_buf[4] = {0,0,0,0};
//void get_temp(void)
//{
// for(int i=0;i<4;i++)
// {
// reg_buf[i]=temp_value[i];
// }
//}
/**
* @brief ????
* @param regAddr
* @param regNum
* @param retData
* @return
*/
Slave_Rsp_Code Slave_ReadHoldReg(uint16_t regAddr, uint16_t regNum, uint8_t *retData) {
// if (regAddr < reg_start_addr) {
// return RSP_ERR_REG_ADDR;
// } else {
// get_temp();
// memcpy(retData, reg_buf, regNum * 2);
return RSP_OK;
// }
}/***************************************************************????********************************************************/
/**
* @brief ???????
* @param regAddr
* @param regNum
* @param retData
* @return
*/
Slave_Rsp_Code Slave_ReadInputReg(uint16_t regAddr, uint16_t regNum, uint8_t *retData) {
return 0;
}
Slave_Rsp_Code Slave_ReadCoilState(uint16_t regAddr, uint16_t num, bool *retData) {
printf("Slave_ReadCoilState reg: %X; num:%d\n", regAddr, num);
for (int i = 0; i < num; ++i) {
retData[i] = true;
}
return RSP_OK;
}
Slave_Rsp_Code Slave_ReadInputState(uint16_t regAddr, uint16_t regNum, bool *retData) {
printf("Slave_ReadInputState reg: %X; num:%d\n", regAddr, regNum);
return RSP_OK;
}
Slave_Rsp_Code Slave_WriteOneReg(uint16_t regAddr, uint16_t data) {
printf("reg: %X; val:%d\n", regAddr, data);
return RSP_ERR_REG_ADDR;
}
Slave_Rsp_Code Slave_WriteMulReg(uint16_t regAddr, uint16_t regNum, uint8_t *data) {
uint8_t idx = 0;
for (int i = 0; i < regNum; ++i) {
printf("val:%d\n", modbus_u8_to_u16(data[idx++], data[idx++]));
}
return RSP_OK;
}
Slave_Rsp_Code Slave_WriteMulCoilsReg(uint16_t regAddr, uint16_t regNum, bool *data) {
printf("Slave_WriteMulCoilsReg reg: %X; num:%d\n", regAddr, regNum);
return RSP_OK;
}
Slave_Rsp_Code Slave_WriteOneCoil(uint16_t regAddr, bool val) {
return RSP_ERR_REG_ADDR;
}
@@ -0,0 +1,39 @@
#ifndef PROCOTOCOLBUILDPROJ_MODBUS_CORE_H
#define PROCOTOCOLBUILDPROJ_MODBUS_CORE_H
#include "string.h"
#include "stdbool.h"
#include "modbus_core_define.h"
#include "modbus_core_crc.h"
#include "slave_rtu.h"
//#include "modbus_core_slave.h"
extern SwSendDataCallBack modbusSendCallBack;
extern SwRecDataCallBack modbusRecCallBack;
// send callback
__attribute__((unused)) void Modbus_RegistrySendCallBack(SwSendDataCallBack sendDataCallBack);
// over call back
__attribute__((unused)) void Modbus_RegistryRecCallBack(SwRecDataCallBack recDataCallBack);
/**
* @brief bool to byte
* @param dst save data
* @param data bool data
* @param dataLen data legth
* @return
*/
uint16_t PackBoolArray(uint8_t *dst, const bool *data, uint16_t dataLen);
/**
* @brief bool to byte
* @param dst save data
* @param data bool data
* @param dataLen data legth
* @return
*/
void UnPackBool(bool *dst, uint16_t cnt, const uint8_t *data, uint16_t dataLen);
#endif //PROCOTOCOLBUILDPROJ_MODBUS_CORE_H
@@ -0,0 +1,8 @@
#ifndef PROCOTOCOLBUILDPROJ_MODBUS_CORE_CRC_H
#define PROCOTOCOLBUILDPROJ_MODBUS_CORE_CRC_H
#include "modbus_core_define.h"
uint16_t Modbus_Crc_Compute(uint8_t *buf, uint16_t bufLen);
#endif //PROCOTOCOLBUILDPROJ_MODBUS_CORE_CRC_H
@@ -0,0 +1,56 @@
#ifndef PROCOTOCOLBUILDPROJ_MODBUS_CORE_DEFINE_H
#define PROCOTOCOLBUILDPROJ_MODBUS_CORE_DEFINE_H
#include <stdint.h>
#include "stdio.h"
typedef enum {
/**
* @brief read coil
*/
ReadCoilState = 0x1,
/**
* @brief read coil input
*/
ReadInputState = 0x2,
/**
* @brief read hold resi
*/
ReadHoldReg = 0x3,
/**
* @brief read input
*/
ReadInputReg = 0x4,
/**
* @brief write one coil
*/
WriteOneCoil = 0x05,
/**
* @brief wirte one resig
*/
WriteOneReg = 0x06,
/**
* @brief wirte nore resig
*/
WriteMulReg = 0x10,
/**
* @brief wirete more coil
*/
WriteMulCoilsReg = 0x0F,
} Modbus_FuncCode_TypeDef;
typedef enum {
// error data
InvalidDataErrorCode = 0x2,
// legth over
RecDataLenErrorCode = 0xFF,
} Modbus_RecCode_TypeDef;
#define modbus_u8_to_u16(a, b) (uint16_t)((uint16_t)((a)<<8)+(b))
// call back resig pointer
typedef void (*SwSendDataCallBack)(void *data, uint16_t len);
// resive pointer
typedef uint16_t (*SwRecDataCallBack)(void *recDataBuf);
#endif //PROCOTOCOLBUILDPROJ_MODBUS_CORE_DEFINE_H
+102
View File
@@ -0,0 +1,102 @@
#ifndef PROCOTOCOLBUILDPROJ_SLAVE_RTU_H
#define PROCOTOCOLBUILDPROJ_SLAVE_RTU_H
#include "modbus_core_define.h"
typedef enum {
RSP_OK = 0x0,
// 不支持的功能码
RSP_ERR_CMD = 0x1,
// 寄存器地址错误
RSP_ERR_REG_ADDR = 0x2,
// 数据值域错误
RSP_ERR_VALUE = 0x3,
// 写入失败
RSP_ERR_WRITE = 0x4,
} Slave_Rsp_Code;
/**
* @brief 从机地址
* @param addr
*/
void Modbus_Poll_Init(uint8_t addr);
/**
* @brief 主调用函数
* @param data
* @param len
*/
void Modbus_Poll(uint8_t *data, uint16_t len);
/**
* @brief
* @param regAddr
* @param regNum
* @param retData
*/
Slave_Rsp_Code Slave_ReadHoldReg(uint16_t regAddr, uint16_t regNum, uint8_t *retData);
/**
* @brief 0x4
* @param regAddr
* @param regNum
* @param retData
* @return
*/
Slave_Rsp_Code Slave_ReadInputReg(uint16_t regAddr, uint16_t regNum, uint8_t *retData);
/**
* @brief 读取线圈状态
* @param regAddr
* @param regNum 单字节个数
* @param retData
* @return
*/
Slave_Rsp_Code Slave_ReadCoilState(uint16_t regAddr, uint16_t regNum, bool *retData);
/**
* @brief 读取输入状态
* @param regAddr
* @param regNum 单字节个数
* @param retData
* @return
*/
Slave_Rsp_Code Slave_ReadInputState(uint16_t regAddr, uint16_t regNum, bool *retData);
/**
* @brief 写一个寄存器
* @param regAddr
* @param data
* @return
*/
Slave_Rsp_Code Slave_WriteOneReg(uint16_t regAddr, uint16_t data);
/**
* @brief 连续写多个寄存器
* @param regAddr
* @param regNum
* @param data
* @return
*/
Slave_Rsp_Code Slave_WriteMulReg(uint16_t regAddr, uint16_t regNum, uint8_t *data);
/**
* @brief 写多个寄存器
* @param regAddr
* @param regNum 单字节个数
* @param data
* @return
*/
Slave_Rsp_Code Slave_WriteMulCoilsReg(uint16_t regAddr, uint16_t regNum, bool *data);
/**
* @brief 写一个线圈寄存器
* @param regAddr
* @param val
* @return
*/
Slave_Rsp_Code Slave_WriteOneCoil(uint16_t regAddr, bool val);
#endif //PROCOTOCOLBUILDPROJ_SLAVE_RTU_H