Saturday, August 13, 2016

PIR sensor and STM32F4 Discovery Board

Today I'm gonna show you how to detect a motion with the PIR sensor connected to the STM32F4 Discovery Board.

What are PIR sensors?
The acronym PIR means Passive Infrared. Those sensors are capable of detecting a motion mostly caused by humans. They are small and inexpensive and therefore commonly used in homes or businesses.

Things you need:
  • STM32F4 Discovery Board with the USB cable
  • PIR Sensor
  • 3 female/female jumper wires or soldering skill

1. Wiring:

STM32F4 PIR Sensor Cable Color
5V Power Red
PD5 Signal Yellow
GND Ground Black

2. Code:

We'll use STM32F4 standard GPIO library. The full code is available here. I'll break it in steps.

a) LEDs initalization

With the help of the documentation we can see that LEDs are connected to the following pins: PD12 (green), PD13 (orange), PD14 (red) and PD15 (blue).

First we enable GPIOD clock.
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
Then we configure all LEDs in output pushpull mode.
GPIO_InitTypeDef led; led.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15; led.GPIO_Mode = GPIO_Mode_OUT; led.GPIO_OType = GPIO_OType_PP; led.GPIO_Speed = GPIO_Speed_2MHz; led.GPIO_PuPd = GPIO_PuPd_NOPULL;
Note: Instead of GPIO_Pin_12, GPIO_Pin_13, ... you can also use GPIO_Pin_All to apply same settings to all pins.

And now initialize the whole structure.
GPIO_Init(GPIOD, &led);
b) Sensor pin initialization

The PIR sensor is connected to PD5 pin. We'll configure the settings in input pushpull mode.
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);
GPIO_InitTypeDef pin; pin.GPIO_Pin = GPIO_Pin_5; pin.GPIO_Mode = GPIO_Mode_IN; pin.GPIO_Speed = GPIO_Speed_2MHz; pin.GPIO_OType = GPIO_OType_PP; pin.GPIO_PuPd = GPIO_PuPd_UP; 
GPIO_Init(GPIOD, &pin);
c) Main program

Check in the loop whether the sensor detected the motion and turn on the LEDs in that case.
while (1) {
    if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_5)) {
      GPIO_SetBits(GPIOD, GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15);
    } else {
      GPIO_ResetBits(GPIOD, GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15);
    }
  }
Instead of using LEDs on the STM board you can connect the external one (see the previous tutorial). As a fun addition to the project you can also add the sound. 


Leave a comment

nour said...

hi
please i want know if we need libraries.

Ecosens said...

I really love it and amazing information in this blog. it's really good and great information well done. PIR Sensor in Bengaluru.