#include "stm32l0xx.h"
__IO uint32_t uwTick;
void SysTick_Delay(__IO uint32_t Delay)
{
uint32_t tickstart = 0U;
tickstart = uwTick;
while((uwTick - tickstart) < Delay)
{
}
}
void RCC_Init(void)
{
/* LSE OFF,LSI DEFAULT,MSI OFF,HSI ON,PLL ON,SYSCLK = 32MHz,CK_PWR = FCLK = HCLK = SysTick = APB1 = APB2 = 32MHz.*/
FLASH->ACR = FLASH_ACR_PRE_READ | FLASH_ACR_PRFTEN;
MODIFY_REG(PWR->CR, PWR_CR_VOS, (PWR_CR_VOS_0));
MODIFY_REG(RCC->CR, RCC_CR_HSION | RCC_CR_HSIDIVEN , RCC_CR_HSION);
while(READ_BIT(RCC->CR, RCC_CR_HSIRDY) == RESET);
MODIFY_REG(RCC->ICSCR, RCC_ICSCR_HSITRIM, (uint32_t)(16) << 8U);
CLEAR_BIT(RCC->CR, RCC_CR_PLLON);
while(READ_BIT(RCC->CR, RCC_CR_PLLRDY) != RESET);
MODIFY_REG(RCC->CFGR, RCC_CFGR_PLLMUL | RCC_CFGR_PLLDIV | RCC_CFGR_PLLSRC, (uint32_t)((RCC_CFGR_PLLMUL4) | (RCC_CFGR_PLLDIV2) | (RCC_CFGR_PLLSRC_HSI)));
SET_BIT(RCC->CR, RCC_CR_PLLON);
while(READ_BIT(RCC->CR, RCC_CR_PLLRDY) == RESET);
MODIFY_REG(FLASH->ACR, FLASH_ACR_LATENCY, (uint32_t)(0x01U));
MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_CFGR_HPRE_DIV1);
MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_CFGR_SW_PLL);
while ((uint32_t)(RCC->CFGR & RCC_CFGR_SWS) != RCC_CFGR_SWS_PLL);
MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_CFGR_PPRE1_DIV1);
MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, ((RCC_CFGR_PPRE1_DIV1) << 3));
CLEAR_BIT(RCC->CR, RCC_CR_MSION);
/* SysTick CLK = 4MHz,Reload = 1kHz. */
SysTick->LOAD = (uint32_t)0x00000F9FUL;
NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL);
SysTick->VAL = 0UL;
SysTick->CTRL = SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk;
/* SysTick->CTRL = SysTick_CTRL_TICKINT_Msk; */
}
void ADC1_COMP_IRQHandler(void)
{
if(READ_BIT(EXTI->PR, EXTI_IMR_IM21) != RESET)
{
/* COMP1的比较器输出翻转了. */
WRITE_REG(EXTI->PR, EXTI_IMR_IM21);
}
if(READ_BIT(EXTI->PR, EXTI_IMR_IM22) != RESET)
{
/* COMP2的比较器输出翻转了. */
WRITE_REG(EXTI->PR, EXTI_IMR_IM22);
}
}
void Comp_Init(void)
{
/* 初始化时钟 */
SET_BIT(RCC->IOPENR, RCC_IOPENR_GPIOAEN);
SET_BIT(RCC->APB2ENR, RCC_APB2ENR_SYSCFGEN); /* COMP共享这个时钟 */
/* 上电没配置过,默认除了JTAG外引脚都是模拟引脚,所以懒得配置了. */
/* PA6/PA4 COMP OUT */
MODIFY_REG(GPIOA->MODER, GPIO_MODER_MODE6 | GPIO_MODER_MODE4, GPIO_MODER_MODE6_1 | GPIO_MODER_MODE4_1);
MODIFY_REG(GPIOA->AFR[0], GPIO_AFRL_AFRL6, (0x07 << GPIO_AFRL_AFRL6_Pos) );
MODIFY_REG(GPIOA->AFR[0], GPIO_AFRL_AFRL4, (0x07 << GPIO_AFRL_AFRL4_Pos) );
/* PA0 = INM,PA1 = INP */
COMP1->CSR = 0x00000011;
/* PA2 = INM,PA3 = INP */
COMP2->CSR = 0x00000019;
/* COMP1占用21线中断,COMP2占用22线中断. */
/* 上降沿中断 */
SET_BIT(EXTI->RTSR, EXTI_IMR_IM21 | EXTI_IMR_IM22);
/* 下降沿中断 */
SET_BIT(EXTI->FTSR, EXTI_IMR_IM21 | EXTI_IMR_IM22);
/* 清中断标志 */
WRITE_REG(EXTI->PR, EXTI_IMR_IM21 | EXTI_IMR_IM22);
/* 开中断模式 */
SET_BIT(EXTI->IMR, EXTI_IMR_IM21 | EXTI_IMR_IM22);
NVIC_SetPriority(ADC1_COMP_IRQn, 0);
NVIC_EnableIRQ(ADC1_COMP_IRQn);
}
int main(void)
{
RCC_Init();
Comp_Init();
while (1)
{
SysTick_Delay(1000);
}
} |