2016年3月31日木曜日

Arduino+ESP8266でIoT

 123D CircuitsのArduino+ESP8266の仮想デバイスをもとに、実際に回路を組んでみました。
その際の手順などを説明します。

○用意するモノ

SunFounder(サンファウンダー)ESP8266Wifi無線シリアルトランシーバモジュール UNO R3 Mega2560 Nano Arduino初心者専用 [並行輸入品]
PL2303HX内蔵USBシリアル変換ケーブル
PL2303HX内蔵USBシリアル変換ケーブルのドライバ
・通信ソフト TeraTerm
・ファームウェア書き換えツール FLASH_DOWNLOAD_TOOLS_v2.4_150924
※ファームウェア書き換えツールは必須ではありません。

 上記ESP8266WiFiモジュール(ESP-01)は、技適が付いてないので注意。また、シリアル変換ケーブルは各種ありますが、Windows10に対応していないものもあるので注意が必要です。
 技適取得済みのWiFiモジュール(ESP-WROOM-02)は、スイッチサイエンスなどで購入できます。使い方は変わらないので、こちらを利用することをお勧めします(端子配列は異なる)。ただし、ESP-WROOM-02を使用したモジュールは、Arduinoの3.3V電源では駆動できないため、別途3.3Vを供給するための電源が必要になります。

EasyWordMall 3.3V 5V MB102ブレッドボード用 電源モジュール パワーモジュール
ACアダプター 12V/0.5A

○下準備
①PL2303HX内蔵USBシリアル変換ケーブルのドライバ、TeraTermをインストールします。
②次のように回路を接続します。
※3.3V電源はArudinoから供給、ESP-WROOM-02の場合は別電源が必要


TXシリアル変換ケーブル白
RXシリアル変換ケーブル緑
CH_PD3.3V
VCC3.3V

○TeraTermの設定
①TeraTermを起動します
②[シリアル(E)]をオンにし、[ポート(R)]から「COMn:Prolific USB-to-Serial Comm Port(COMn)」(「n」は番号で環境により異なる)を選択し、[OK]ボタンをクリックします。


③[設定(S)]→[端末(T)]を選択します。
④「改行コード」の[受信(R)]と[送信(M)]を「CR+LF」に設定し、[OK]ボタンをクリックします。


⑤[設定(S)]→[シリアルポート(E)]を選択します。
⑥[ボー・レート(B)]を「115200」に設定し、[OK]ボタンをクリックします。


⑦[設定(S)]→[設定の保存(S)]を選択します。
⑧保存先フォルダを選択し、[保存(S)]ボタンをクリックします。

○ESP-01の設定
 ESP-01は、初期設定がAPモードになっているため、次のように操作して、モードを変更します。

①TeraTermから「AT」と入力し、[Enter]キーを押し、「OK」と表示されることを確認します。
※「OK」と表示されない場合は、配線を確認してください。
②「AT+CWMODE=3」と入力し、「Enter」キーを押します。

ATコマンドについては、こちらを参照してください。

○回路の配線
 LED制御と温度計測をするための回路を組みます。



○プログラムの作成
 実際の回路では、Wifi接続時などのウェイト時間を多くとらないと上手く動きません。

