硬件核心代码 温湿度获取 及USB串口通讯

/* 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 "i2c.h"
#include "rtc.h"
#include "spi.h"
#include "usart.h"
#include "usb_device.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#define AHT21_ADDRESS   0x38
#include 
#include 
#include "AHT_Sensor.h"
#include "ds18b20.h"
#include "W25QXX.h"
#include "stm32f1xx_it.h"
#include "usbd_cdc_if.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* 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 -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint8_t wData[0x100];   //写缓存数组
uint8_t rData[0x100];   //读缓存数组
uint8_t ID[4];          //设备ID缓存数组
uint32_t WriteAddr = 0x0;

int W25Q64Ready = 1; //内部数据存储模块就绪【后续监测如果发现失败自动会设置为0】
int I2C1_Sensor = 1; //传感器模块就绪【后续监测如果发现失败自动会设置为0】
int BluMechineConnectReady = 1; //蓝牙模块就绪【后续监测如果发现失败自动会设置为0】
int I2C2_Sensor = 1; //血氧及心率采集模块就绪【后续监测如果发现失败自动会设置为0】
RTC_DateTypeDef GetData;  //获取日期结构体
RTC_TimeTypeDef GetTime;   //获取时间结构体
char* SystemMessage;
int LED_X = 0;
int LED_Y = 0;
int MaxSizeLedOfX = 128; //LED 分辨率
int MaxSizeLedOfY = 128; //LED 分辨率
//uint32_t ReadAddr=0x0;
/* 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_I2C2_Init();
    MX_SPI1_Init();
    MX_SPI2_Init();
    MX_USART1_UART_Init();
    MX_USART2_UART_Init();
    MX_I2C1_Init();
    MX_USB_DEVICE_Init();
    MX_RTC_Init();
    /* USER CODE BEGIN 2 */
    Init_I2C_Sensor_Port();
    float humidity = 0;
    float temperature = 0;
    InitW25QXXSystem();//初始化W25Q64
    /* USER CODE END 2 */
    //SendCmdToLed("CLR(0)");
    //ShowTextToLed("系统开始启动!");
    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while(1)
    {
        /* USER CODE BEGIN 3 */
        //ShowTextToLed("系统开始监测传感器!");
        uint32_t CT_data[2];
        char message[520] = {'\0'};
        /***********************************************************************************/
        /**///①刚上电,产品芯片内部就绪需要时间,延时100~500ms,建议500ms
        /***********************************************************************************/
        //SendSystemDataToCom();
        HAL_Delay(500);
        /***********************************************************************************/
        /**///②上电第一次发0x71读取状态字,判断状态字是否为0x18,如果不是0x18,进行寄存器初始化
        /***********************************************************************************/
        if((AHT20_Read_Status() & 0x18) != 0x18)
        {
            AHT20_Start_Init(); //重新初始化寄存器
            HAL_Delay(10);
        }
        /***********************************************************************************/
        /**///③根据客户自己需求发测量命令读取温湿度数据,当前while(1)循环发测量命令读取温湿度数据,仅供参考
        /***********************************************************************************/
        HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, GPIO_PIN_RESET);
        //AHT20_Read_CTdata(CT_data);       //不经过CRC校验,直接读取AHT20的温度和湿度数据    推荐每隔大于1S读一次
        AHT20_Read_CTdata_crc(CT_data);  //crc校验后,读取AHT20的温度和湿度数据
        humidity = CT_data[0] * 100 * 10 / 1024 / 1024;  //计算得到湿度值c1(放大了10倍)
        temperature = CT_data[1] * 200 * 10 / 1024 / 1024 - 500;//计算得到温度值t1(放大了10倍)
        下一步客户处理显示数据,
        sprintf(message, "AHT25 :\r\n当前湿度: %0.2f\r\n当前温度:%0.2f ℃ \r\n", humidity / 10, temperature / 10+0.9);
        //char DataValue[strlen(message)+1];
        //ShowTextToLed("传感器已读取完成!");
        //ShowTextToLed(message);
        //HAL_UART_Transmit(&huart1, (uint8_t*)DataValue, sizeof(DataValue), 1000);
        //strcpy(DataValue,message);
        CDC_Transmit_FS((uint8_t*)message, sizeof(message));
        //SendMessage(message);
