#include <stdint.h>
#define RCC_BASE 0x40021000UL
#define RCC_IOPENR (*(volatile uint32_t*)(RCC_BASE + 0x34))
#define GPIOA_BASE 0x50000000UL
#define GPIOA_MODER (*(volatile uint32_t*)(GPIOA_BASE + 0x00))
#define GPIOB_BASE 0x50000400UL
#define GPIOB_MODER (*(volatile uint32_t*)(GPIOB_BASE + 0x00))
#define RCC_APBENR2 (*(volatile uint32_t*)(RCC_BASE + 0x40))
#define ADCEN (1<<20)
#define ADC_BASE 0x40012400UL
#define ADC_CR (*(volatile uint32_t*)(ADC_BASE + 0x08))
#define ADC_ISR (*(volatile uint32_t*)(ADC_BASE + 0x00))
#define ADC_CHSELR (*(volatile uint32_t*)(ADC_BASE + 0x28))
#define ADC_DR (*(volatile uint32_t*)(ADC_BASE + 0x40))
#define ADEN (1<<0) // bit 0 of ADC_CR 0 - disable ADC, 1- enable ADC
#define ADDIS (1<<1) // bit 1 of ADC_CR 0- No ADDIS command, 1- disable ADC
#define ADCAL (1<<31) //bit 31 of ADC_CR 0-cal complete, 1-to calibrate ADC
#define ADSTART (1<<2) //bit 2 of ADC_CR 0-No ADC, 1-to start ADC
#define ADRDY (1<<0) //bit 0 of ADC_ISR 0-ADC not ready, 1-ADC is ready
#define EOC (1<<2) //bit 2 of ADC_ISR 0-channel conversion not complete, 1-completed
#define PA1 (1<<1)
#define RCC_APBENR1 (*(volatile uint32_t*)(RCC_BASE + 0x3C))
#define TIM3EN (1<<1)
#define TIM3_BASE 0x40000400UL
#define TIM3_CR1 (*(volatile uint32_t*)(TIM3_BASE + 0x00))
#define TIM3_CCMR1 (*(volatile uint32_t*)(TIM3_BASE + 0x18))
#define TIM3_CCER (*(volatile uint32_t*)(TIM3_BASE + 0x20))
#define TIM3_PSC (*(volatile uint32_t*)(TIM3_BASE + 0x28))
#define TIM3_ARR (*(volatile uint32_t*)(TIM3_BASE + 0x2C))
#define TIM3_CCR1 (*(volatile uint32_t*)(TIM3_BASE + 0x34))
#define TIM3_EGR (*(volatile uint32_t*)(TIM3_BASE + 0x14))
#define GPIOB_AFRL (*(volatile uint32_t*)(GPIOB_BASE + 0x20))
void ADC_disable(){
if (ADC_CR & ADEN){
ADC_CR |= ADDIS;
while(ADC_CR & ADEN);
}
}
void Start_Cal(){
ADC_CR |= ADCAL;
while(ADC_CR & ADCAL);
}
void Enable_ADC(){
ADC_ISR |= ADRDY;
ADC_CR |= ADEN;
while (!(ADC_ISR & ADRDY ));
}
void Sel_Chnl(){
ADC_CHSELR = PA1 ;
}
void Set_PSC_ARR(){
TIM3_PSC = 11;
TIM3_ARR = 4095;
TIM3_EGR |= (1<<0);
}
void PWM_Confg(){
TIM3_CCMR1 &= ~(7<<4);
TIM3_CCMR1 |= (6<<4);
TIM3_CCMR1 |= (1<<3);
TIM3_CCER |= (1<<0);
TIM3_CR1 |= (1<<7);
TIM3_CR1 |= (1<<0);
}
int main(){
uint32_t adc_value =0;
RCC_IOPENR |= ((1<<0)|(1<<1));
GPIOA_MODER &= ~(3<<(1*2));
GPIOA_MODER |= (3<<(1*2));
GPIOB_MODER &= ~(3<<(4*2));
GPIOB_MODER |= (2<<(4*2));
RCC_APBENR2 |= ADCEN ;
RCC_APBENR1 |= TIM3EN ;
GPIOB_AFRL &= ~ (15<<16);
GPIOB_AFRL |= (1<<16);
// ADC conversion steps
ADC_disable();
Start_Cal();
Enable_ADC();
Sel_Chnl();
// PWM GENERATION STEPS
Set_PSC_ARR();
PWM_Confg();
while(1){
ADC_CR |= ADSTART;
while(!(ADC_ISR & EOC));
adc_value = ADC_DR;
TIM3_CCR1 = adc_value;
}
}