・LED制御
int LED = 5;
int errorLED = 11;
String ssid = "<SSID>"; // wifi SSID
String password = "<Password>"; // wifi password
String host = "dweet.io"; // dweet.io
const int httpPort = 80;
String uri = "/get/latest/dweet/for/arduino-led-onoff";
// the setup routine runs once when you press reset:
void setup() {
pinMode(LED, OUTPUT); // init our bule LED
pinMode(errorLED, OUTPUT); // init our red error LED
// Start our ESP8266 Serial Communication
Serial.begin(115200); // Serial connection over USB to computer
Serial.println("AT"); // Serial connection on Tx / Rx port to ESP8266
delay(5000); // Wait a little for the ESP to respond
if (!Serial.find("OK")) digitalWrite(errorLED, HIGH); // check if the ESP is running well
// Connect to Wifi
Serial.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
delay(10000); // Wait a little for the ESP to respond
if (!Serial.find("OK")) digitalWrite(errorLED, HIGH); // check if the ESP is running well
// Open TCP connection to the host:
Serial.println("AT+CIPSTART=\"TCP\",\"" + host + "\"," + httpPort);
delay(50); // Wait a little for the ESP to respond
if (!Serial.find("OK")) digitalWrite(errorLED, HIGH); // check if the ESP is running well
}
// the loop routine runs over and over again forever:
void loop() {
// Construct our HTTP call
String httpPacket = "GET " + uri + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n";
int length = httpPacket.length();
// Send our message leuntilngth
Serial.print("AT+CIPSEND=");
Serial.println(length);
delay(10); // Wait a little for the ESP to respond
if (!Serial.find(">")) {
digitalWrite(errorLED, HIGH); // check if the ESP is running well
} else {
digitalWrite(errorLED, LOW);
}
// Send our http request
Serial.print(httpPacket);
delay(10); // Wait a little for the ESP to respond
if (!Serial.find("SEND OK\r\n")) digitalWrite(errorLED, HIGH); // check if the ESP is running well
while(!Serial.available()) delay(5); // wait we receive the response from the server
if (Serial.find("\r\n")){ // search for a blank line which defines the end of the http header
delay(5);
unsigned int i = 0; //timeout counter
String outputString = "";
while (!Serial.find("\"action\":\"")){} // find the part we are interested in.
while (i<60000) { // 1 minute timeout checker
if(Serial.available()) {
char c = Serial.read();
if(c=='\"') break; // break out of our loop because we got all we need
outputString += c; // append to our output string
i=0; // reset our timeout counter
}
i++;
}
if(outputString=="on"){
digitalWrite(LED, HIGH);
} else {
digitalWrite(LED, LOW);
}
}
delay(10000); // wait 10 seconds before updating
}
view raw led_dweet.ino hosted with ❤ by GitHub
・温度計測
int sensorPin = 0;
int errorLED = 11;
String ssid = "<SSID>"; // wifi SSID
String password = "<Password>"; // wifi Password
String host = "dweet.io"; // dweet.io
const int httpPort = 80;
String uri = "/dweet/for/arduino-temperature";
// the setup routine runs once when you press reset:
void setup() {
pinMode(errorLED, OUTPUT); // init our red error LED
// Start our ESP8266 Serial Communication
Serial.begin(115200); // Serial connection over USB to computer
Serial.println("AT"); // Serial connection on Tx / Rx port to ESP8266
delay(5000); // Wait a little for the ESP to respond
if (!Serial.find("OK")) digitalWrite(errorLED, HIGH); // check if the ESP is running well
// Connect to Wifi
Serial.println("AT+CWJAP=\"" + ssid + "\",\"" + password + "\"");
delay(10000); // Wait a little for the ESP to respond
if (!Serial.find("OK")) digitalWrite(errorLED, HIGH); // check if the ESP is running well
// Open TCP connection to the host:
Serial.println("AT+CIPSTART=\"TCP\",\"" + host + "\"," + httpPort);
delay(50); // Wait a little for the ESP to respond
if (!Serial.find("OK")) digitalWrite(errorLED, HIGH); // check if the ESP is running well
}
// the loop routine runs over and over again forever:
void loop() {
int reading = analogRead(sensorPin);
float voltage = reading * 5.0 / 1024.0;
float temperatureC = voltage * 100;
// Construct our HTTP call
String httpPacket = "POST " + uri +"?temperature="+ temperatureC + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n";
int length = httpPacket.length();
// Send our message length
Serial.print("AT+CIPSEND=");
Serial.println(length);
delay(10); // Wait a little for the ESP to respond
if (!Serial.find(">")) digitalWrite(errorLED, HIGH); // check if the ESP is running well
// Send our http request
Serial.print(httpPacket);
delay(10); // Wait a little for the ESP to respond
if (!Serial.find("SEND OK\r\n")) digitalWrite(errorLED, HIGH); // check if the ESP is running well
delay(10000); // wait 10 seconds before updating
}
view raw dweet_temp.ino hosted with ❤ by GitHub

 
 <SSID>にはWiFiのSSIDを、<password>にはWiFiのパスワードを入力します。
 クライアント側(ブラウザ側)のHTMLコードは変わりませんので、前回の記事を参照してください。