//        if(W25Q64Ready == 1)
//        {
//            if(BSP_W25Qx_Write((uint8_t*)message, WriteAddr, strlen(message)) == W25Qx_OK)
//            {
//                WriteAddr += sizeof(message);//写入的地址执行累加 方便后面继续添加
//            }
//            else
//            {
//                //写入失败 发出警告
//                char* NoteText = "Something wrong in  Write Data To Flash\r\n";
//                HAL_UART_Transmit(&huart1, (uint8_t*)NoteText, strlen(NoteText), 1000);
//            }
//        }
        /***********************************************************************************/
        HAL_GPIO_WritePin(GPIOB, GPIO_PIN_8, GPIO_PIN_SET);
        HAL_Delay(500);
        /* USER CODE END 3 */
    }
    /* USER CODE END WHILE */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
    RCC_OscInitTypeDef RCC_OscInitStruct = {0};
    RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
    RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

    /** Initializes the RCC Oscillators according to the specified parameters
    * in the RCC_OscInitTypeDef structure.
    */
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_HSE;
    RCC_OscInitStruct.HSEState = RCC_HSE_ON;
    RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
    RCC_OscInitStruct.HSIState = RCC_HSI_ON;
    RCC_OscInitStruct.LSIState = RCC_LSI_ON;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
    RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL6;
    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_CLOCKTYPE_PCLK2;
    RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
    RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
    RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

    if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
    {
        Error_Handler();
    }
    PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_USB;
    PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
    PeriphClkInit.UsbClockSelection = RCC_USBCLKSOURCE_PLL_DIV1_5;
    if(HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
    {
        Error_Handler();
    }
}

