Doornect

Sistema para automatização e integração IoT de portas, permitindo fazer o controle de entrada e manuseio a distância.

IntermediateFull instructions provided3 days150
Doornect

Things used in this project

Hardware components

STM32 Nucleo-64 Board
STMicroelectronics STM32 Nucleo-64 Board
×1
NodeMCU ESP8266 Breakout Board
NodeMCU ESP8266 Breakout Board
×1
SG90 Micro-servo motor
SG90 Micro-servo motor
×1
LED (generic)
LED (generic)
+resistor
×2
Buzzer
Buzzer
*projeto futuro
×1
Rotary potentiometer (generic)
Rotary potentiometer (generic)
*projeto futuro
×1
Grove - 12-Channel Capacitive Touch Keypad (ATtiny1616)
Seeed Studio Grove - 12-Channel Capacitive Touch Keypad (ATtiny1616)
*projeto futuro
×1
PIR Motion Sensor (generic)
PIR Motion Sensor (generic)
*projeto futuro
×1

Software apps and online services

Firebase
Google Firebase

Hand tools and fabrication machines

3D Printer (generic)
3D Printer (generic)

Story

Read more

Custom parts and enclosures

Prototipo basico 3D

Prototipo basico 3D

Prototipo basico 3D

Protótipo básico para impressão 3D de um modelo compatível com servo para testar sistema

Prototipo basico 3D

Schematics

Imagem do esquema

Doornect Schematics

Diagrama do projecto Doornect.

Pinpad, Buzzer, potenciômetro e sensor de presença estão instalados como exemplo apenas, não estão inclusos na versão atual do codigo.

Code

STM Nucleo

C/C++
Código para STM Nucleo 32 usado a CubeIDE
/* 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 "cmsis_os.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

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

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define SERVO_MIN_PULSE_WIDTH 1000
#define SERVO_MAX_PULSE_WIDTH 2000
#define SERVO_PERIOD 20000
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;

TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim3;

UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;

osThreadId defaultTaskHandle;
/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_ADC1_Init(void);
static void MX_TIM3_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_TIM2_Init(void);
void StartDefaultTask(void const * argument);

/* USER CODE BEGIN PFP */
int16_t readVoltage(void);
void openGate(void * vParam);
void closeGate(void * vParam);
void gateSensor(void * vParam);
void cli(void * vParam);
void sendChar(unsigned char c);
void pwm_task(void * vParam);
void user_pwm_setvalue(uint16_t value);
char readChar(int uart_number);
void checkPass(void *vParam);
/* 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)
{
  /* USER CODE BEGIN 1 */
  int ck = 0;
  /* 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_USART2_UART_Init();
  MX_ADC1_Init();
  MX_TIM3_Init();
  MX_USART1_UART_Init();
  MX_TIM2_Init();
  /* USER CODE BEGIN 2 */
  HAL_TIM_Base_Start_IT(&htim3);
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_2);
  /* USER CODE END 2 */

  /* USER CODE BEGIN RTOS_MUTEX */
  /* add mutexes, ... */
  /* USER CODE END RTOS_MUTEX */

  /* USER CODE BEGIN RTOS_SEMAPHORES */
  /* add semaphores, ... */
  /* USER CODE END RTOS_SEMAPHORES */

  /* USER CODE BEGIN RTOS_TIMERS */
  /* start timers, add new ones, ... */
  /* USER CODE END RTOS_TIMERS */

  /* USER CODE BEGIN RTOS_QUEUES */
  /* add queues, ... */
  /* USER CODE END RTOS_QUEUES */

  /* Create the thread(s) */
  /* definition and creation of defaultTask */
  osThreadDef(defaultTask, StartDefaultTask, osPriorityNormal, 0, 128);
  defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL);

  /* USER CODE BEGIN RTOS_THREADS */
  /* add threads, ... */
