Analog servos with blue pill
Hello everybody! I am working on an animatronic for my niece, and I am using the STM32F103C8T6 blue pill to control it.I want to share the code, (still in progress) hoping it will be useful for some of you.
include "main.h"
void SystemClock_Config(void);
int count;
int adder;
int leg1;
int leg2;
int neck;
int main(void)
{
HAL_Init();
SystemClock_Config();
RCC->APB2ENR |= RCC_APB2ENR_TIM1EN;
TIM1->PSC = 72;
TIM1->CR1 |= TIM_CR1_CEN;
TIM1->ARR = 19999;
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN;
GPIOA->CRH &=~ GPIO_CRH_MODE10;
GPIOA->CRH &=~ GPIO_CRH_CNF10_0;
GPIOA->CRH |= GPIO_CRH_CNF10_1;
GPIOA->ODR &=~ GPIO_ODR_ODR10;
RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;
GPIOB->CRL |= GPIO_CRL_MODE5_0;
GPIOB->CRL &= ~ GPIO_CRL_MODE5_1;
GPIOB->CRL &= ~ GPIO_CRL_CNF5;
GPIOB->CRL |= GPIO_CRL_MODE6_0;
GPIOB->CRL &= ~ GPIO_CRL_MODE6_1;
GPIOB->CRL &= ~ GPIO_CRL_CNF6;
GPIOB->CRH |= GPIO_CRH_MODE12_0;
GPIOB->CRH &= ~ GPIO_CRH_MODE12_1;
GPIOB->CRH &= ~ GPIO_CRH_CNF12;
GPIOA->CRL |= GPIO_CRL_MODE5_0;
GPIOA->CRL &= ~ GPIO_CRL_MODE5_1;
GPIOA->CRL &= ~ GPIO_CRL_CNF5;
GPIOA->CRL |= GPIO_CRL_MODE6_0;
GPIOA->CRL &= ~ GPIO_CRL_MODE6_1;
GPIOA->CRL &= ~ GPIO_CRL_CNF6;
GPIOA->CRL |= GPIO_CRL_MODE7_0;
GPIOA->CRL &= ~ GPIO_CRL_MODE7_1;
GPIOA->CRL &= ~ GPIO_CRL_CNF7;
while (1)
{
if (GPIOA->IDR & GPIO_IDR_IDR10)
{
if (count<70)
{
/*
leg1=1500;
leg2=1850;
neck= 1300;
/
leg1=1500;
leg2=800;
}
else if (count>70 && count<140)
{ /*
leg1=1150;
leg2=1500;
neck=1700;
/
leg1=2200;
leg2=1500;
}
else if (count>=140)
{
count=0;
GPIOA->ODR ^= GPIO_ODR_ODR5;
GPIOA->ODR ^= GPIO_ODR_ODR6;
}
}
else
{
GPIOA->ODR &= ~GPIO_ODR_ODR5;
GPIOA->ODR &= ~GPIO_ODR_ODR6;
/*
leg1=1800;
leg2=1500;
neck=1100;
/
leg1=1500;
leg2=1500;
count=0;
}
if (TIM1->CNT <= leg1)
{
GPIOB->ODR |= GPIO_ODR_ODR5;
if (adder==0 && GPIOA->IDR & GPIO_IDR_IDR10)
{
count++;
adder=1;
}
}
if (TIM1->CNT > leg1)
{
GPIOB->ODR &= ~ GPIO_ODR_ODR5;
adder=0;
}
if (TIM1->CNT <= leg2)
{
GPIOB->ODR |= GPIO_ODR_ODR6;
}
if (TIM1->CNT > leg2)
{
GPIOB->ODR &= ~ GPIO_ODR_ODR6;
}
}
}
void SystemClock_Config(void)
{
RCC->CR |= RCC_CR_HSEON;
while ((RCC->CR & RCC_CR_HSERDY)==0){}
RCC->CFGR &= ~ RCC_CFGR_HPRE;
RCC->CFGR &= ~ RCC_CFGR_PPRE2;
RCC->CFGR |= RCC_CFGR_SW_0;
RCC->CFGR &= ~ RCC_CFGR_SW_1;
while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_HSE) {}
RCC->CR &= ~ RCC_CR_PLLON;
while ((RCC->CR & RCC_CR_PLLRDY) != 0) {}
RCC->CFGR |= RCC_CFGR_PLLSRC;
RCC->CFGR |= RCC_CFGR_PLLMULL;
RCC->CFGR &= ~ RCC_CFGR_PLLMULL_3;
RCC->CR |= RCC_CR_PLLON;
while ((RCC->CR & RCC_CR_PLLRDY)==0){}
RCC->CFGR &= ~ RCC_CFGR_SW_0;
RCC->CFGR |= RCC_CFGR_SW_1;
while ((RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL){}
}
I also include a video of the animatronic
https://www.tiktok.com/@eltallerdelgordo/video/7682951937947471122
