arduino+php+sinacloud+微信 監控led及室溫

      前言:生命不息,折騰不止。這是一種對生命的認知及態度。吾本是學軟件的,但因爲大學期間接觸到的社團有搞硬件的,看到他們搞的遙控小車,小四軸。。。以爲他們好geek,因而也對硬件愈發的感興趣。業餘時間研究一下硬件,積累了一點硬件知識。一直期盼着作一個小項目來實戰一下。某日在arduino論壇發現了一位大神的做品是用微信控制arduino的,因而在他的做品上演譯了一番。php

     硬件:java

        arduino uno(¥25/一塊,原諒我窮B只能用山寨的了),mysql

       enc28j60(¥13/一塊,以太網模塊),DHT11(溫溼度傳感器,便宜),MQ-2(煙霧傳感器,也不貴)git

        led(在廢棄家電上扒下來的),spring

        杜邦線(若干根,焊工好的話,能夠從廢棄家電上扒下來再用來焊接)。sql

賬號準備:微信公衆號或測試號,新浪雲賬號(新浪雲免費的空間足夠使用,因爲最近學了springmvc,想用java寫,但java環境初期都要收費,無奈只好用原文的php)。數據庫

硬件接線:arduino uno  與 enc28j60    服務器

Enc28j60 Arduino UNO
VCC 3.3V
GND GND
SCK Pin 13
SO Pin 12
SI Pin 11
CS Pin 10

 

arduino uno與DHT11接線說明微信

arduino uno與MQ-2接線說明mvc

實物:

 

一切線路okay!下面準備燒錄程序:(使用arduino ide將下面代碼燒錄進uno板,兩個庫文件須要放進ide的libraries下:文件)

//   
//   FILE:  dht_test.pde  
// PURPOSE: DHT library test sketch for Arduino  
//  


#include 
 #include     
#define DHT11_PIN 6//put the sensor in the digital pin 6
 
EthernetClient client;
signed long next;
char server[] = "1.smarthousetest.applinzi.com";
char state = '0';
char c;
unsigned long lastConnectionTime = 0;          
boolean lastConnected = false;                 
const unsigned long postingInterval = 200*1000; 
double temperature=0;
double humidity=0;
double smoke=0;
int ledPin=2; //設定控制LED的數字IO腳
dht DHT;  
  
  
void setup()  
{  
  Serial.begin(9600);  
  Serial.println("DHT TEST PROGRAM ");  
  Serial.print("LIBRARY VERSION: ");  
  Serial.println(DHT_LIB_VERSION);  
  Serial.println();  
  Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");  

 // 設置串口通訊波特率
  uint8_t mac[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xE1};
  IPAddress myIP(192,168,0,110);
  Serial.println("*****");
  Ethernet.begin(mac,myIP);
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());

  pinMode(5,OUTPUT);
  
}  
  
void loop()  
{  
  
  // READ DATA  
  Serial.print("DHT11, \t");  
 int chk = DHT.read11(DHT11_PIN);  
  switch (chk)  
  {  
    case 0:  Serial.print("OK,\t"); break;  
    case -1: Serial.print("Checksum error,\t"); break;  
    case -2: Serial.print("Time out error,\t"); break;  
    default: Serial.print("Unknown error,\t"); break;  
  }  
 // DISPLAT DATA  
  Serial.print(DHT.humidity,1);  
  Serial.print(",\t");  
  Serial.println(DHT.temperature,1);  

temperature=DHT.temperature;
humidity=DHT.humidity;
temperature=DHT.temperature;


 if(state == '0'){
    digitalWrite(5, LOW);      
  }else if(state == '1'){
    digitalWrite(5, HIGH);
  }

    smoke=analogRead(0);
    Serial.println(smoke,DEC);

if(smoke>=300){//煙霧濃度值大於300時,自動亮
   digitalWrite(ledPin,HIGH); //設定PIN5腳爲LOW = 0V
}else{
   digitalWrite(ledPin,LOW); //設定PIN5腳爲LOW = 0V
}
    

  while(client.available()) {
    c = client.read();
    if (c == '{'){
      state = client.read();
    }
    Serial.println(state);
   
  }


 
  if (!client.connected() && lastConnected) {
    Serial.println("disconnecting**.");
    client.stop();
  }
 
  if(!client.connected()) {
 Serial.println("!client.connected()");
    
    if (client.connect(server, 80)) {
  Serial.println(client.connect(server, 80));
      // send the HTTP PUT request:
      client.print("GET /update.php?token=smarthouse&temperature=");
      client.print(temperature);
      client.print("&humidity=");
      client.print(humidity);
      client.print("&smoke=");
      client.print(smoke);
      client.println(" HTTP/1.1");
      client.println("Host: 1.smarthousetest.applinzi.com");//項目url
      client.println("Connection: close");
      client.println();
 
      lastConnectionTime = millis();
    }else {
      Serial.println("connection failed");
      Serial.println("disconnecting.////");
      client.stop();
    }
  }
  lastConnected = client.connected();
  
  
  delay(1000);  
}  
//  
// END OF FILE  
//  


  燒錄完成,則將服務器端的項目部署上去。部署步驟省略