//  xTaskCreate(
//    pwm_task, /* Nome da funcao que contem a task */
//    "pwm_task", /* Nome descritivo */
//    configMINIMAL_STACK_SIZE, /* tamanho da pilha da task */
//    NULL, /* parametro para a task */
//    1, /* nivel de prioridade */
//    NULL); /* ponteiro para o handle da task */
  xTaskCreate(
       cli,
       "serialRcvr",
       configMINIMAL_STACK_SIZE,
       &ck,
       1,
       NULL);
  xTaskCreate(
         openGate,
         "opengateAdm",
         configMINIMAL_STACK_SIZE,
         &ck,
         1,
         NULL);
  xTaskCreate(
           closeGate,
           "closegateAdm",
           configMINIMAL_STACK_SIZE,
           &ck,
           1,
           NULL);
  xTaskCreate(
         gateSensor,
         "gatesensor",
         configMINIMAL_STACK_SIZE,
         &ck,
         1,
         NULL);
  xTaskCreate(
		   checkPass,
           "checkPass",
           configMINIMAL_STACK_SIZE,
           &ck,
           1,
           NULL);

  //THREADS ATIVIDADES

  /* USER CODE END RTOS_THREADS */

  /* Start scheduler */
  osKernelStart();

  /* We should never get here as control is now taken by the scheduler */
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* 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
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  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 = 1;
  RCC_OscInitStruct.PLL.PLLN = 10;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  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_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief ADC1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_ADC1_Init(void)
{

  /* USER CODE BEGIN ADC1_Init 0 */

  /* USER CODE END ADC1_Init 0 */

  ADC_MultiModeTypeDef multimode = {0};
  ADC_ChannelConfTypeDef sConfig = {0};

  /* USER CODE BEGIN ADC1_Init 1 */

  /* USER CODE END ADC1_Init 1 */

  /** Common config
  */
  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_DISABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  hadc1.Init.LowPowerAutoWait = DISABLE;
  hadc1.Init.ContinuousConvMode = DISABLE;
  hadc1.Init.NbrOfConversion = 1;
  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_PRESERVED;
  hadc1.Init.OversamplingMode = DISABLE;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure the ADC multi-mode
  */
  multimode.Mode = ADC_MODE_INDEPENDENT;
  if (HAL_ADCEx_MultiModeConfigChannel(&hadc1, &multimode) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_5;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_2CYCLES_5;
  sConfig.SingleDiff = ADC_SINGLE_ENDED;
  sConfig.OffsetNumber = ADC_OFFSET_NONE;
  sConfig.Offset = 0;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC1_Init 2 */

  /* USER CODE END ADC1_Init 2 */

}

/**
  * @brief TIM2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 15;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 9999;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 0;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */
  HAL_TIM_MspPostInit(&htim2);

}

/**
  * @brief TIM3 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM3_Init(void)
{

  /* USER CODE BEGIN TIM3_Init 0 */

  /* USER CODE END TIM3_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM3_Init 1 */

  /* USER CODE END TIM3_Init 1 */
  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 400-1;
  htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim3.Init.Period = 10000-1;
  htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM3_Init 2 */

  /* USER CODE END TIM3_Init 2 */

}

/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
static 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.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  /* USER CODE END USART1_Init 2 */

}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static 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.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 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7|GPIO_PIN_8, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10, GPIO_PIN_RESET);

  /*Configure GPIO pin : B1_Pin */
  GPIO_InitStruct.Pin = B1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : PA6 */
  GPIO_InitStruct.Pin = GPIO_PIN_6;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*Configure GPIO pins : PA7 PA8 */
  GPIO_InitStruct.Pin = GPIO_PIN_7|GPIO_PIN_8;
  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 : PB10 */
  GPIO_InitStruct.Pin = GPIO_PIN_10;
  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 pin : PC7 */
  GPIO_InitStruct.Pin = GPIO_PIN_7;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

int16_t readVoltage(void){

    HAL_ADC_Start(&hadc1);

    HAL_ADC_PollForConversion(&hadc1, HAL_MAX_DELAY);

    return HAL_ADC_GetValue(&hadc1);
}

void sendChar(unsigned char c){
	unsigned char pChar = c;
	HAL_UART_Transmit(&huart1, &pChar,1 ,HAL_MAX_DELAY );
}

char readChar(int uart_number){
	unsigned char caracter;

	if(uart_number == 1){
		while(HAL_UART_Receive(&huart1, &caracter, 1, HAL_MAX_DELAY) != HAL_OK);
	}
	else if(uart_number == 2){
		while(HAL_UART_Receive(&huart2, &caracter, 1, HAL_MAX_DELAY) != HAL_OK);
	}
	return caracter;
}