/* USER CODE BEGIN 4 */
void ShowTextToLed(char* text)
{
    //int LED_X=0;
    //int LED_Y=0;
    //int MaxSizeLedOfX=128;//LED 分辨率
    //int MaxSizeLedOfY=128;//LED 分辨率
    const int DateLength = strlen(text) + 20;
    char DataValue[DateLength];
    sprintf(DataValue, "DC16(%d,%d,\'%s\',2); \r\n", LED_X, LED_Y, text);
    int TotalPix = DateLength * 16 + LED_X + LED_Y;
    LED_X = TotalPix / MaxSizeLedOfX + 16;
    LED_Y = TotalPix % MaxSizeLedOfX;
    if(LED_X > MaxSizeLedOfX)LED_X = 0;
    if(LED_Y > MaxSizeLedOfY)LED_Y = 0;
    //SystemMessage = "DC16(0,30,\'\',1); \r\n";
    HAL_UART_Transmit(&huart1, (uint8_t*)DataValue, sizeof(DataValue), 1000);
    HAL_Delay(50);
}
void SendCmdToLed(char* text)
{
    strcat(text, ";\r\n");
    HAL_UART_Transmit(&huart1, (uint8_t*)text, strlen(text), 1000);
    HAL_Delay(50);
}
void InitW25QXXSystem()
{
    /*-Step1- 验证设备ID  ************************************************Step1*/
    uint32_t i;
    BSP_W25Qx_Init();
    BSP_W25Qx_Read_ID(ID);
    //第一位厂商ID固定0xEF,第二位设备ID根据容量不同,具体为:
    //W25Q16为0x14、32为0x15、40为0x12、64为0x16、80为0x13、128为0x17
    char* UserMessage;
    if((ID[0] != 0xEF) | (ID[1] != 0x16))
    {
        UserMessage = "Step1 W25Qxx ID 获取失败 设备未就绪 后续关于存储的测试及检查操作已终止!\r\n";
        HAL_UART_Transmit(&huart1, (uint8_t*)UserMessage, strlen(UserMessage), 1000);
        W25Q64Ready = 0;
        return;
    }
    else
    {
        HAL_UART_Transmit(&huart1, (uint8_t*)UserMessage, strlen(UserMessage), 1000);
    }
    /*-Step2- 擦除块  ************************************************Step2*/
    if(BSP_W25Qx_Erase_Block(0) == W25Qx_OK)
        HAL_UART_Transmit(&huart1, (uint8_t*)"QSPI Erase Block OK!\r\n", sizeof("QSPI Erase Block OK!\r\n"), 1000);
    else
        HAL_UART_Transmit(&huart1, (uint8_t*)"Something wrong in Step2\r\n", sizeof("Something wrong in Step2\r\n"), 1000);
    /*-Step3- 写数据  ************************************************Step3*/
    for(i = 0; i < 0x100; i ++)
    {
        wData[i] = i;
        rData[i] = 0;
    }
    if(BSP_W25Qx_Write(wData, 0x00, 0x100) == W25Qx_OK)
        HAL_UART_Transmit(&huart1, (uint8_t*)"QSPI Write OK!\r\n", sizeof("QSPI Write OK!\r\n"), 1000);
    else
        HAL_UART_Transmit(&huart1, (uint8_t*)"Something wrong in Step3\r\n", sizeof("Something wrong in Step3\r\n"), 1000);
    /*-Step4- 读数据  ************************************************Step4*/
    if(BSP_W25Qx_Read(rData, 0x00, 0x100) == W25Qx_OK)
        HAL_UART_Transmit(&huart1, (uint8_t*)"QSPI Read ok\r\n\r\n", sizeof("QSPI Read ok\r\n\r\n"), 1000);
    else
        HAL_UART_Transmit(&huart1, (uint8_t*)"Something wrong in Step4\r\n", sizeof("Something wrong in Step4\r\n"), 1000);
    HAL_UART_Transmit(&huart1, (uint8_t*)"QSPI Read Data : \r\n", sizeof("QSPI Read Data : \r\n"), 1000);
    for(i = 0; i < 0x100; i++)
        sprintf(UserMessage, "0x%02X", rData[i]);
    sprintf(UserMessage, "%s%s", UserMessage, "\r\n\r\n");
    HAL_UART_Transmit(&huart1, (uint8_t*)UserMessage, strlen(UserMessage), 1000);
    /*-Step5- 数据对比  ************************************************Step5*/
    if(memcmp(wData, rData, 0x100) == 0)
        HAL_UART_Transmit(&huart1, (uint8_t*)"W25Q64FV QuadSPI Test OK\r\n", sizeof("W25Q64FV QuadSPI Test OK\r\n"), 1000);
    else
        HAL_UART_Transmit(&huart1, (uint8_t*)"W25Q64FV QuadSPI Test False\r\n", sizeof("W25Q64FV QuadSPI Test False\r\n"), 1000);
    /*-Step6- 擦除整个芯片  ************************************************Step6*/
    BSP_W25Qx_Erase_Chip();
    /* USER CODE END 2 */
}
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
    //串口的中断回调函数
    char* UserTest;
    if(GPIO_Pin == GPIO_PIN_8)
    {
        UserTest = "您按下了PA8按钮!";
    }
    else
    {
        UserTest = "您按下了除PA8以外部分的按钮!";
    }
    CDC_Transmit_FS((uint8_t*)UserTest, strlen(UserTest));
}
void SendSystemDataToCom()
{
    char UserMessage[100];
    HAL_RTC_GetTime(&hrtc, &GetTime, RTC_FORMAT_BIN);//获取时间
    /* Get the RTC current Date */
    HAL_RTC_GetDate(&hrtc, &GetData, RTC_FORMAT_BIN);//获取日期
    /* Display date Format : yy/mm/dd */
    sprintf(UserMessage, "当日日期:%02d-%02d-%02d\r\n", 2000 + GetData.Year, GetData.Month, GetData.Date);
    CDC_Transmit_FS((uint8_t*)UserMessage, strlen(UserMessage));
    /* Display date Format : weekday */
    char* WeekDayStr;
    if(GetData.WeekDay == 1)
    {
        WeekDayStr = "星期一\r\n";
    }
    else if(GetData.WeekDay == 2)
    {
        WeekDayStr = "星期二\r\n";
    }
    else if(GetData.WeekDay == 3)
    {
        WeekDayStr = "星期三\r\n";
    }
    else if(GetData.WeekDay == 4)
    {
        WeekDayStr = "星期四\r\n";
    }
    else if(GetData.WeekDay == 5)
    {
        WeekDayStr = "星期五\r\n";
    }
    else if(GetData.WeekDay == 6)
    {
        WeekDayStr = "星期六\r\n";
    }
    else if(GetData.WeekDay == 7)
    {
        WeekDayStr = "星期日\r\n";
    }
    CDC_Transmit_FS((uint8_t*)WeekDayStr, strlen(WeekDayStr));
    HAL_Delay(50);
    /* Display time Format : hh:mm:ss */
    sprintf(UserMessage, "当日时间:%02d:%02d:%02d\r\n", GetTime.Hours, GetTime.Minutes, GetTime.Seconds);
    CDC_Transmit_FS((uint8_t*)UserMessage, strlen(UserMessage));
    HAL_Delay(50);
}
/* 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 */
}

你可能感兴趣的:(单片机,stm32,嵌入式硬件)