ADC_HandleTypeDef hadc;
TIM_HandleTypeDef htim;
GPIO_InitTypeDef GPIO_InitStruct;
void SystemClock_Config(void);
void ADC_Config(void);
void PWM_Config(void);
void LCD_Config(void);
void delay_ms(uint32_t ms);
int main(void)
{
HAL_Init();
SystemClock_Config();
ADC_Config();
PWM_Config();
LCD_Config();
HAL_ADC_Start(&hadc);
while (1)
{
uint32_t weight = HAL_ADC_GetValue(&hadc);
printf("Weight: %lu g\n", weight);
// Decide whether to feed according to weight
if (weight < 500)
{
// Set the motor PWM duty cycle and start the motor
HAL_TIM_PWM_Start(&htim, TIM_CHANNEL_1);
}
else
{
HAL_TIM_PWM_Stop(&htim, TIM_CHANNEL_1);
}
delay_ms(1000);
}
}
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct. = RCC_PLL_ON;
RCC_OscInitStruct. = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct. = 16;
RCC_OscInitStruct. = 336;
RCC_OscInitStruct. = RCC_PLLP_DIV4;
RCC_OscInitStruct. = 7;
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 ADC_Config(void)
{
ADC_ChannelConfTypeDef sConfig = {0};
__HAL_RCC_ADC1_CLK_ENABLE();
= ADC1;
= ADC_CLOCK_SYNC_PCLK_DIV4;
= ADC_RESOLUTION_12B;
= ADC_SCAN_DISABLE;
= ENABLE;
= DISABLE;
= ADC_EXTERNALTRIGCONVEDGE_NONE;
= ADC_SOFTWARE_START;
= ADC_DATAALIGN_RIGHT;
= 1;
= DISABLE;
= DISABLE;
if (HAL_ADC_Init(&hadc) != HAL_OK)
{
Error_Handler();
}
= WEIGHT_ADC_CHANNEL;
= 1;
= ADC_SAMPLETIME_3CYCLES;
if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
{
Error_Handler();
}
}
void PWM_Config(void)
{
TIM_OC_InitTypeDef sConfigOC = {0};
GPIO_InitStruct.Pin = MOTOR_GPIO_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
GPIO_InitStruct.Alternate = GPIO_AF2_TIM4;
HAL_GPIO_Init(MOTOR_GPIO_PORT, &GPIO_InitStruct);
__HAL_RCC_TIM4_CLK_ENABLE();
= TIM4;
= 84;
= TIM_COUNTERMODE_UP;
= 2000;
= TIM_CLOCKDIVISION_DIV1;
if (HAL_TIM_PWM_Init(&htim) != HAL_OK)
{
Error_Handler();
}
= TIM_OCMODE_PWM1;
= TIM_OCPOLARITY_HIGH;
= TIM_OCFAST_DISABLE;
= TIM_OCNPOLARITY_HIGH;
= TIM_OCNIDLESTATE_RESET;
=