In this mini blog series we will build an IoT based intruder detection and alert system.
Blogs:
Part1 : Connecting Pir Sensor <--- this blog
Part2 : Capturing intruder image
Part3 : Email Alerts
In this post we shall connect a simple cheap Pir motion sensor to Riotboard.
We will be using Pir sensor HC-Sr501.
Pir Sensor HC-Sr501 has pins : VCC, GND, OUT.
VCC will be connected to pin2 (5VIN) in J13 expansion port.
GND will be connected to pin4 (GND) in J13 expansion port.
OUT will be connected to pin7 (GPIO4_17) in J13 expansion port.
(plz check usermanual for more info on J13 expansion port)
Pir setup..
this post uses the Linux BSP available here.
Next we will compile the below code and test.
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <string.h> int main() { int ret =0; int fd=0; char buf[1]; system("devmem 0x20E00A0 w 0x5 "); system("echo 113 > /sys/class/gpio/unexport"); system("echo 113 > /sys/class/gpio/export"); usleep(100000); system("echo in > /sys/class/gpio/gpio113/direction"); usleep(100000); fd = open("/sys/class/gpio/gpio113/value",O_RDONLY); while(1) { ret = read(fd,buf,sizeof(1)); if(lseek(fd,0,SEEK_SET) < 0) return 1; if(ret>0 && (atoi(buf)==1)) { printf("\n\033[031;43m HUMAN DETECTED \033[0m "); fflush(stdout); usleep(500000); } else printf("\nNo Detection"); fflush(stdin); fflush(stdout); usleep(500000); } close(fd); }
code explanation:
ln12 : using devmem to convert pin7 to gpio.
ln14: exporting pin7 as gpio in /sys/class for user.
ln16 : configure pin7 as gpio input , in pir we are reading(input) the OUT pin value .
ln19 : opening gpio as READ_ONLY
ln23: while reading a file the pointer moves by certain position,
in this case the file frequently updated.
so using lseek system call to read file from beginning,
ln25 : if HIGH value (1) present it means movement detected.
Q. why so many fflush & usleep used ??
A. to ensure the GPIO read and the terminal write happens in sync with program flow.
Now perform some hand movement infront of Pir sensor, it will show HUMAN DETECTED
No movement
Hand movement
Video demo:
in the next blog we will capture intruder image & send snapshot based on pir interrupt.
Top Comments