/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2019 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the License; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        www.st.com/SLA0044
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include"main.h"
#include "adc.h"
#include "usart.h"
#include "i2c.h"
#include "tim.h"
#include "stm32f4xx_hal.h"
#include "gpio.h"

/* Private variables ---------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/
#define VECT_TAB_OFFSET  0x10000
int tankstatus = 0;
uint8_t zigbeecmd1[5]={0xFE,0x00,0x01,0x00,0x01};
uint8_t zigbeecmd2[5]={0xFE,0x00,0x02,0x00,0x02};
uint8_t zigbeestatu[20];
uint8_t zigbeestatu1[5];
uint8_t zigbeecon[7]="connect";
uint8_t zigbeenotcon[11]="not connect";
uint8_t zigbeechang[14]="change is down";
uint16_t M4_AD_Value = 0;
float M4_voltage_V =0;
float M4_pH_mid = 1.500;
float M4_pH_low = 2.030;
float M4_pH_high =0.975;
float M4_PH=0;
uint8_t soil[8] ={0x01,0x03,0x00,0x00,0x00,0x03,0x05,0xCB};
uint8_t data[11] ={0,0,0,0,0,0,0,0,0,0,0};
float M8_Soil =0;
int rh=0;
int temp=0;
int ec=0;
uint8_t cmd[7]={0xFF,0x00,0x00,0x00,0x00,0x00,0x0D};
HAL_StatusTypeDef Status;
#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC
#define ADDR_AT24C04_WRITE_FIRST_16_PAGES 0xEC
#define ADDR_AT24C04_READ 0xED
#define AT24C04_TIMEOUT 0xED
#define AT24C04_PAGE_SIZE 16
#define BUFFER_SIZE 1
uint16_t dig_T1;
uint16_t dig_T2;
uint16_t dig_T3;
uint16_t dig_P1;
uint16_t dig_P2;
uint16_t dig_P3;
uint16_t dig_P4;
uint16_t dig_P5;
uint16_t dig_P6;
uint16_t dig_P7;
uint16_t dig_P8;
uint16_t dig_P9;
uint32_t adc_P=0;
uint32_t adc_T=0;
uint8_t WriteBuffer[BUFFER_SIZE]={0xb6};
uint8_t WriteBuffer1[BUFFER_SIZE]={0xff};
uint8_t WriteBuffer2[BUFFER_SIZE]={0x00};
uint8_t ReadBuffer[BUFFER_SIZE];
int RH;
float M15_BMP280 =0;
/* USER CODE BEGIN PV */
typedef  void (*pFunction)(void);
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void MX_ADC1_Init1(char pin);
void sensor(void);
void user_pwm_setvalue(uint16_t value);
void user_pwm_setvalue2(uint16_t value);
HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);
HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData);
long bmp280_T_MultipleReadThree(void);
long bmp280_P_MultipleReadThree(void);
short bmp280_MultipleReadTwo(uint16_t addr);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief  The application entry point.
* @retval int
*/
int main(void)
{
  SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET;
  HAL_Init();
  SystemClock_Config();
  MX_GPIO_Init();
  MX_USART2_UART_Init();
  MX_UART4_Init();
  MX_USART1_UART_Init();
  HAL_UART_Transmit(&huart2, (uint8_t *)zigbeecmd2, sizeof(zigbeecmd2), 10);
  HAL_UART_Receive(&huart2, (uint8_t *)zigbeestatu,sizeof(zigbeestatu),2000);
  HAL_UART_Transmit(&huart4, (uint8_t *)zigbeestatu, sizeof(zigbeestatu),10);
  HAL_UART_Transmit(&huart2, (uint8_t *)zigbeecmd1, sizeof(zigbeecmd1), 10);
  HAL_UART_Receive(&huart2, (uint8_t *)zigbeestatu,sizeof(zigbeestatu),2000);
  HAL_UART_Transmit(&huart4, (uint8_t *)zigbeestatu, sizeof(zigbeestatu),10);
  if (zigbeestatu[18]== 0x01)
  {
     HAL_UART_Transmit(&huart4, (uint8_t *)zigbeecon, sizeof(zigbeecon),10);
  }
  else if(zigbeestatu[18]== 0x05 || zigbeestatu[18]== 0x00)
  {
     HAL_UART_Transmit(&huart4, (uint8_t *)zigbeenotcon, sizeof(zigbeenotcon),10);
  }
  MX_TIM2_Init();
  AT24C04_Write(&hi2c1,0xe0,WriteBuffer);
  AT24C04_Write(&hi2c1,0xf4,WriteBuffer1);
  AT24C04_Write(&hi2c1,0xf5,WriteBuffer2);
  dig_T1 = bmp280_MultipleReadTwo(0x88);
  dig_T2 = bmp280_MultipleReadTwo(0x8A);
  dig_T3 = bmp280_MultipleReadTwo(0x8C);
  dig_P1 = bmp280_MultipleReadTwo(0x8E);
  dig_P2 = bmp280_MultipleReadTwo(0x90);
  dig_P3 = bmp280_MultipleReadTwo(0x92);
  dig_P4 = bmp280_MultipleReadTwo(0x94);
  dig_P5 = bmp280_MultipleReadTwo(0x96);
  dig_P6 = bmp280_MultipleReadTwo(0x98);
  dig_P7 = bmp280_MultipleReadTwo(0x9A);
  dig_P8 = bmp280_MultipleReadTwo(0x9C);
  dig_P9 = bmp280_MultipleReadTwo(0x9E);
  while (1)
  {
    sensor();
    if(M4_PH<14 && M4_PH > 0 && M8_Soil > 0 && M15_BMP280 > 0)
    {
         HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_RESET);

         HAL_Delay(10000);

         HAL_GPIO_WritePin(GPIOA,GPIO_PIN_13, GPIO_PIN_SET);

         user_pwm_setvalue2(0);
         user_pwm_setvalue(10);

     
    }
  }
}
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 72;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 3;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_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();
  }
}
void user_pwm_setvalue(uint16_t value)
{
    TIM_OC_InitTypeDef sConfigOC;
    sConfigOC.OCMode = TIM_OCMODE_PWM1;
    sConfigOC.Pulse = value;
    sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
    sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
    HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);
    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
}
void user_pwm_setvalue2(uint16_t value)
{
    TIM_OC_InitTypeDef sConfigOC;
    sConfigOC.OCMode = TIM_OCMODE_PWM1;
    sConfigOC.Pulse = value;
    sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
    sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
    HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2);
    HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);
}
void sensor(void)
{
    adc_T=bmp280_T_MultipleReadThree();
    adc_P=bmp280_P_MultipleReadThree();
    double var1, var2,t_fine;
    var1 = (((double) adc_T) / 16384.0 - ((double) dig_T1) / 1024.0)* ((double) dig_T2);
    var2 = ((((double) adc_T) / 131072.0 - ((double) dig_T1) / 8192.0)* (((double) adc_T) / 131072.0 - ((double) dig_T1) / 8192.0))* ((double) dig_T3);
    t_fine = (int32_t) (var1 + var2);
    double temperature = (var1 + var2) / 5120.0;
    double pressure;
    var1 = (t_fine / 2.0) - 64000.0;
    var2 = var1 * var1 * ((double) dig_P6) / 32768.0;
    var2 = var2 + var1 * ((double) dig_P5) * 2.0;
    var2 = (var2 / 4.0) + (((double) dig_P4) * 65536.0);
    var1 = (((double) dig_P3) * var1 * var1 / 524288.0+ ((double) dig_P2) * var1) / 524288.0;
    var1 = (1.0 + var1 / 32768.0) * ((double) dig_P1);
      if (var1 == 0.0)
      {
         var1 = 0;
      }
    pressure = 1048576.0 - (double) adc_P;
    pressure = (pressure - (var2 / 4096.0)) * 6250.0 / var1;
    var1 = ((double) dig_P9) * pressure * pressure / 2147483648.0;    var2 = pressure * ((double) dig_P8) / 32768.0;
    pressure = pressure + (var1 + var2 + ((double) dig_P7)) / 16.0;
    cmd[1]=pressure/10000; 
    int pa =pressure;
    cmd[2]=(pa%10000)/100;
    cmd[3]=(pa%10000)%100;
    HAL_UART_Transmit(&huart4, (uint8_t *)cmd, sizeof(cmd),1);
    MX_ADC1_Init1(ADC_CHANNEL_0);
    HAL_ADC_Start(&hadc1);
    HAL_ADC_PollForConversion(&hadc1, 50);
    if(HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))
      {
          M4_AD_Value = HAL_ADC_GetValue(&hadc1);
          M4_voltage_V = M4_AD_Value*3.3f/4096;
          if (M4_voltage_V > M4_pH_mid)
           {
               M4_PH = 7.0 - 3.0 / (M4_pH_low - M4_pH_mid) * (M4_voltage_V - M4_pH_mid);
           }
          else
           {
               M4_PH = 7.0 - 3.0 / (M4_pH_mid - M4_pH_high) * (M4_voltage_V - M4_pH_mid);
           }
      }
    HAL_UART_Transmit(&huart4,(unsigned char*)&M4_PH,4,10);
    HAL_UART_Transmit(&huart2, (uint8_t *)soil,sizeof(soil),50);
    HAL_UART_Receive_IT(&huart2, (uint8_t *)data,sizeof(data));
    adc_T=bmp280_T_MultipleReadThree();
    adc_P=bmp280_P_MultipleReadThree();
    double var1, var2,t_fine;
    var1 = (((double) adc_T) / 16384.0 - ((double) dig_T1) / 1024.0)* ((double) dig_T2);
    var2 = ((((double) adc_T) / 131072.0 - ((double) dig_T1) / 8192.0)* (((double) adc_T) / 131072.0 - ((double) dig_T1) / 8192.0))* ((double) dig_T3);
    t_fine = (int32_t) (var1 + var2);
    double temperature = (var1 + var2) / 5120.0;
    double pressure;
    var1 = (t_fine / 2.0) - 64000.0;
    var2 = var1 * var1 * ((double) dig_P6) / 32768.0;
    var2 = var2 + var1 * ((double) dig_P5) * 2.0;
    var2 = (var2 / 4.0) + (((double) dig_P4) * 65536.0);
    var1 = (((double) dig_P3) * var1 * var1 / 524288.0+ ((double) dig_P2) * var1) / 524288.0;
    var1 = (1.0 + var1 / 32768.0) * ((double) dig_P1);
      if (var1 == 0.0)
      {
         var1 = 0;
      }
    pressure = 1048576.0 - (double) adc_P;
    pressure = (pressure - (var2 / 4096.0)) * 6250.0 / var1;
    var1 = ((double) dig_P9) * pressure * pressure / 2147483648.0;    var2 = pressure * ((double) dig_P8) / 32768.0;
    pressure = pressure + (var1 + var2 + ((double) dig_P7)) / 16.0;
    cmd[1]=pressure/10000; 
    int pa =pressure;
    cmd[2]=(pa%10000)/100;
    cmd[3]=(pa%10000)%100;
    HAL_UART_Transmit(&huart4, (uint8_t *)cmd, sizeof(cmd),1);
    HAL_Delay(10000);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
   if (huart->Instance == USART2)
   {
     if (data[0]==0x01 && data[1]==0x03)
     {
       rh = (data[3] << 8) + data[4];
       temp = (data[5] << 8) + data[6];
       ec = (data[7] << 8) + data[8];
     }
   }
}
HAL_StatusTypeDef AT24C04_Write(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)
{
       Status = HAL_I2C_Mem_Write(&hi2c1, ADDR_AT24C04_WRITE_FIRST_16_PAGES, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, AT24C04_PAGE_SIZE, AT24C04_TIMEOUT);
       return Status;
}
HAL_StatusTypeDef AT24C04_Read(I2C_HandleTypeDef *hi2c,uint16_t MemAddress,uint8_t *pData)
{
   Status = HAL_I2C_Mem_Read(&hi2c1, ADDR_AT24C04_READ, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, BUFFER_SIZE, AT24C04_TIMEOUT);
   return Status;
}
  long bmp280_T_MultipleReadThree()
{
     uint8_t msb, lsb, xlsb;
     int32_t temp = 0;
     AT24C04_Read(&hi2c1,0xfa,ReadBuffer);
     msb=ReadBuffer[0];
     AT24C04_Read(&hi2c1,0xfb,ReadBuffer);
     lsb=ReadBuffer[0];
     AT24C04_Read(&hi2c1,0xfc,ReadBuffer);
     xlsb=ReadBuffer[0];
     temp = ((msb << 12)|(lsb << 4)|(xlsb >> 4));
     return temp;
}
long bmp280_P_MultipleReadThree()
{
   uint8_t msb, lsb, xlsb;
   int32_t pressure = 0;
   AT24C04_Read(&hi2c1,0xf7,ReadBuffer);
   msb=ReadBuffer[0];
   AT24C04_Read(&hi2c1,0xf8,ReadBuffer);
   lsb=ReadBuffer[0];
   AT24C04_Read(&hi2c1,0xf9,ReadBuffer);
   xlsb=ReadBuffer[0];
   pressure = ((msb << 12)|(lsb << 4)|(xlsb >> 4));
   return pressure;
}
  short bmp280_MultipleReadTwo(uint16_t addr )
{
   uint8_t msb, lsb;
   uint16_t temp = 0;
   AT24C04_Read(&hi2c1,addr,ReadBuffer);
   lsb = ReadBuffer[0];
   AT24C04_Read(&hi2c1,addr+1,ReadBuffer);
   msb = ReadBuffer[0];
   temp = msb << 8|lsb;
   return temp;
}
void MX_ADC1_Init1(char pin)
{
  ADC_ChannelConfTypeDef sConfig = {0};
  hadc1.Instance = ADC1;
  hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV2;
  hadc1.Init.Resolution = ADC_RESOLUTION_12B;
  hadc1.Init.ScanConvMode = DISABLE;
  hadc1.Init.ContinuousConvMode = DISABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 1;
  hadc1.Init.DMAContinuousRequests = DISABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
    if (HAL_ADC_Init(&hadc1) != HAL_OK)
    {
      Error_Handler();
    }
  sConfig.Channel = pin;
  sConfig.Rank = 1;
  sConfig.SamplingTime = ADC_SAMPLETIME_3CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
}
void MX_GPIO_Input1(unsigned long pin)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  __HAL_RCC_GPIOE_CLK_ENABLE();
  GPIO_InitStruct.Pin = pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_PULLDOWN;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
void Error_Handler(void)
{
}
