Monitoring the sensor
Now that we have everything in place and our magnetic sensor is detecting whether the door is closed, we can monitor this sensor with a simple Bash script that uses the I2C tool commands that we installed earlier.
The code listing for poll-magnetic-switch.sh
is as follows:
#!/bin/bash sudo i2cset –y 1 0x20 0x00 0xFF # loop forever while true do # read the sensor state SWITCH=$(sudo i2cget –y 1 0x20 0x12) if [ $SWITCH == "0x01" ] then #contact closed so wait for a second echo "The door is closed!" sleep 1 else #contact was opened echo "The door is open!" fi done
When you run the script and then push the button, you should see "The door is open!" scrolling up the console screen until you stop pressing it.
By combining this with ...
Get Raspberry Pi: Amazing Projects from Scratch now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.