void openGate(void * vParam)
{
	int *ck = (int *)vParam;
	while(1)
	{
		if(*ck == 1){
			HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10, 0);// BUZZER
			sendChar('o');
			vTaskDelay(180);
			*ck = 2;
		}
	}
}

void closeGate(void * vParam)
{
	int *ck = (int *)vParam;
	while(1)
	{
		if(*ck == 3){
//			int delay = 2000;
//			int reset = 2000;
//			while(delay > 0){
//				if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_6) == 1){
//					HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10, 1);// BUZZER
//					*ck = 1;
//				}
//				if(*ck != 3){
//					delay = reset;// FALTA ARRCHAMENTO
//				}
//				vTaskDelay(1);
//				delay--;
//			}
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, 0);// Verde
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, 1);// Vermelho
			sendChar('c');
			vTaskDelay(2000);
			*ck = 0;
		}
	}
}

void gateSensor(void * vParam)
{
	int *ck = (int *)vParam;
	float power = 5;
	while(1)
	{
		if(*ck == 2){
			// int vol = readVoltage();
			// vol = power * vol / 4095;
			// int delay = vol*2000 + 2000;
			int delay = 4000;

			while(delay > 0)
			{
//				if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_6) == 1){// SENSOR
//					HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10, 1);// BUZZER
//					delay++;
//				} else if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_6) == 0){
//					HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10, 0);// BUZZER
//				}
				vTaskDelay(1);
				delay--;
			}
			if(delay == 0){
				*ck = 3;
			}
		}
	}
}

void cli(void * vParam)
{
	int *ck = (int *)vParam;
	int pinpad = 0;
	*ck = 0;
	unsigned char caracter;
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, 0);// Verde
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, 1);// Vermelho

	while(1)
	{
		caracter = readChar(1);
		if((caracter == 'o' || pinpad == 1) && *ck == 0) {
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, 1);// VERDE
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, 0);
			*ck = 1;
		} else if (*ck==0){
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, 0);
			vTaskDelay(100);
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, 1);
		}
	}
}

void checkPass(void *vParam) {
	int *ck = (int *)vParam;
	while(1){
		int botao = HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_6);
		if(botao == 1){// SENSOR
			HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10, 1);// BUZZER
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_7, 1);// VERDE
			HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, 0);
			*ck = 1;
		} else if(botao == 0){
			HAL_GPIO_WritePin(GPIOB, GPIO_PIN_10, 0);// BUZZER
		}
	}
}


//CODIGOS NAO UTILIZADOS NO MOMENTO
//
//void pwm_task(void * vParam)
//{
// int pwm_value = 1000;
// int step = 100;
// while(1)
// {
// vTaskDelay(100);
//// int vol = readVoltage();
//// vol = vol/2;
// if(pwm_value == 0) step = 100;
// if(pwm_value == 2000) step = -100;
// pwm_value += step;
//
// user_pwm_setvalue(pwm_value);
// }
//}
//
//void user_pwm_setvalue(uint16_t value)
//{
//
// HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_1);
// 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);
//}
/* USER CODE END 4 */

/* USER CODE BEGIN Header_StartDefaultTask */
/**
  * @brief  Function implementing the defaultTask thread.
  * @param  argument: Not used
  * @retval None
  */
/* USER CODE END Header_StartDefaultTask */
void StartDefaultTask(void const * argument)
{
  /* USER CODE BEGIN 5 */
  /* Infinite loop */
  for(;;)
  {
    osDelay(1);
  }
  /* USER CODE END 5 */
}

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM1 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM1) {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */
  if (htim->Instance == htim3.Instance) {
  /* Toggle LED */
  HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5);
  }
  /* USER CODE END Callback 1 */
}

/**
  * @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 */

Node MCU

C/C++
Código para Node MCU ESP8266
/*
 * Created by K. Suwatchai (Mobizt)
 *
 * Email: k_suwatchai@hotmail.com
 *
 * Github: https://github.com/mobizt/Firebase-ESP8266
 *
 * Copyright (c) 2023 mobizt
 *
 */

