#include <stdint.h>
#define RCC_Base 0x40021000
#define GPIOA_Base 0x50000000
#define ADC_Base 0x40012400
uint32_t *AHBENR = (uint32_t*)(RCC_Base + 0x34);
uint32_t *APB2ENR = (uint32_t*) (RCC_Base + 0x40);
uint32_t *GPIOA_Moder = (uint32_t*) (GPIOA_Base + 0x00);
uint32_t *GPIOA_InReg = (uint32_t*)(GPIOA_Base + 0x10);
uint32_t *ADC1_CR = (uint32_t*) (ADC_Base + 0x08);
uint32_t *ADC1_DR = (uint32_t*) (ADC_Base + 0x40);
uint32_t *ADC1_CHSELR = (uint32_t*) (ADC_Base + 0x28);
uint32_t *ADC1_ISR = (uint32_t*) (ADC_Base + 0x00);
uint32_t *ADC1_SMPR = (uint32_t*) (ADC_Base + 0x14);
uint32_t adc_val;
void setup()
{
Serial.begin(115200);
Serial.println("Hello, STM32!");
GPIO_init();
ADC1_init();
}
void loop()
{
adc_val = ADC1_read();
Serial.println(adc_val);
delay(1000);
}
void GPIO_init()
{
*AHBENR |= (1<<0); // Enable GPIO clock
*APB2ENR |= (1 << 20); // Enable ADC clock
*GPIOA_Moder |= (3<<4); //Set PA2 to Analog Mode
}
void ADC1_init()
{
*ADC1_CR |= (1<<28); //Enable Volt Reg
for(int lc=0;lc<1000;lc++);
*ADC1_CR |= (1<<31); //Callibration
//while(*ADC1_CR & (1<<31));
*ADC1_ISR |= (1<<0);//Ready
*ADC1_CR |= (1<<0);//Enable
while(!(*ADC1_ISR & (1<<0)));
*ADC1_CHSELR = (1<<0);
*ADC1_SMPR |= (9<<0);
}
uint32_t ADC1_read()
{
*ADC1_CR |= (1 << 2); //Start conversion
while (!(*ADC1_ISR & (1 << 2))); //Wait till conversion is over
return *ADC1_DR;
}
/*Resolution value
value =10k
total steps = 4096
value per step = 10k/4096
input = 0-3.3v
Vmax = 3.3
Res = 3.3/4096
*/