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 our elaborate light switch project in chapter 2, we can switch on the LED connected to GPIO17 when the door is opened:

#!/bin/bash

#set up the LED GPIO pin
sudo echo 17 > /sys/class/gpio/export
sudo echo out > /sys/class/gpio/gpio17/direction

#set up port expander 
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
    #switch not pushed so turn off LED pin
    sudo echo 0 > /sys/class/gpio/gpio17/value
  else
    #switch was pushed so turn on LED pin
    sudo echo 1 > /sys/class/gpio/gpio17/value
  fi
  #short delay
  sleep 0.5
done

Note

Later, as we add more sensors to different input pins, we will need to be able to detect which one has been triggered. We'll look at writing a Bash function later in the book, which will parse the returned hex value from the i2cget command, and tell us exactly which of the 8 inputs is high.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.76.30