/** This example will show how to authenticate using
 * the legacy token or database secret with the new APIs (using config and auth data).
 */
#include <SoftwareSerial.h>
#include <Servo.h>
#include <Arduino.h>
#if defined(ESP32)
#include <WiFi.h>
#include <FirebaseESP32.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#include <FirebaseESP8266.h>
#elif defined(ARDUINO_RASPBERRY_PI_PICO_W)
#include <WiFi.h>
#include <FirebaseESP8266.h>
#endif

// Provide the RTDB payload printing info and other helper functions.
#include <addons/RTDBHelper.h>

#define Pin_ST_NUCLEO_RX 5
#define Pin_ST_NUCLEO_TX 4

Servo myservo;

int pos = 0;
int once = 0;
char nucleo = 'a';

SoftwareSerial SSerial(Pin_ST_NUCLEO_RX, Pin_ST_NUCLEO_TX);

/* 1. Define the WiFi credentials */
#define WIFI_SSID "fernando"
#define WIFI_PASSWORD "carvalho"
// #define WIFI_SSID "Moto Gomes50"
// #define WIFI_PASSWORD "Mateus6462"
#define DATABASE_URL "https://embarcados-8bba0-default-rtdb.firebaseio.com/"
#define DATABASE_SECRET "nAXtG5zXcUw4HMG6ZncryWNKCKQemeWRgGSksDB9"

/* 3. Define the Firebase Data object */
FirebaseData fbdo;

/* 4, Define the FirebaseAuth data for authentication data */
FirebaseAuth auth;

/* Define the FirebaseConfig data for config data */
FirebaseConfig config;

unsigned long dataMillis = 0;

#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
WiFiMulti multi;
#endif

void setup()
{
    pos = 0;
    once = 0;
    nucleo = 'a';
    Serial.begin(115200);
    SSerial.begin(115200);

    myservo.attach(2);
    myservo.write(0);

#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
    multi.addAP(WIFI_SSID, WIFI_PASSWORD);
    multi.run();
#else
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
#endif

    Serial.print("Connecting to Wi-Fi");
    unsigned long ms = millis();
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(300);
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
        if (millis() - ms > 10000)
            break;
#endif
    }
    Serial.println();
    Serial.print("Connected with IP: ");
    Serial.println(WiFi.localIP());
    Serial.println();

    Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION);

    /* Assign the certificate file (optional) */
    // config.cert.file = "/cert.cer";
    // config.cert.file_storage = StorageType::FLASH;

    /* Assign the database URL and database secret(required) */
    config.database_url = DATABASE_URL;
    config.signer.tokens.legacy_token = DATABASE_SECRET;

    Firebase.reconnectWiFi(true);

    // The WiFi credentials are required for Pico W
    // due to it does not have reconnect feature.
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
    config.wifi.clearAP();
    config.wifi.addAP(WIFI_SSID, WIFI_PASSWORD);
#endif

    /* Initialize the library with the Firebase authen and config */
    Firebase.begin(&config, &auth);

    // Or use legacy authenticate method
    // Firebase.begin(DATABASE_URL, DATABASE_SECRET);
}

