揭開物聯網的神祕面紗--物聯網小燈

物聯網的定義:(來自維基百科

The Internet of things (IoT) is the network of physical devices, vehicles, home appliances and other items embedded with electronics, software, sensors, actuators, and connectivity which enables these objects to connect and exchange data. Each thing is uniquely identifiable through its embedded computing system but is able to inter-operate within the existing Internetinfrastructure.

The IoT allows objects to be sensed or controlled remotely across existing network infrastructure, creating opportunities for more direct integration of the physical world into computer-based systems, and resulting in improved efficiency, accuracy and economic benefit in addition to reduced human intervention.When IoT is augmented with sensors and actuators, the technology becomes an instance of the more general class of cyber-physical systems, which also encompasses technologies such as smart grids, virtual power plants, smart homes, intelligent transportation and smart cities.

"Things", in the IoT sense, can refer to a wide variety of devices such as heart monitoring implants, biochip transponders on farm animals, cameras streaming live feeds of wild animals in coastal waters, automobiles with built-in sensors, DNA analysis devices for environmental/food/pathogen monitoring, or field operation devices that assist firefighters in search and rescue operations. Legal scholars suggest regarding "things" as an "inextricable mixture of hardware, software, data and service".

These devices collect useful data with the help of various existing technologies and then autonomously flow the data between other devices.


物聯網小燈全架構實現

目標:將小燈接入互聯網使其使其與網絡互連,能查詢小燈的實時狀態,能對小燈的狀態進行更改

從服務器的API服務到下位機的入網。

所需設備:

服務器一臺(阿里雲騰訊雲都可以)

嵌入式開發板一塊(51板,正點原子32開發板或則Linux嵌入式開發板都行,<前提是你會那樣>)

WiFi模塊一個:(ESP8266模塊或則使用NodeMCU開發板

自己做一個小燈一個(自己手焊,打板都行)

框架圖(源自百度圖庫):


服務器搭建:

步驟:

1、租用一臺服務器

2、搭建一個LNMP服務器(附LNMP一鍵安裝包,過程就省略了,有教程,Linux+Nginx+MySQL+PHP

3,數據庫構建:

遠程終端命令行代碼(SQL代碼):

登錄:
[root@host]# mysql -u root -p
Enter password:******
創建數據庫:
CREATE DATABASE api;
創建數據表:
USE api;
CREATE TABLE `device`(
   `id` VARCHAR(20) NOT NULL,
   `status` VARCHAR(20) NOT NULL);
插入數據:
INSERT INTO device 
    -> (id, status)
    -> VALUES
    -> ("Light", "Low_brightness");
INSERT INTO device 
    -> (username, passwd)
    -> VALUES
    -> ("賬戶名", "密碼");


數據庫搭建成功測試代碼:


mysql> select * from device;
+-------+----------------+
| id    | status         |
+-------+----------------+
| Light | Low_brightness |
+-------+----------------+
1 row in set (0.00 sec)
mysql> select * from user;
+----------+--------+
| username | passwd |
+----------+--------+
| test     | Li34   |
+----------+--------+
1 row in set (0.00 sec)


服務端搭建API接口服務(PHP代碼):

1、用於將數據庫的數據封裝成JSON或XML格式


<?php

class Response {
	const JSON = "json"; 
	/**
	* 按綜合方式輸出通信數據
	* @param integer $code 狀態碼
	* @param string $message 提示信息
	* @param array $data 數據
	* @param string $type 數據類型
	* return string
	* 調用方式 Response::show($code, $message, $data, $type); //其中type可以來自用戶
	*/
	public static function show($code, $message = '', $data = array(), $type = self::JSON) {
		if(!is_numeric($code)) { 
			return '';
		}
		$type = isset($_GET['format']) ? $_GET['format'] : self::JSON;
		
		$result = array(
			'code' => $code,
			'message' => $message,
			'data' => $data,
		);

		if($type == 'json') {
			self::json($code, $message, $data);
			exit;
		} elseif($type == 'array') {
			var_dump($result);
		} elseif($type == 'xml') {
			self::xmlEncode($code, $message, $data);
			exit;
		} else {
			// TODO
		}
	}
	/**
	* 按json方式輸出通信數據
	* @param integer $code 狀態碼
	* @param string $message 提示信息
	* @param array $data 數據
	* return string
	* 調用方式 require_once('./response.php'); 調用response.php號文件 
	* 			Response::json($code, $message, $data);調用Response的json方法
	*/
	public static function json($code, $message = '', $data = array()) {
		
		if(!is_numeric($code)) { 
			return '';
		}

		$result = array(
			'code' => $code,
			'message' => $message,
			'data' => $data
		);
		echo json_encode($result);
		exit;
	}

	/**
	* 按xml方式輸出通信數據
	* @param integer $code 狀態碼
	* @param string $message 提示信息
	* @param array $data 數據
	* return string
	* 調用方式 Response::xmlEncode($code, $message, $data);
	*/
	public static function xmlEncode($code, $message, $data = array()) {
		if(!is_numeric($code)) { 
			return '';
		}
		$result = array(
			'code' => $code,
			'message' => $message,
			'data' => $data,
		);
		header("Content-Type:text/xml"); 
		$xml = "<?xml version='1.0' encoding='UTF-8'?>\n";
		$xml .= "<root>\n";
		$xml .= self::xmlToEncode($result);
		$xml .= "</root>";
		echo $xml;
	}

	public static function xmlToEncode($data) {

		$xml = $attr = "";
		foreach($data as $key => $value) { 
			if(is_numeric($key)) {
				$attr = " id='{$key}'";
				$key = "item";
			}
			$xml .= "<{$key}{$attr}>";
			$xml .= is_array($value) ? self::xmlToEncode($value) : $value; //遞歸調用xmlToEncode
			$xml .= "</{$key}>\n";
		}
		return $xml;
	}

}
2、用於返回下位機數據
<?php

$dbms='mysql';     //數據庫類型
$host='localhost'; //數據庫主機名
$dbName='api';    //使用的數據庫
$user='用戶名';      //數據庫連接用戶名
$pass='密碼';          //對應的密碼
$dsn="$dbms:host=$host;dbname=$dbName";
require_once('./response.php');
try {
    $dbh = new PDO($dsn, $user, $pass);
    foreach($dbh->query('SELECT * from device') as $row) { 
    }
    $dbh = null;
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
$data = array(
    'id' => $row['id'],
    'status' => $row['status'],
);
Response::show(200,'success',$data); 
?>

服務器API服務數據返回測試:

在瀏覽器中輸入:服務器IP地址/test.php?format=xml

執行結果:

<?xml version='1.0' encoding='UTF-8'?>
<root>
<code>200</code>
<message>success</message>
<data><id>Light</id>
<status>Low_brightness</status>
</data>
</root>

實現網頁控制小燈代碼:

(HTML代碼)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>智能燈網頁控制</title>
	</head>
	
<body>
		<h2 class="headingOuter">智能燈網頁控制</h2>
		<form action="control.php" method="get">
        亮度:
        <table width="200">
          <tr>
            <td><label>
              <input type="radio" name="control" value="Lights_off" id="control_0" />
              關燈</label></td>
          </tr>
          <tr>
            <td><label>
              <input type="radio" name="control" value="Low_brightness" id="control_1" />
              低亮度</label></td>
          </tr>
          <tr>
            <td><label>
              <input type="radio" name="control" value="Medium_brightness" id="control_2" />
              中亮度</label></td>
          </tr>
          <tr>
            <td><label>
              <input type="radio" name="control" value="high_brightness" id="control_3" />
              高亮度</label></td>
          </tr>
        </table>

<!--<input type="text" name="brightness">-->
			<input type="submit" value="提交">
</form>
</body>
</html>
(PHP代碼)
<?php
	$get_temp = $_GET["control"];
	$dbms='mysql';     //數據庫類型
	$host='localhost'; //數據庫主機名
	$dbName='api';    //使用的數據庫
	$user='root';      //數據庫連接用戶名
	$pass='密碼';          //對應的密碼
	$dsn="$dbms:host=$host;dbname=$dbName";
	$dup="update device set status='$get_temp' where 1";
	    $dbh = new PDO($dsn, $user, $pass);
	    $count = $dbh->exec($dup);//執行SQL語句
	    print "Upate $count rows success!\n";
	    sleep(10);
	    $dbh = null;
	    header("Location: http://服務器的網址/control.html");

測試圖片:


簡單的網頁登錄認證:

(HTML代碼)

<html>
	<head>智能燈網頁控制用戶登錄</head>
	<form name="LoginForm" method="post" action="login.php" onSubmit="return InputCheck(this)">
		<p>
			<label for="username" class="label">用戶名:</label>
			<input id="username" name="username" type="text" class="input" />
		<p/>
		<p>
			<label for="password" class="label">密 碼:</label>
			<input id="password" name="password" type="password" class="input" />
		<p/>
		<p>
			<input type="submit" name="submit" value="  確 定  " class="left" />
		</p>
	</form>
</html>
(PHP代碼)
<?php
	if(!isset($_POST['submit']))
	{
	    exit('Unauthorized access!');
	}
	$username = htmlspecialchars($_POST['username']);
	$password = htmlspecialchars($_POST['password']);
	include('conn.php');
	foreach($dbh->query('SELECT username, passwd from user where 1') as $row) 
	{
	}
	if($username == $row['username'] && $password == $row['passwd'])
	{
		header("Location: http://服務器IP地址/control.html"); 
	} 
	else 
	{
		exit('Login failed! click here <a href="javascript:history.back(-1);">come back</a> try again');
	}
?>
<?php  
	$dbms='mysql';
	$host='localhost';
	$dbName='api';
	$user='用戶名';
	$pass='密碼';
	$dsn="$dbms:host=$host;dbname=$dbName";
	try 
	{
	    $dbh = new PDO($dsn, $user, $pass);
	} 
	catch (PDOException $e) 
	{
	    print "Error!: " . $e->getMessage() . "<br/>";
	    die();
	}
?>

成功圖片:


下位機代碼(我是使用的是STM32+人工焊的小燈採用164芯片):

由於我買的是ALIENTEK STM32開發板,它裏面帶有ESP8266的測試模板,直接在上面進行修改即可,至於模塊燒寫AT指令集,我已寫過可以看固件下載

小燈驅動(C語言代碼):

164模塊編寫:

#include "164.h"
#include "delay.h"
//unsigned char Tab[]={0x00,0X01,0X02,0X04,0X08,0X80,0X40,0X20,0X10};	//共陰數碼管
unsigned char Tab[]={0x00,0X04,0X06,0X07};	//LED燈的亮度
/*************************
0x00 滅
0x04 低亮
0x06 中亮
0x07 高亮
*************************/

unsigned char DS_data[6];
void HC164_Init(void)
{
 GPIO_InitTypeDef  GPIO_InitStructure;	
 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);	 //使能PC端口時鐘	
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4|GPIO_Pin_5;	//LED0-->PA.8 端口配置
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; 		 //推輓輸出
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;		 //IO口速度爲50MHz
 GPIO_Init(GPIOC, &GPIO_InitStructure);					 //根據設定參數初始化GPIOA.8
 GPIO_SetBits(GPIOC,GPIO_Pin_4);						 //PA.8 輸出高
}
 void separateData(unsigned long dat)	 // dat爲6位數
{
   DS_data[0]=dat%10;                                                    
   DS_data[1]=dat/10%10;
   DS_data[2]=dat/100%10;
   DS_data[3]=dat/1000%10;
   DS_data[4]=dat/10000%10;
   DS_data[5]=dat/100000%10;
}
void write_164(unsigned char dat)
	
{
   unsigned char i;
   for(i=0;i<8;i++)     
   {
     CLK=0;             
     if(dat&0x80)  
		 MOSI=1;
     else          
		 MOSI=0;
     CLK=1;               
     dat<<=1; 
  }
}

void display()
{
   unsigned char i;
   for(i=0;i<6;i++)
   {
		write_164(Tab[DS_data[0]]);
		delay_ms(1); 
   }
}


小燈控制實現
#include "eled.h"	   
#include "164.h"
//初始化PB5和PE5爲輸出口.並使能這兩個口的時鐘		    
//LED IO初始化


void ELED_Init(void)
{
 
 GPIO_InitTypeDef  GPIO_InitStructure;
 	
 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA|RCC_APB2Periph_GPIOD, ENABLE);	 //使能PA,PD端口時鐘
	
 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;				 //LED0-->PA.8 端口配置
 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; 		 //推輓輸出
 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;		 //IO口速度爲50MHz
 GPIO_Init(GPIOA, &GPIO_InitStructure);					 //根據設定參數初始化GPIOA.8
 GPIO_SetBits(GPIOA,GPIO_Pin_8);						 //PA.8 輸出高

 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;	    		 //LED1-->PD.2 端口配置, 推輓輸出
 GPIO_Init(GPIOD, &GPIO_InitStructure);	  				 //推輓輸出 ,IO口速度爲50MHz
 GPIO_SetBits(GPIOD,GPIO_Pin_2); 						 //PD.2 輸出高 
}
 
void control_brightness(uint8_t brightness)
{
	if(brightness == Lights_off)
	{
		separateData(0);//滅
		display();
	}
	else if(brightness == Low_brightness)
	{
		separateData(1);//低亮度
		display();	
	}
	else if(brightness == Medium_brightness)
	{
		separateData(2);//中亮度
		display();			
	}
	else if(brightness == high_brightness)
	{
		separateData(3);//中亮度
		display();		
	}
}

核心代碼

#include "common.h"
#include "stdlib.h"
#include "164.h"
#include "Photoresistor.h"
#include "eled.h"
#include <string.h>

u8 USART2_RX_BUF_TEMP[1024];
int flag_lights_test=0;//燈的標誌位默認0爲滅,1爲低亮度,2爲中亮度,3高亮度
char *buf1 = "Lights_off", \
	 *buf2 = "Low_brightness", \
	 *buf3 = "Medium_brightness", \
	 *buf4 = "high_brightness";
u8 netpro=0;	//網絡模式
void light_Status_changes_test(int flag);
u8 atk_8266_send_cmd_test(u8 *cmd,u8 *ack,u16 waittime);
int StringFind_test(const char *pSrc, const char *pDst);
u8 atk_8266_wifista_test(void)
{
	int flag_netpro=1;
	int flag_lights_test_temp=1;
	u8 key;
	u8 timex=0; 
	u8 ipbuf[16]; 	//IP緩存
	u8 *p;
	u16 t=999;		//加速第一次獲取鏈接狀態
	u8 res=0;
	u16 rlen=0;
	u8 constate=0;	//連接狀態
	p=mymalloc(32);							//申請32字節內存
	atk_8266_send_cmd("AT+CWMODE=1","OK",50);		//設置WIFI STA模式
	atk_8266_send_cmd("AT+RST","OK",20);		//DHCP服務器關閉(僅AP模式有效) 
	delay_ms(1000);         //延時3S等待重啓成功
	delay_ms(1000);
	delay_ms(1000);
	delay_ms(1000);
	//設置連接到的WIFI網絡名稱/加密方式/密碼,這幾個參數需要根據您自己的路由器設置進行修改!! 
	sprintf((char*)p,"AT+CWJAP=\"%s\",\"%s\"",wifista_ssid,wifista_password);//設置無線參數:ssid,密碼
	while(atk_8266_send_cmd(p,"WIFI GOT IP",300));					//連接目標路由器,並且獲得IP
PRESTA:
	netpro|=atk_8266_netpro_sel(50,30,(u8*)ATK_ESP8266_CWMODE_TBL[0]);	//選擇網絡模式
		if(netpro&0X01)     //TCP Client    透傳模式測試
		{
			LCD_Clear(WHITE);
			POINT_COLOR=RED;
			Show_Str_Mid(0,30,"ATK-ESP WIFI-STA 測試",16,240); 
			Show_Str(30,50,200,16,"正在配置ATK-ESP模塊,請稍等...",12,0);
			if(atk_8266_ip_set("WIFI-STA 遠端IP設置",(u8*)ATK_ESP8266_WORKMODE_TBL[netpro],(u8*)portnum,ipbuf))goto PRESTA;	//IP輸入
			atk_8266_send_cmd("AT+CIPMUX=0","OK",20);   //0:單連接,1:多連接
			sprintf((char*)p,"AT+CIPSTART=\"TCP\",\"%s\",%s",ipbuf,(u8*)portnum);    //配置目標TCP服務器
			while(atk_8266_send_cmd(p,"OK",200))
			{
					LCD_Clear(WHITE);
					POINT_COLOR=RED;
					Show_Str_Mid(0,40,"WK_UP:返回重選",16,240);
					Show_Str(30,80,200,12,"ATK-ESP 連接TCP失敗",12,0); //連接失敗	 
					key=KEY_Scan(0);
					if(key==WKUP_PRES)goto PRESTA;
			}	
			atk_8266_send_cmd("AT+CIPMODE=1","OK",200);      //傳輸模式爲:透傳			
		}
		else					//TCP Server
		{
				LCD_Clear(WHITE);
				POINT_COLOR=RED;
				Show_Str_Mid(0,30,"ATK-ESP WIFI-STA 測試",16,240); 
				Show_Str(30,50,200,16,"正在配置ATK-ESP模塊,請稍等...",12,0);
				atk_8266_send_cmd("AT+CIPMUX=1","OK",20);   //0:單連接,1:多連接
				sprintf((char*)p,"AT+CIPSERVER=1,%s",(u8*)portnum);    //開啓Server模式(0,關閉;1,打開),端口號爲portnum
				atk_8266_send_cmd(p,"OK",50);    
		}
			LCD_Clear(WHITE);
			POINT_COLOR=RED;
			Show_Str_Mid(0,30,"ATK-ESP WIFI-STA 測試",16,240);
			Show_Str(30,50,200,16,"正在配置ATK-ESP模塊,請稍等...",12,0);			
			LCD_Fill(30,50,239,50+12,WHITE);			//清除之前的顯示
			Show_Str(30,50,200,16,"WK_UP:退出測試  KEY0:發送數據",12,0);
			LCD_Fill(30,80,239,80+12,WHITE);
			atk_8266_get_wanip(ipbuf);//服務器模式,獲取WAN IP
			sprintf((char*)p,"IP地址:%s 端口:%s",ipbuf,(u8*)portnum);
			Show_Str(30,65,200,12,p,12,0);				//顯示IP地址和端口	
			Show_Str(30,80,200,12,"狀態:",12,0); 		//連接狀態
			Show_Str(120,80,200,12,"模式:",12,0); 		//連接狀態
			Show_Str(30,100,200,12,"發送數據:",12,0); 	//發送數據
			Show_Str(30,115,200,12,"接收數據:",12,0);	//接收數據
			atk_8266_wificonf_show(30,180,"請設置路由器無線參數爲:",(u8*)wifista_ssid,(u8*)wifista_encryption,(u8*)wifista_password);
			POINT_COLOR=BLUE;
			Show_Str(120+30,80,200,12,(u8*)ATK_ESP8266_WORKMODE_TBL[netpro],12,0); 		//連接狀態
			USART2_RX_STA=0;
			ELED_Init();
			HC164_Init();
			while(1)
			{
				if(flag_lights_test!=flag_lights_test_temp)
				{
					light_Status_changes_test(flag_lights_test);
				}
				key=KEY_Scan(0);
				if(key==WKUP_PRES)			//WK_UP 退出測試		 
				{ 
					res=0;					
					atk_8266_quit_trans();	//退出透傳
					atk_8266_send_cmd("AT+CIPMODE=0","OK",20);   //關閉透傳模式
					break;												 
				}
				else if(key==KEY0_PRES)	//KEY0 發送數據 
				{
					if((netpro==1)&&(flag_netpro==1))   //TCP Client
					{
						atk_8266_quit_trans();
						atk_8266_send_cmd("AT+CIPSEND","OK",20);         //開始透傳   
						delay_ms(1000);		
						delay_ms(1000);	
						delay_ms(1000);	
						delay_ms(1000);	
						delay_ms(1000);	
						sprintf((char*)p,"GET http://服務器的IP地址/api/test.php?format=json\r\n",ATK_ESP8266_WORKMODE_TBL[netpro],t/10);
						u2_printf("%s",p);
						timex=100;
						flag_netpro=0;
					}
				}
				if(flag_netpro==0)
				{
					delay_ms(1000);
					delay_ms(1000);	
					delay_ms(1000);	
					delay_ms(1000);	
					delay_ms(1000);	
					sprintf((char*)p,"GET http://服務器的IP地址/api/test.php?format=json\r\n",ATK_ESP8266_WORKMODE_TBL[netpro],t/10);
					Show_Str(30+54,100,200,12,p,12,0);
					u2_printf("%s",p);
					timex=100;	
					delay_ms(1000);
					delay_ms(1000);
				}
				if(timex)timex--;
				if(timex==1)LCD_Fill(30+54,100,239,112,WHITE);
				t++;
				delay_ms(10);
				if(USART2_RX_STA&0X8000)		//接收到一次數據了
				{ 
					rlen=USART2_RX_STA&0X7FFF;	//得到本次接收到的數據長度
					USART2_RX_BUF[rlen]=0;		//添加結束符 
					printf("%s",USART2_RX_BUF);	//發送到串口   
					sprintf((char*)p,"收到%d字節,內容如下",rlen);//接收到的字節數 
					LCD_Fill(30+54,115,239,130,WHITE);
					POINT_COLOR=BRED;
					Show_Str(30+54,115,156,12,p,12,0); 			//顯示接收到的數據長度
					POINT_COLOR=BLUE;
					LCD_Fill(30,130,239,319,WHITE);
					Show_Str(30,130,180,190,USART2_RX_BUF,12,0);//顯示接收到的數據  
					strcpy(USART2_RX_BUF_TEMP,USART2_RX_BUF);
					flag_lights_test_temp=flag_lights_test;//存儲上一次的flag_lights_test的值
					if(StringFind(USART2_RX_BUF_TEMP, buf1) >= 0) flag_lights_test=0;
					if(StringFind(USART2_RX_BUF_TEMP, buf2) >= 0) flag_lights_test=1;
					if(StringFind(USART2_RX_BUF_TEMP, buf3) >= 0) flag_lights_test=2;
					if(StringFind(USART2_RX_BUF_TEMP, buf4) >= 0) flag_lights_test=3;
					USART2_RX_STA=0;
					if(constate!='+')t=1000;		//狀態爲還未連接,立即更新連接狀態
					else t=0;                   //狀態爲已經連接了,10秒後再檢查
				}  
				if(t==1000)//連續10秒鐘沒有收到任何數據,檢查連接是不是還存在.
				{
					constate=atk_8266_consta_check();//得到連接狀態
					if(constate=='+')Show_Str(30+30,80,200,12,"連接成功",12,0);  //連接狀態
					else Show_Str(30+30,80,200,12,"連接失敗",12,0); 	 
					t=0;
				}
				if((t%20)==0)LED0=!LED0;
				atk_8266_at_response(1);
			}
	myfree(p);		//釋放內存 
	return res;		
} 

/*添加開始*/
//向ATK-ESP8266發送命令
//cmd:發送的命令字符串
//ack:期待的應答結果,如果爲空,則表示不需要等待應答
//waittime:等待時間(單位:10ms)
//返回值:0,發送成功(得到了期待的應答結果)
//       1,發送失敗
//例如:atk_8288_send_cmd("AT+RST","OK",20);
//		表示發送指令:AT+RST 到 WIFI 模塊,重啓模塊;期待的應答爲:OK;等待時間爲200ms。
u8 atk_8266_send_cmd_test(u8 *cmd,u8 *ack,u16 waittime)
{
	/*添加開始*/
	char *test_1 = "success", \
		 *test_2 = "failure";
	/*添加結束*/
	u8 res=0; 
	USART2_RX_STA=0;
	u2_printf("%s\r\n",cmd);	//發送命令
	if(ack&&waittime)		//需要等待應答
	{
		while(--waittime)	//等待倒計時
		{
			delay_ms(10);
			if(USART2_RX_STA&0X8000)//接收到期待的應答結果
			{
				if(StringFind_test(ack, test_1) == 0)
				{
					printf("ack:%s\r\n",(u8*)ack);
					break;//得到有效數據 
				}
					USART2_RX_STA=0;
			} 
		}
		if(waittime==0)res=1; 
	}
	return res;
} 



/*************************************************
Function   : StringFind
Description: 在字符串中查找指定的字符串
Input      : pSrc、pDst,在pSrc查找指定pDst子串
Return     : 如果查找到返回0,如果沒有查到返回-1
English    : find string in string, return the first start location or -1 if can not find  
*************************************************/
int StringFind_test(const char *pSrc, const char *pDst)  
{  
    int i, j;  
    for (i=0; pSrc[i]!='\0'; i++)  
    {  
        if(pSrc[i]!=pDst[0])  
            continue;         
        j = 0;  
        while(pDst[j]!='\0' && pSrc[i+j]!='\0')  
        {  
            j++;  
            if(pDst[j]!=pSrc[i+j])  
            break;  
        }  
        if(pDst[j]=='\0')  
            return 0;  
    }  
    return -1;  
}  

void light_Status_changes_test(int flag)
{
	if(flag_lights_test == 0) control_brightness(Lights_off);
	if(flag_lights_test == 1) control_brightness(Low_brightness);
	if(flag_lights_test == 2) control_brightness(Medium_brightness);
	if(flag_lights_test == 3) control_brightness(high_brightness);
}
/*添加結束*/

演示視頻:

物聯網小燈演示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章