2017年5月27日 星期六

LinkIt ONE: Wifi 連接和 Http Operation

操作 HTTP 來撈資料或控制,是核心功能沒有之一,以下筆記紀錄 LinkIt ONE 做 Wifi + HTTP 操作。

設置


請按照下圖,將 Wifi Antenna 接在中間。 (這個天線的安裝最好在斷電下執行) 

*接著,請注意靠近中間的開關,應該是朝向 SPI ,也就是靠近 LED 的位置。

打開範例專案

圖出處: (連結)

修改參數

以要求這個網址: http://jsonplaceholder.typicode.com/posts/1 為範例。

註解如下:

/*
  Web client

 This sketch connects to a website 
 using Wi-Fi functionality on MediaTek LinkIt platform.

 Change the macro WIFI_AP, WIFI_PASSWORD, WIFI_AUTH and SITE_URL accordingly.

 created 13 July 2010
 by dlf (Metodo2 srl)
 modified 31 May 2012
 by Tom Igoe
 modified 20 Aug 2014
 by MediaTek Inc.
 */

#include <LWiFi.h>
#include <LWiFiClient.h>

#define WIFI_AP "AP 名稱(可以有空格)"
#define WIFI_PASSWORD "AP 密碼"
#define WIFI_AUTH LWIFI_WPA  // choose from LWIFI_OPEN, LWIFI_WPA, or LWIFI_WEP. //選擇加密模式
#define SITE_URL "jsonplaceholder.typicode.com" //Host 名稱,注意這個不是 URL 全部。

LWiFiClient c;

void setup()
{
  LWiFi.begin();
  Serial.begin(115200);

  // keep retrying until connected to AP
  Serial.println("Connecting to AP");
  while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)))
  {
    delay(1000);
  }

  // keep retrying until connected to website
  Serial.println("Connecting to WebSite");
  while (0 == c.connect(SITE_URL, 80)) //選擇 Port
  {
    Serial.println("Re-Connecting to WebSite");
    delay(1000);
  }

  // send HTTP request, ends with 2 CR/LF
  Serial.println("send HTTP GET request");
  c.println("GET /posts/1 HTTP/1.1");  //修改 GET, POST...etc, 修改 /posts/1 是主機後面的路徑。
  c.println("Host: " SITE_URL);
  c.println("Connection: close");
  c.println();

  // waiting for server response
  Serial.println("waiting HTTP response:");
  while (!c.available())
  {
    delay(100);
  }
}

boolean disconnectedMsg = false;

void loop()
{
  // Make sure we are connected, and dump the response content to Serial
  while (c)
  {
    int v = c.read();
    if (v != -1)
    {
      Serial.print((char)v);
    }
    else
    {
      Serial.println("no more content, disconnect");
      c.stop();
      while (1)
      {
        delay(1);
      }
    }
  }

  if (!disconnectedMsg)
  {
    Serial.println("disconnected by server");
    disconnectedMsg = true;
  }
  delay(500);
}

燒錄時特別注意 AP 名稱有沒有打對,沒有打對, Console 好像也不會顯示任何東西。
燒錄後馬上監聽 COM Port ,不然它太快輸出完,你就看不到訊息了。


Reference:
https://docs.labs.mediatek.com/resource/linkit-one/en/tutorials/using-http-with-the-linkit-one-development-board

沒有留言:

張貼留言

© ERIC RILEY , 自由無須告知轉貼
Background Japanese Sayagata by Olga Libby