void loop() {
  if (millis() - dataMillis > 100) {
    dataMillis = millis();
    
    bool door_status = false;
    bool lockdown_status = false;

    Serial.printf("Getting lockdown info... %s\n", Firebase.RTDB.getInt( & fbdo, "/lockdown", & lockdown_status) ? String(lockdown_status).c_str() : fbdo.errorReason().c_str());

    if (lockdown_status == false) {
      Serial.printf("Get door info... %s\n", Firebase.RTDB.getBool( & fbdo, "/Door", & door_status) ? String(door_status).c_str() : fbdo.errorReason().c_str());

      if(door_status == true) {
        SSerial.write('o');
      } else if (door_status == false) {
        SSerial.write('c');
      }

      if (SSerial.available()) {
        nucleo = SSerial.read();
        if (nucleo == 'o' && once == 0) {
          //Serial.printf("Abrindo porta... %s\n", Firebase.RTDB.setBool( & fbdo, "/Door", true) ? "ok" : fbdo.errorReason().c_str());
          once = 1;
          for (pos; pos < 180; pos += 1) {
            if (SSerial.read() == 'c') {
              Serial.printf("\n\n\nMANDOU FECHAR QUANDO TAVA ABRINDO\n\n\n");
              Serial.printf("Abrindo porta... %s\n", Firebase.RTDB.setBool( & fbdo, "/Door", false) ? "ok" : fbdo.errorReason().c_str());
              nucleo = 'c';
              break;
            }
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(1);                       // waits 15 ms for the servo to reach the position
          }
        }
        if (nucleo == 'c' && once == 1) {
          Serial.printf("\n\n\nMANDOU FECHAR DE FAT\n\n\n");
          Serial.printf("Fechando porta... %s\n", Firebase.RTDB.setBool( & fbdo, "/Door", false) ? "ok" : fbdo.errorReason().c_str());
          once = 0;
          for (pos; pos >= 0; pos -= 1) {
            if (SSerial.read() == 'o' && once == 0) {
              Serial.printf("Abrindo porta... %s\n", Firebase.RTDB.setBool( & fbdo, "/Door", true) ? "ok" : fbdo.errorReason().c_str());
              nucleo = 'o';
              once = 1;
              break;
            }
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(1);                       // waits 15 ms for the servo to reach the position
          }
        }
      } 
    } else if (lockdown_status == true) {
      Serial.printf("Abrindo porta... %s\n", Firebase.RTDB.setBool( & fbdo, "/Door", false) ? "ok" : fbdo.errorReason().c_str());
    }
  }
}

Front HTML