2016年3月29日火曜日

123D CircuitsでIoTデバイス(Arduino+ESP8266)のプロトタイピング-その2 センサーデータ収集

今回は、123D Circuits上に作成したArduino+ESP8266(WIFIモジュール)の仮想IoTデバイスで計測した温度データを取得、収集した可視化してみます。IoTプラットフォームには、dweet.ioを使います。

以下のHTMLを「temp_123d.htm」と名前を付けて保存してください。
※このコードは、このブログのサイドバーに埋め込んでいます。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>温度</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="http://dweet.io/client/dweet.io.min.js"></script>
</head>
<body>
<div>
<button onclick="subscribe()">接続</button>
<button onclick="unsubscribe()">切断</button>
</div>
<div>
<div id="temperatureGauge"></div>
<div id="chart_div"></div>
</div>
<script type="text/javascript">
var thingName = "arduino-temperature" // channel名の設定
// Google Chart
google.load("visualization", "1", {packages:["gauge", "line","corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Data for temperature Gauge
Data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Temperature', 0],
]);
// Option for temperature Gauge
Options = {
width: 200, height: 200,
min: 0, max: 150,
redFrom: 112, redTo: 150,
yellowFrom:75, yellowTo: 112,
minorTicks: 5
};
Gauge = new google.visualization.Gauge(document.getElementById('temperatureGauge'));
Gauge.draw(Data, Options);
};
function subscribe() {
dweetio.listen_for(thingName, function(dweet){
// Update temperature data
Data.setValue(0, 1, dweet.content.temperature);
Gauge.draw(Data, Options);
});
}
function unsubscribe(){
dweetio.stop_listening_for(thingName);
Data.setValue(0, 1, 0);
Gauge.draw(Data, Options);
}
</script>
</body>
</html>
view raw temp_123d.js hosted with ❤ by GitHub
123D Circuitsの[Start Simulation]をクリックしてください。

「temp_123d.htm」をブラウザで開いてください。
[接続]ボタンをクリックすると温度データと取得します。
[切断]ボタンをクリックすると、データの取得を停止します。
※データを取得するまで時間がかかります。


123D Circuitsの温度データを変化させるには、温度センサーLM35をクリックし、表示されたバーをスライドさせます。


グラフで確認するには、こちらを参照してください。


2016年3月28日月曜日

123D CircuitsでIoTデバイス(Arduino+ESP8266)のプロトタイピング-その1 LED制御

123D Circuitsは、Arduino電子回路の仮想実験室です。回路の試作からPCBの作成まで行うことができます。

今回は、123D Circuits上に作成したArduino+ESP8266(WIFIモジュール)の仮想IoTデバイスを、ネットワーク経由で制御してみます。IoTプラットフォームには、dweet.ioを使います。

以下のHTMLを「led_dweet.htm」と名前を付けて保存してください。

<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>dweet test</title>
<script src="http://dweet.io/client/dweet.io.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(function(){
var thingName = "arduino-led-onoff"; //thing nameの設定
// データの送信
function publish(action) {
dweetio.dweet_for(
thingName,
{'action' : action},
function(err, dweet){
console.log(dweet.content);
}
);
}
// [ON]ボタンのクリックで文字列「on」を送信
$('#on-button').click(function(){
publish('on');
});
// [OFF]ボタンのクリックで文字列「off」を送信
$('#off-button').click(function(){
publish('off');
});
});
</script>
</head>
<body>
<button id="on-button">ON</button>
<button id="off-button">OFF</button>
</body>
</html>
view raw led_dweet.html hosted with ❤ by GitHub
123D Circuitsの[Start Simulation]をクリックしてください。


「led_dweet.htm」をブラウザで開いて、[ON]ボタンを押すと、青LEDが点灯し、[OFF]ボタンをクリックすると、消灯します。

※LEDが点灯、消灯するまで、時間がかかる場合があります。