index.php:

FromUserName;
$toUserName = $xmlObj->ToUserName;
$msgType = $xmlObj->MsgType;
 
 
if($msgType == 'text'){
        $content = $xmlObj->Content;
}else{
        $retMsg = '只支持文本和語音消息';
}
 
if (strstr($content, "溫度")) {
        $con = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); 
        mysql_select_db("app_smarthousetest", $con);
 
        $result = mysql_query("SELECT * FROM sensor_data");
        while($arr = mysql_fetch_array($result)){
          if ($arr['ID'] == 0) {
                  $tempr = $arr['temperature'];
          }
        }
        mysql_close($con);
 
    $retMsg = "親愛的主人,你的房間的溫度爲".$tempr."℃。";
}else if(strstr($content, "溼度")) {
        $con = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); 
        mysql_select_db("app_smarthousetest", $con);
 
        $result = mysql_query("SELECT * FROM sensor_data");
        while($arr = mysql_fetch_array($result)){
          if ($arr['ID'] == 0) {
                  $tempr = $arr['humidity'];
          }
        }
        mysql_close($con);
 
    $retMsg = "親愛的主人,你的房間的溼度爲".$tempr."%";
}else if(strstr($content, "煙霧濃度")) {
        $con = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); 
        mysql_select_db("app_smarthousetest", $con);
 
        $result = mysql_query("SELECT * FROM sensor_data");
        while($arr = mysql_fetch_array($result)){
          if ($arr['ID'] == 0) {
                  $tempr = $arr['smoke'];
          }
        }
        mysql_close($con);
 
    $retMsg = "親愛的主人,你的房間的煙霧濃度值爲".$tempr;
}else if (strstr($content, "開燈")) {
        $con = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); 
 
 
        $dati = date("h:i:sa");
        mysql_select_db("app_smarthousetest", $con);
 
        $sql ="UPDATE led_data SET create_time='$dati',status = '1'  WHERE ID = '0'";//修改開關狀態值
 
        if(!mysql_query($sql,$con)){
            die('Error: ' . mysql_error);
        }else{
                mysql_close($con);
                $retMsg = "好的";
        }
}else if (strstr($content, "關燈")) {
        $con = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); 
 
 
        $dati = date("h:i:sa");
        mysql_select_db("app_smarthousetest", $con);
 
        $sql ="UPDATE led_data SET create_time='$dati',status = '0'
        WHERE ID = '0'";//修改開關狀態值
 
        if(!mysql_query($sql,$con)){
            die('Error: ' . mysql_error());
        }else{
                mysql_close($con);
                $retMsg = "好的";
        }        
}else{
        $retMsg = "暫時不支持該命令";
}
 
//XML信息
$retTmp = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                <FuncFlag>0</FuncFlag>
                </xml>";
$resultStr = sprintf($retTmp, $fromUserName, $toUserName, time(), $retMsg);
 
//反饋到微信服務器
echo $resultStr;
?>

 

update.php

<?php 
if (($_GET['temperature'] || $_GET['humidity'] || $_GET['smoke'] )&& ($_GET['token'] == "smarthouse")) {//能夠改token,這至關於密碼,在Arduino端改爲相應的值便可
        $con = mysql_connect(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS); 
        $temperature = $_GET['temperature'];
        $humidity = $_GET['humidity'];
        $smoke = $_GET['smoke'];
        mysql_select_db("app_smarthousetest", $con);//要改爲相應的數據庫名
 
        $result = mysql_query("SELECT * FROM led_data");
        while($arr = mysql_fetch_array($result)){//找到須要的數據的記錄,並讀出狀態值
                if ($arr['ID'] == 0) {
                        $status = $arr['status'];
                }
        }
        $dati = date("h:i:sa");//獲取時間
        $sql ="UPDATE sensor_data SET create_time='$dati',temperature = '$temperature',humidity = '$humidity',smoke = '$smoke'
        WHERE ID = '0'";//更新相應的傳感器的值
        if(!mysql_query($sql,$con)){
            die('Error: ' . mysql_error());//若是出錯,顯示錯誤
        }
        mysql_close($con);
        echo "{".$status."}";//返回狀態值,加「{」是爲了幫助Arduino肯定數據的位置
}else{
        echo "Permission Denied";//請求中沒有type或data或token或token錯誤時,顯示Permission Denied
}
?>
 

 

數據庫:

sensor_data

id id int
溫度 temperature float
溼度 humidity float
煙霧濃度 smoke float
建立時間 create_time dataTime

led_data

id id int
狀態 status int
建立時間 create_time dataTime

 

一切基本完成,就差將申請的微信公衆號,使用開發者模式,將url填寫爲項目的url,這裏的爲:1.smarthousetest.applinzi.com。token則爲:smarthouse。

 

下面就是正式的調用了,關注公衆號後,則可實現以下圖功能:

 

折騰多時,終於完成!

相關文章
相關標籤/搜索