HTML
HTML do exemplo de frontend
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Html Generated</title>
    <meta name="description" content="Figma htmlGenerator">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="htmlGenerator">
    <link href="https://fonts.googleapis.com/css?family=Helvetica&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <style>
        body {
          font-family: Helvetica, sans-serif;
          background: linear-gradient(to right, #007991, #78ffd6); /* Muda esse krai ai */
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          margin: 0;
          position: relative; 
          overflow: hidden; 
        }

        body::after {
          content: '';
          position: absolute;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          background: radial-gradient(circle at 50% 50%, transparent, #003E4B 50%);
          opacity: 0.5;
          z-index: -1;
        }

        .container {
          display: flex;
          flex-direction: column;
          align-items: center;
          margin: 0 auto;
          max-width: 375px;
          background: #fff;
          padding: 50px;
          border-radius: 8px;
          position: relative; 
          z-index: 1; 
        }

        .logo {
          width: 80%;
          height: auto;
        }

        .switch {
          position: relative;
          display: inline-block;
          width: 60px;
          height: 34px;
        }

        .switch input {
          opacity: 0;
          width: 0;
          height: 0;
        }

        .slider {
          position: absolute;
          cursor: pointer;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: #ccc;
          -webkit-transition: .4s;
          transition: .4s;
        }

        .slider:before {
          position: absolute;
          content: "";
          height: 26px;
          width: 26px;
          left: 4px;
          bottom: 4px;
          background-color: white;
          -webkit-transition: .4s;
          transition: .4s;
        }

        input:checked + .slider {
          background-color: #2196F3;
        }

        input:focus + .slider {
          box-shadow: 0 0 1px #2196F3;
        }

        input:checked + .slider:before {
          -webkit-transform: translateX(26px);
          -ms-transform: translateX(26px);
          transform: translateX(26px);
        }

        .slider.round {
          border-radius: 34px;
        }

        .slider.round:before {
          border-radius: 50%;
        }


		.status {
		  text-align: center;
		}

		.status-text {
		  font-size: 24px;
		  font-weight: bold;
		}


        @media (max-width: 768px) {
          .container {
            padding: 20px; 
          }
          
          .logo {
            width: 100%;
          }

          .button, .status-text {
            font-size: 16px;
          }
          
          .door-icon {
            width: 40px;
          }
        }
    </style>
</head>
<body>
  <div class="container">
    <img class="logo" src="images/logo.png" alt="Logo">
    <br>
    <br>
    <label class="switch">
      <input type="checkbox" id="power-button">
      <span class="slider round"></span>
    </label>
    <br>
    <div class="door-action">
      <img class="door-icon open" src="images/light_m_3x_1.png" alt="Porta Aberta">
      <button class="button" id="open-button">Abrir</button>
    </div>
    <div class="door-action">
      <img class="door-icon lockdown" src="images/lockdown_3x_1.png" alt="Lockdown">
      <button class="button" id="lockdown-button">Lockdown</button>
    </div>    
    <div class="status">
      <p class="status-text">ESTADO ATUAL:</p>
      <img class="door-icon" id="current-state" src="fechada_img_url" alt="Estado Atual">
    </div>
  </div>
     <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js"></script>
    <script src="app.js"></script>
</body>
</html>

Front CSS

CSS
CSS do exemplo de front
body {
  font-family: Arial, sans-serif;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
  max-width: 375px;
}

.logo {
  width: 100%;
  height: auto;
}

.button {
  margin: 20px 0;
  padding: 10px;
  font-size: 18px;
}

.door-action {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.door-icon {
  width: 50px;
  height: auto;
}

.status {
  text-align: center;
}

.status-text {
  font-size: 24px;
  font-weight: bold;
}

Front JavaScript

JavaScript
Exemplo de JavaScript para o front. Chaves API do firebase e Twilio foram redigidas. Use esse codigo com cautela, o nível de segurança é muito baixo e todas as chaves ficam expostas, deve ser usado como exemplo de negocio apenas.
var config = {
  apiKey: "x",
  authDomain: "x",
  databaseURL: "x",
  storageBucket: "x"
};

firebase.initializeApp(config);

var database = firebase.database();

var systemRef = database.ref('system');
var doorRef = database.ref('Door');
var lockdownRef = database.ref('lockdown');

var powerButton = document.getElementById('power-button');
var openButton = document.getElementById('open-button');
var lockdownButton = document.getElementById('lockdown-button');
var currentStatusImg = document.getElementById('current-state');
var statusText = document.querySelector('.status-text');

function errorHandler(error) {
  statusText.innerText = 'Desconectado';
  currentStatusImg.src = 'images/xmark.icloud.fill@20x.png';
}

// Listen for changes
systemRef.on('value', function(snapshot) {
  var systemStatus = snapshot.val();
  powerButton.checked = systemStatus;
  if (!systemStatus) {
      statusText.innerText = 'Sistema Desligado';
      currentStatusImg.src = 'images/Asset 5@3x.png';
  }
}, errorHandler);

doorRef.on('value', function(snapshot) {
  var doorStatus = snapshot.val();
  if (doorStatus !== null) {
      statusText.innerText = doorStatus ? 'Aberto' : 'Fechado';
      currentStatusImg.src = doorStatus ? 'images/status_open.png' : 'images/status_closed_3x_1.png';
      if (doorStatus) {
        fetch('https://api.twilio.com/2010-04-01/Accounts/APIKEY/Messages.json', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Authorization': 'Basic ' + btoa('APIKEY')
          },
          body: new URLSearchParams({
            'To': 'NUMBER',
            'From': 'NUMBER',
            'Body': 'Porta Aberta!'
          })
        })
        .then(response => console.log(response))
        .catch(error => console.error(error));
      }
  }
}, errorHandler);



lockdownRef.on('value', function(snapshot) {
  var lockdownStatus = snapshot.val();
  if (lockdownStatus !== null) {
      statusText.innerText = lockdownStatus ? 'Lockdown' : statusText.innerText;
      currentStatusImg.src = lockdownStatus ? 'images/lockdown_3x_1.png' : currentStatusImg.src;
  }
}, errorHandler);

// Toggle boolean value in Firebase
function toggleValue(ref) {
  ref.transaction(function(currentValue) {
      return !currentValue;
  });
}

// Event listeners for the buttons
powerButton.addEventListener('change', function() { toggleValue(systemRef); });
openButton.addEventListener('click', function() { toggleValue(doorRef); });
lockdownButton.addEventListener('click', function() { toggleValue(lockdownRef); });

Front SCSS

SCSS
Fonte para front
$helvetica-font : "Helvetica"

Credits

TIBERIO GOUVEIA DE CERQUEIRA
1 project • 0 followers
Mateus Araujo
1 project • 0 followers

Comments