官术网_书友最值得收藏!

The most elaborate light switch in the world

By combining the two little projects earlier, we can now create a system that will do something useful when the pushbutton switch is pushed—for example, switching on the LED that we also have connected. Granted, we could just connect the LED directly to the switch and a battery, but not only would that be boring, it would defeat the point of what we're trying to do, which is programmatically sensing and controlling things.

Here's the breadboard layout for our elaborate light switch:

And here's the circuit diagram:

The illuminating script

Our full Bash script for our elaborate light switch is demonstrated next. This will loop endlessly, detecting the state of the switch GPIO pin, and will turn on the LED GPIO pin when the switch is pushed.

The code listing for light-switch.sh is as follows:

#!/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 the switch GPIO pin
sudo echo 27 > /sys/class/gpio/export
sudo echo in > /sys/class/gpio/gpio27/direction

# loop forever
while true
do
  # read the switch state
  SWITCH=$(sudo cat /sys/class/gpio/gpio27/value)

  #0=Pushed 1=Not Pushed
  if [ $SWITCH = "1" ]
  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

So, here we are—we have a script that will detect an input state and do something in response; in this case, it will switch on an LED. We're now forming the basis of how we are going to put together our home security system.

Note

Remember, don't connect anything to your Raspberry Pi in place of the LED, such as a buzzer or any other device that consumes lots of current. This is likely to irreversibly render your board dead. We'll look at ways, later on in this book, to control devices with higher power requirements.

主站蜘蛛池模板: 武清区| 石阡县| 广东省| 婺源县| 尼勒克县| 平山县| 潞西市| 吴桥县| 始兴县| 大荔县| 樟树市| 班戈县| 邮箱| 岳池县| 莲花县| 高平市| 赤壁市| 毕节市| 信丰县| 神池县| 龙陵县| 新和县| 泗水县| 华容县| 凭祥市| 芮城县| 柳河县| 萨嘎县| 平凉市| 井冈山市| 赤水市| 鸡东县| 哈尔滨市| 莒南县| 资源县| 贵港市| 贡觉县| 辛集市| 永寿县| 平和县| 和林格尔县|