My sensor is not responding to the 10 us pulses I am giving to its Trig pin. The below code uses external interrupts to know whether I am getting any input at all from the echo pin of the sensor and the interrupt is not firing at all.

#include "stm32f4xx.h"
void GPIO_init(void);
void EXTI_init(void);
void TIM2_init(void);
void usdelay(int);
void msdelay(int);
int main(){
    GPIO_init();
    TIM2_init();
    EXTI_init();
    while(1){
        GPIOC -> ODR &= ~(1<<7);
        usdelay(2);
        GPIOC -> ODR |= (1<<7);
        usdelay(10);
        GPIOC -> ODR &= ~(1<<7);
        msdelay(50);
    }
}

void GPIO_init(void){
    RCC -> CFGR &= ~(0x908FUL);
    RCC -> AHB1ENR |= (0x3<<2);
    GPIOC -> MODER |= (0x1<<14);
    GPIOC -> MODER &= ~(0x3<<12);
    GPIOD -> MODER |= (0x1<<28);
    GPIOD -> OTYPER &= ~(0x1<<14);
    GPIOC -> OTYPER &= ~(0x3<<6);
    GPIOD -> PUPDR |= (0x2<<28);
    GPIOC -> PUPDR |= (0xA<<12);
}

void TIM2_init(void){
    RCC -> APB1ENR |= (0x1);
    TIM2 -> CR1 &= ~(0x0010);
    TIM2 -> PSC = 0;
    TIM2 -> ARR = 4;
    TIM2 -> SR &= ~(0x01);
}

void EXTI_init(void){
    RCC -> APB2ENR |= (0x1<<14);
    SYSCFG -> EXTICR[1] |= (0x2<<8);
    EXTI -> IMR |= (0x1<<6);
    EXTI -> RTSR |= (0x1<<6);
    EXTI -> FTSR |= (0x1<<6);
    NVIC -> ISER[0] |= (0x1<<23);
}

void usdelay(int x){
    TIM2 -> ARR = 4*x;
    TIM2 -> CNT = 0;
    TIM2 -> CR1 |= 0x01;
    while(!(TIM2 -> SR & (0x01)));
    TIM2 -> CR1 &= ~(0x01);
    TIM2 -> SR &= ~(0x01);
}

void msdelay(int x){
    TIM2 -> ARR = 4000*x;
    TIM2 -> CNT = 0;
    TIM2 -> CR1 |= (0x1);
    while(!(TIM2 -> SR & (0x1)));
    TIM2 -> CR1 &= ~(0x1);
    TIM2 -> SR &= ~(0x1);
}

void EXTI9_5_IRQHandler(){
    EXTI -> PR |= (1<<6);
    GPIOD -> ODR ^= (1<<14);

}

I thought there might be some issues with wiring or supply but after double checking with an arduino it seems everything is working correctly, the sensor, connections and even the supply from STM32 is working as expected. Is it some issue with my clock ? I am assuming a 16 MHz clock as default when no prescaler is applied to the APB1ENR register. I have also tried example codes (one of them: https://ruturajn.hashnode.dev/interfacing-an-ultrasonic-sensor-with-the-stm32f407-discovery-board-using-bare-metal-programming) and still it isn't working.

Edit: So I fixed the issue by using PA0 for interrupt and PC0 for output. Input capture method is also working without any issues.

1

There are 1 best solutions below

1
Shardul Sajnekar On

I used different ports for input and output and that seems to have fixed the issue, I used PA0 for the interrupt and PC0 for the output and this time there are no issues but last time when I used PC6 and PD0 for input and output respectively, the problem persisted, so I don't know if using Port A has fixed the problem or using Pin 0 of both ports has fixed it.

Anyway the problem has been solved.