2017年5月17日 星期三

Raspberry Pi - 智慧插座

現在市面上的智慧家居玲琅满目,上週的課程剛好有學到繼電器,所以就順帶做個智慧插座。這次DIY的智慧插座功能很簡單,純粹只用網頁開關插座,沒有其他功能。(RaspberryPi使用Python編寫,其實蠻容易擴充功能的。)

1. 首先,準備好RaspberryPi,麵包板、繼電器、延長線

2. 把延長線的火線剪開,來源段接在繼電器的COM上,終點端接在NO上
(圖裡右側3條細線,請忽略)


3. 繼電器的VCC接上3.3v,GND接上ground,In2接上GPIO(由於In1沒用到,所以不接)

4. 打開editor複製以下的code然後命名為intelligent_socket.py
(到此步驟,只要在terminal輸入python3 intelligent_socket.py 1 插座就接上電了;相反參數給0則斷電)
import RPi.GPIO as GPIO
import time
import sys
import argparse

parser = argparse.ArgumentParser()
parser.add_argument("boolean",help="1=on 2=off", type=int)
args = parser.parse_args()

GPIO.setmode(GPIO.BCM)
GPIO5 = 5 # In2 接在GPIO5上
GPIO.setup(GPIO5, GPIO.OUT)

signal = args.boolean
if signal == 1:
 GPIO.output(GPIO5, True)
elif signal == 0:
 GPIO.output(GPIO5, False)
else:
 pass 

print("end")
5. 打開editor複製以下的code然後命名為socket.php,並儲存在apache的網絡路徑。
<?php
 if(isset($_GET["a"])){
  $signal = $_GET["a"];
 
  switch($signal){
   case 'open':
    $output = shell_exec('python3 /home/pi/Desktop/intelligent_socket.py 1 2>&1');
    break;
   case 'close':
    $output = shell_exec('python3 /home/pi/Desktop/intelligent_socket.py 0 2>&1');
    break;
  }
  echo $output;
  die("done");
 }

?>

<!DOCTYPE html>
<html>
<head>
 <title>遠端插座開關</title>
 <script src="https://code.jquery.com/jquery-3.2.1.js"></script>
 <script type="text/javascript">
  $(document).ready(function(){
   $('#open').click(function(){
    $.ajax({
     url: 'socket.php?a=open',
     success: function(result){
      console.log(result);
     },
     statusCode: {
      404: function() {
       alert('網頁出錯,請重新操作或聯絡管理員');
      }
     }
    });   
   })
   $('#close').click(function(){
    $.ajax({
     url: 'socket.php?a=close',
     success: function(result){
      console.log(result);
     },
     statusCode: {
      404: function() {
       alert('網頁出錯,請重新操作或聯絡管理員');
      }
     }
    });   
   })
  })
 </script>
</head>
<body>
 <button id="open">OPEN</button>
 <button id="close">CLOSE</button>
</body>
</html>

6. 由於GPIO接觸到硬體,apache沒權限直接呼叫gpio function,所以只好把apache加進gpio的group裡。打開terminal,複製以下兩行到terminal(這步驟很重要,不然會失敗)

sudo usermod -a -G gpio www-data
sudo service apache2 restart

7. 用browser打開127.0.0.1/socket.php,點擊open則打開插座,點擊close則關閉插座。

8. 成功!


沒有留言:

張貼留言

Centos GUI Webserver 設定

新灌的一台Centos7可以做以下的設定 語系設定: - sudo localectl set-locale LC_CTYPE=zh_TW.UTF-8 修改ssh port - http://linux.vbird.org/linux_server/0310telne...