Created
May 17, 2019 06:26
-
-
Save kawashimaken/385234e1549270f36392356172c2b632 to your computer and use it in GitHub Desktop.
ESP32からビットコインの価格(日本円)を取得して表示するプログラム
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <WiFi.h> | |
#include "ArduinoJson.h" | |
#include <HTTPClient.h> | |
//WIFIのID | |
const char* ssid = ""; | |
//WIFIのパースワード、パスワードのないWIFIはこここのままでも良い | |
const char* password = ""; | |
//今回ビットコインの値段を取得するためのAPIのURL | |
const char* apiServer = "https://api.coindesk.com/v1/bpi/currentprice/JPY.json"; | |
//デフォルトのセットアップ処理、初期化をここに描こう | |
void setup() | |
{ | |
// | |
Serial.begin(115200); | |
// WiFiに接続することを試みる | |
Serial.printf("%s に接続してみます", ssid); | |
// | |
WiFi.begin(ssid, password); | |
//接続済 ではない場合 | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
//点を表示する | |
Serial.print("."); | |
} | |
//接続できた場合 | |
Serial.println("接続できた!"); | |
} | |
//メインのループです | |
void loop() | |
{ | |
//WIFIの接続状態を確認する | |
//WIFI接続している場合 | |
if ((WiFi.status() == WL_CONNECTED)) { | |
HTTPClient http; | |
//APIサーバに接続開始 | |
http.begin(apiServer); | |
//HTTP Requestを作成する | |
int httpCode = http.GET(); | |
//返り値を確認する | |
if (httpCode > 0) { | |
//レスポンスを文字列として取得する | |
String payload = http.getString(); | |
//正常の場合は200 | |
//Serial.println(httpCode); | |
//一回レスポンスを表示する | |
Serial.println(payload); | |
//jsonに変換するためにメモリを確保 | |
DynamicJsonDocument doc(1024); | |
//payloadをjson objectに変換する | |
deserializeJson(doc, payload); | |
JsonObject obj = doc.as<JsonObject>(); | |
//その中のbpi.JPYを取り出す | |
JsonObject result=obj[String("bpi")][String("JPY")]; | |
//ビットコインの価格を取り出す、同時に文字列に変換しておく | |
String rate=result[String("rate")]; | |
//表示する | |
Serial.println(rate); | |
} | |
else { | |
Serial.println("HTTP request エラー"); | |
return; | |
} | |
//リソースを解放する | |
http.end(); | |
delay(3000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment