/**
******************************************************************************
* @file : main.c
* @author : Auto-generated by STM32CubeIDE
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
#include <stdint.h>
#include "stm32f103xb.h"
#include "stm32f103_hal.h"
void delay_ms(uint16_t ms) {
volatile unsigned long t = 0;
for(uint16_t i = 0; i < ms; i++)
{
for(t = 0; t < 800; t++);
}
}
void delay_us(uint16_t us)
{
for (volatile unsigned int cycles = 0; cycles < us; cycles++);
}
volatile uint16_t firing_delay = 1000;
volatile uint8_t triac_on = 1;
int main(void)
{
// RCC config
rcc_clock_enable(RCC_GPIOA); // Activo clock de GPIOA
rcc_clock_enable(RCC_TIM3); // Activo clock de TIM3
rcc_clock_enable(RCC_AFIO); // Activo clock de AFIO (EXTI)
// GPIO config
gpio_set_output(GPIOA, GPIO_PIN_1, GPIO_OUTPUT_PP, GPIO_SPEED_2MHZ);
gpio_set_input(GPIOA, GPIO_PIN_2, GPIO_INPUT_PD);
gpio_set_input(GPIOA, GPIO_PIN_3, GPIO_INPUT_PD);
// TIMER config
timer_init(TIM3, TIMER_MODE_UP, 1000, 7);
timer_set_interrupt(TIM3, TIMER_IRQ_UPDATE, IRQ_ENABLE);
NVIC_EnableIRQ(TIM3_IRQn);
// EXTI config
exti_set_interrupt(PA0, EXTI_IRQ_RISING);
NVIC_EnableIRQ(EXTI0_IRQn);
// Loop
while (1)
{
if( gpio_read_pin(GPIOA, GPIO_PIN_3) )
{
triac_on=1;
if(firing_delay>1000) firing_delay -= 1000;
delay_ms(10);
while(gpio_read_pin(GPIOA, GPIO_PIN_3));
delay_ms(10);
}
if( gpio_read_pin(GPIOA, GPIO_PIN_2) )
{
if(firing_delay<9000) firing_delay += 1000;
else
{
triac_on=0;
firing_delay=10000;
}
delay_ms(10);
while(gpio_read_pin(GPIOA, GPIO_PIN_2));
delay_ms(10);
}
}
}
void EXTI0_IRQHandler(void)
{
// Clear pending flag
EXTI->PR = 1 << 0;
// Launch timer
if(triac_on) {
TIM3->ARR = firing_delay;
timer_start(TIM3, TIMER_ONESHOT);
}
}
void TIM3_IRQHandler(void)
{
// Clear pending flag
TIM3->SR &= ~TIM_SR_UIF;
// User code
GPIOA->ODR |= 1 << 1;
delay_us(100);
GPIOA->ODR &= ~(1 << 1);
}