2016年5月22日日曜日

Digispark 開発環境のセットアップ

 Digisparkは、超小型のArduino互換ボードです。
 
 Amazonだと、500円程度(ぼったくり価格でも販売されているので注意)、AliExpressなら200円以下で購入できます。

今回は、Digisparkの開発環境を、Windows10PCにセットアップする方法を説明します。
※Arduino IDEはインストール済のこととします。

○ドライバーのインストール
 次のように操作して、ドライバーをインストールします。
Digisparkのドライバー(micronucleus-2.0a4-win.zip)をダウンロードします。
②ダウンロードしたZIPファイルを解凍し、32ビット環境なら「DPinst.exe」、64ビット環境なら「DPinst64.exe」を実行します。
③「ユーザーアカウント制御」ダイアログボックスが表示されたら、[はい]をクリックします。
④「デバイスドライバのインストルウィザード」の[次へ]をクリックします。
 
⑤[完了]をクリックします。
 

⑥[スタート]ボタンを右クリックして、「デバイスマネージャー」を選択し、デバイスマネージャーを起動します。
DigisparkをUSBポートに挿入し、次の図ように認識されることを確認します。
 

 約5秒後に、リムーブされます。これは仕様なので気にしないでください。ブートローダーのバージョンによっては、認識とリムーブを一定間隔で繰り返す場合もあります。確認が終わったらDigisparkは取り外しておいてください。

○ボードマネージャのインストール
 次のように操作して、ボードマネージャをインストールします。
①Arduino IDEを起動します。
②[ファイル]→[環境設定]を選択します。
 

③「追加のボードマネージャのURL」に次のURLを入力し、[OK]ボタンをクリックします。
 
※複数のボードマネージャのURLを指定する場合、「,」で区切って入力するか、右側のボタンをクリックし、表示されたウィンドウに行単位で入力します。
 

④[ツール]→[ボードマネージャ]を選択します。
 

[タイプ]から「提供された」を選択し、「Digistump AVR Boards」をインストールします。
 

⑥[ツール]→[ボード]→[Digispark(Default- 16.5mhz)]を選択します。
 

⑦[ツール]→[書込装置]→[Micronucleus]を選択します。
 


○スケッチの書き込み
 スケッチを書き込むには、次のように操作します。

Digisparkは取り外しておきます。
②[ファイル]→[スケッチの例]→[Digispark_Examples]→[Start]を選択します。
③[スケッチ]→[マイコンボードに書き込む]を選択します。
④コンパイルが終わり、「Plug in device now...(will timeout in 60 seconds)」と表示されたら、DigisparkをUSBポートに接続します。
 

 書き込みが終了すると、「Micronucleus done. Thank you!」と表示されます。
 


2016年5月21日土曜日

ESP8266でIoT - Adafruit IO偏

  Adafruit IOでESP8266のWiFiモジュールをIoTデバイスに使用する方法を説明します。

※「ESP8266でIoT - 開発環境のセットアップ」の手順で開発環境をセットアップ済のこととします。

○準備
Adafruit IO+Arduino+MQTTでIoT‐センサー・データの収集」の「③Adafruit IOの準備」の手順でアカウントを作成します。
②「Adafruit MQTT Library」(Adafruit_MQTT_Library-master.zip)をダウンロードします。
③Arudino IDEを起動します。
④[スケッチ]→[ライブラリをインクルード]→[.ZIP形式のライブラリをインクルード]を選択します。
⑤ダウンロードしたZIPファイル「Adafruit_MQTT_Library-master.zip」を選択し、[開く]をクリックします。

○プログラム 

・データの送信
 Adafruit IOにデータを送信するプログラムは、次のように書きます。

#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#define WLAN_SSID "...your SSID..."
#define WLAN_PASS "...your password..."
// Adafruit.io Setup
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..."
#define AIO_KEY "...your AIO key..."
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
// Store the MQTT server, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM = AIO_SERVER;
const char MQTT_USERNAME[] PROGMEM = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM = AIO_KEY;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);
// Setup a feed called 'Welcome Feed' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
const char PHOTOCELL_FEED[] PROGMEM = AIO_USERNAME "/feeds/Welcome Feed";
Adafruit_MQTT_Publish Analog = Adafruit_MQTT_Publish(&mqtt, PHOTOCELL_FEED);
void MQTT_connect();
void setup() {
Serial.begin(115200);
delay(10);
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// connect to adafruit io
MQTT_connect();
}
void loop() {
// ping adafruit io a few times to make sure we remain connected
if(! mqtt.ping(3)) {
// reconnect to adafruit io
if(! mqtt.connected())
MQTT_connect();
}
// Grab the current state of the analog input
float analog_data = analogRead(A0);
// Publish data
if (!Analog.publish(analog_data))
Serial.println(F("Failed to publish analog data"));
else
Serial.println(F("Analog data published!"));
// Repeat every 10 seconds
delay(10000);
}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}

・データの取得
 Adafruit IOからデータを取得するプログラムは、次のように書きます。
#include <ESP8266WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
// LED pin
const int led_pin = 5;
#define WLAN_SSID "...your SSID..."
#define WLAN_PASS "...your password..."
// Adafruit.io Setup
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883 // use 8883 for SSL
#define AIO_USERNAME "...your AIO username (see https://accounts.adafruit.com)..."
#define AIO_KEY "...your AIO key..."
// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
// Store the MQTT server, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM = AIO_SERVER;
const char MQTT_USERNAME[] PROGMEM = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM = AIO_KEY;
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);
// Setup a feed called 'LED' for subscribing to changes.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
const char PHOTOCELL_FEED[] PROGMEM = AIO_USERNAME "/feeds/LED";
Adafruit_MQTT_Subscribe led = Adafruit_MQTT_Subscribe(&mqtt, PHOTOCELL_FEED);
void MQTT_connect();
void setup() {
// Set lamp pin to output
pinMode(led_pin, OUTPUT);
Serial.begin(115200);
delay(10);
// Connect to WiFi access point.
Serial.println(); Serial.println();
Serial.print("Connecting to ");
Serial.println(WLAN_SSID);
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// listen for events on the led feed
mqtt.subscribe(&led);
// connect to adafruit io
MQTT_connect();
}
void loop() {
Adafruit_MQTT_Subscribe *subscription;
// ping adafruit io a few times to make sure we remain connected
if(! mqtt.ping(3)) {
// reconnect to adafruit io
if(! mqtt.connected())
MQTT_connect();
}
// this is our 'wait for incoming subscription packets' busy subloop
while (subscription = mqtt.readSubscription(1000)) {
// we only care about the led events
if (subscription == &led) {
// convert mqtt ascii payload to int
char *value = (char *)led.lastread;
Serial.print(F("Received: "));
Serial.println(value);
// Apply message to led
String message = String(value);
message.trim();
if (message == "ON") {digitalWrite(led_pin, HIGH);}
if (message == "OFF") {digitalWrite(led_pin, LOW);}
}
}
}
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}

 LEDを制御するためのフィード、ブロックの方法については、「Adafruit IO+Arduino+MQTTでIoT‐デバイスの制御」の「③Adafruit の準備」を参照してください。
 LEDは、GPIO5に接続します。
 


ESP8266でIoT - M2X偏

 M2X でESP8266のWiFiモジュールをIoTデバイスに使用する方法を説明します。

※「ESP8266でIoT - 開発環境のセットアップ」の手順で開発環境をセットアップ済のこととします。

○準備
①「Arduino+M2XでIoT」の「②M2Xの準備」の手順でデバイスとストリームを作成します。
「AT&T's M2X Android Client」ライブラリをダウンロードします。
③ダウンロードしたZIPファイルを解凍し、「M2XStreamClient」フォルダをArduino IDEのライブラリフォルダ(「Users\<ユーザー名>\Documents\Arduino\libraries」)にコピーします。

○プログラム(スケッチ)
 M2Xにデータを送信するプログラムは、次のように書きます。

#include <ESP8266WiFi.h>
#define ESP8266_PLATFORM
#include "M2XStreamClient.h"
char ssid[] = "<ssid>"; // your network SSID (name)
char pass[] = "<WPA password>"; // your network password (use for WPA, or use as key for WEP)
int keyIndex = 0; // your network key Index number (needed only for WEP)
int status = WL_IDLE_STATUS;
char deviceId[] = "<device id>"; // Device you want to push to
char streamName[] = "<stream name>"; // Stream you want to push to
char m2xKey[] = "<M2X access key>"; // Your M2X access key
WiFiClient client;
M2XStreamClient m2xClient(&client, m2xKey);
void setup() {
Serial.begin(115200);
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
Serial.println("Connected to wifi");
printWifiStatus();
}
void loop() {
float val = analogRead(A0);
Serial.print("value: ");
Serial.print(val);
int response = m2xClient.updateStreamValue(deviceId, streamName, val);
Serial.print("M2x client response code: ");
Serial.println(response);
if (response == -1) while(1) ;
delay(5000);
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}

2016年5月20日金曜日

ESP8266でIoT - IFTTT偏

  IFTTTのMaker用のライブラリも書いてみました。


○ライブラリのインストール
  IFTTTのMaker用のライブラリをインストールするには、次のように操作します。
※「ESP8266でIoT - 開発環境のセットアップ」の手順で開発環境をセットアップ済のこととします。

ESP8266 IFTTT Maker library(IFTTT-esp-master.zip)をダウンロードします。
②Arduino IDEを起動します。
③[スケッチ]→[ライブラリをインクルード]→[.ZIP形式のライブラリをインクルード]を選択します。
④ダウンロードしたZIPファイル「IFTTT-esp-master.zip)」を選択し、[開く]をクリックします。

○プログラム(スケッチ)
 ※プログラムを書込む際には、GPIO0をLowにします。

 IFTTTのMakeにデータを送信するプログラムは、次のように書きます。
#include "IFTTTESP8266.h"
#define EVENT "Your_Maker_Event_Name_here" // Put here your Maker Event Name
#define KEY "Your_Key_here" // Put here your IFTTT key
#define WIFISSID "ssid"
#define PASSWORD "password"
IFTTT client(KEY);
void setup(){
Serial.begin(115200);
delay(10);
client.wifiConnection(WIFISSID, PASSWORD);
}
void loop(){
String value = String(analogRead(A0));
client.add(value1); // specifies the args of type "String"
//Send value can specify up to three
client.add(value2); // optional
client.add(value3); // optional
client.sendAll(EVENT);
}

 データは最大3つ送信できます。データはString型で指定する必要があります。

 IFTTTのMakerについては、以下の記事を参照してください。

ESP8266でIoT - dweet.io偏

   ubidotsのライブラリをベースに、dweet.ioのライブラリを書いてみました。


 使用には、ArduinoJson libraryが必要になります。

○ライブラリのインストール
 dweet.ioのライブラリをインストールするには、次のように操作します。
※「ESP8266でIoT - 開発環境のセットアップ」の手順で開発環境をセットアップ済のこととします。

dweetESP8266 library(dweet-esp-master.zip)をダウンロードします。
②Arduino IDEを起動します。
③[スケッチ]→[ライブラリをインクルード]→[.ZIP形式のライブラリをインクルード]を選択します。
④ダウンロードしたZIPファイル「dweet-esp-master.zip」を選択し、[開く]をクリックします。

○プログラム(スケッチ)
 ※プログラムを書込む際には、GPIO0をLowにします。 

・1つのデータの送信
 dweet.ioに1つのデータを送信するプログラムは、次のように書きます。

include "dweetESP8266.h"
#define THIG_NAME "Your_thing_neme_here" // Put here your thing name
#define WIFISSID "ssid"
#define PASSWORD "password"
dweet client;
void setup(){
Serial.begin(115200);
delay(10);
client.wifiConnection(WIFISSID, PASSWORD);
}
void loop(){
String val = String(analogRead(A0));
client.add(key, val); // specifies the args of type "String"
client.sendAll(THIG_NAME);
}
view raw DweetValue.ino hosted with ❤ by GitHub

 dweet.ioのデータはキーと値の組み合わせで送信します。キー(Key)、値(ValまたはValue)は、String型で指定してください。 たとえば、キー「action」、値「on」のデータを送信するには「client.add(”action”, "on")」と指定します。数値の場合、String型に変換して指定します。

・複数データの送信
 dweet.ioに複数のデータ(最大5つ)を送信するプログラムは、次のように書きます。

#include "dweetESP8266.h"
#define THIG_NAME "Your_thing_neme_here" // Put here your thing name
#define WIFISSID "ssid"
#define PASSWORD "password"
dweet client;
void setup(){
Serial.begin(115200);
delay(10);
client.wifiConnection(WIFISSID, PASSWORD);
}
void loop(){
String value1 = String(analogRead(A0));
String value2 = String(analogRead(A1));
String value3 = String(analogRead(A2));
client.add(key1, value1); // specifies the args of type "String"
client.add(key2, value2);
client.add(key3, value3);
client.sendAll(THIG_NAME);
}


・データの取得
 dweet.ioからデータを取得するプログラムは、次のように書きます。

#include "dweetESP8266.h"
#define THIG_NAME "Your_thing_neme_here" // Put here your thing name
#define WIFISSID "ssid"
#define PASSWORD "password"
dweet client;
void setup() {
Serial.begin(115200);
delay(10);
client.wifiConnection(WIFISSID, PASSWORD);
}
void loop() {
// specifies the args of type "String"
String value = client.getDweet(THIG_NAME, key);
Serial.println(value);
}
view raw GetDweet.ino hosted with ❤ by GitHub
 getDweet関数の第2引数keyには、取得したいデータのキーを指定します。たとえば、キー「action」のデータを取得するには、「getDweet(THIG_NAME, "action")」と指定します。



ESP8266でIoT - ubidots偏

 ubidotsには、ESP8266単体をIoTデバイスにするためのライブラリが用意されています。ドキュメントでは、NodeMCU用とされていますが、ESP8266チップを使用したWiFiモジュールのほぼすべてで使用できます。
 

○準備
①「ESP8266でIoT - 開発環境のセットアップ」の手順で開発環境をセットアップします。
②「Arduino+ubidotsでセンサー・データをリアルタイムで可視(グラフ)化する」の「①ubidotsの準備」の手順でubidotsのデータソース(Source)、変数(Variable)を作成します。

○ライブラリのインストール
 ubidotsのライブラリをインストールするには、次のように操作します。

UbidotsMicroESP8266 library(ubidots-nodemcu-master.zip)をダウンロードします。
②Arudino IDEを起動します。
③[スケッチ]→[ライブラリをインクルード]→[.ZIP形式のライブラリをインクルード]を選択します。
④ダウンロードしたZIPファイル「ubidots-nodemcu-master.zip」を選択し、[開く]をクリックします。

○プログラム(スケッチ)
 ※プログラムを書込む際には、GPIO0をLowにします。 

・1つのデータの送信
 ubidotsに1つのデータを送信するプログラムは、次のように書きます。

#include "UbidotsMicroESP8266.h"
#define ID "<variable ID>" // Put here your Ubidots variable ID
#define TOKEN "<TOKEN>" // Put here your Ubidots TOKEN
#define SSID "<ssid>"
#define PASS "<password>"
Ubidots client(TOKEN);
void setup(){
Serial.begin(115200);
delay(10);
client.wifiConnection(SSID,PASS);
}
void loop(){
float value = analogRead(A0);
client.add(ID, value);
client.sendAll();
}


・複数のデータの送信
 ubidotsに複数のデータ(最大3つ)を送信するプログラムは、次のように書きます。
#include "UbidotsMicroESP8266.h"
#define ID1 "<variable ID1>" // Put here your Ubidots variable ID
#define ID2 "<variable ID2>"
#define ID3 "<variable ID3>"
#define TOKEN "<TOKEN>" // Put here your Ubidots TOKEN
#define SSID "<ssid>"
#define PASS "<password>"
Ubidots client(TOKEN);
void setup(){
Serial.begin(115200);
delay(10);
client.wifiConnection(SSID, PASS);
}
void loop(){
float value1 = analogRead(A0);
float value2 = analogRead(A1);
float value3 = analogRead(A2);
client.add(ID1, value1);
client.add(ID2, value2);
client.add(ID3, value3);
client.sendAll();
}



・データの取得
 ubidotsからデータを取得するプログラムは、次のように書きます。


#include "UbidotsMicroESP8266.h"
#define ID "<variable ID>" // Put here your Ubidots variable ID
#define TOKEN "<TOKEN>" // Put here your Ubidots TOKEN
#define SSID "<ssid>"
#define PASS "<password>"
Ubidots client(TOKEN);
void setup() {
Serial.begin(115200);
delay(10);
client.wifiConnection(SSID,PASS);
}
void loop() {
float value = client.getValue(ID);
Serial.println(value);
}
 <variable ID>にはvariable IDを、<TOKEN>にはubidotsのTOKENを、<ssid>にはWiFiのSSIDを、<password>にはWiFiのパスワードを入力します。

ESP8266でIoT - 開発環境のセットアップ

 今回は、ESP8266単体をIoTデバイスとして使用するために、「 Arduino core for ESP8266 WiFi chip」という開発環境をインストールする方法を説明します。
 「 Arduino core for ESP8266 WiFi chip」は、Arduino IDEにESP8266 チップのサポートを追加すします。Arduinoの機能とライブラリを使用して、ESP8266を単体で動かすプログラム(スケッチ)を作成できます。

○「Arduino core for ESP8266 WiFi chip」のインストール
 Arduino IDEに「 Arduino core for ESP8266 WiFi chip」をインストールするには、次のように操作します。
Arduino IDE(1.6.9)はインストール済のこととします。

①[ファイル]→[環境設定]を選択します。
 

②「追加のボードマネージャのURL」に次のURLを入力し、[OK]ボタンをクリックします。
 
※複数のボードマネージャのURLを指定する場合、「,」で区切って入力するか、右側のボタンをクリックし、表示されたウィンドウに行単位で入力します。
 

③[ツール]→[ボードマネージャ]を選択します。
 

④[タイプ]から「提供された」を選択し、「esp8266 by ESP8266 Community」をインストールします。
 


○ESP-WROOM-02用の設定
 ESP-WROOM-02用に設定するには、次のように操作します。

①[ツール]→[ボード]→[Generic ESP8266 Module]を選択します。
2016052007.png

②[ツール]メニューから、各項目を次のように設定します。

Flash Mode:DIO
Flash Frequency:40MHz
CPU Frequency:80MHz
Flazh Size:4M(3M SPIFFS)
Upload Speed:115200
 
※シリアルポートには、PCとESP-WROOM-02ボードを接続しているポートを指定してください。


2016年5月14日土曜日

IchigoJam+MixJuiceでIoT

  MixJuiceは、IchigoJam用のWiFiネットワークボードです。
 今回は、IchigoJamとMixJuiceを使って、IoTデバイスを構築してみました。IoTプラットフォームにはdweet.ioを使用します。
 具体的には、IchigoJamに接続した温度センサー(TMP36)の計測データを、dweet.iにポストして、そのデータをブラウザで受信してGoogleゲージで可視化します。

○MixJuiceの作成
 MixJuiceの中身はESP-WROOM-02です。ファームウェアも公開されているので、自作することができます。手元にESP-WROOM-02があったので、とりあえずブレッドボードベースで作成してみました。

・必要なモノ

・ツール・ファームウェアのダウンロード
 以下のツール、ファームウェアをダウンロードし、任意のフォルダに解凍しておきます。
  MixJuiceファームウェア(「DOWNLOAD」をクリック)

※rarファイルを解凍するためのツール「7-Zip」のダウンロードはこちらから。

・ESP-WROOM-02の配線

GPIO0 Low(GND)
GPIO2 High(3.3V)
GPIO15 Low(GND)
EN 10kΩで3.3Vにプルアップ
RST 10kΩで3.3Vにプルアップ
TXD シリアル変換ケーブルRXD(白)
RXD シリアル変換ケーブルTXD(緑)


・ファームウェアの書き込み
 次のように操作してMixJuiceのファームウェアを書き込みます。
①FLASH DOWNLOAD TOOLSを起動します。
②COMポート(COM PORT)とボーレート(BOAUDRATE)を設定します。
③「Download Path Config」のいずれかの入力ボックスの右にある[...]ボタンをクリックします。
④MixJuiceファームウェア「MixJuice.bin」を選択し、[開く(O)]ボタンをクリックします。
⑤ADDRに「0x00000」と入力し、左のチェックをオンにします。
⑥その他を次のように設定します。

CristalFreq :26M
SPI SPEED :40MHz
SPI MODE :QIO
FLASH SIZE:32Mbit

 
※この図では「Download Path Config」に「「MixJuice.bin」」以外の項目が入力されていますが、無視してください。

⑦[START]ボタンをクリックします。

 なお ESP-WROOM-02の規定のファームウェアへの書き換え、アップデート方法については、ここを参照してください。

○回路の配線

MixJuice IchigoJam
TXD   RXD
RXD   TXD

 MixJuice(ESP-WROOM-02)の「GPIO0」はHigh(3.3V)に設定します。

 温度センサー(TMP36)は、次のように配線します。
 

○アクセスポイントへの接続
 次のように操作して、アクセスポイント(WiFiルーター)に接続します。
①IchigoJamとMixJuiceの電源をオンにします。
②「?"MJ APC ssid password"」と入力します。ssidにはアクセスポイントのSSIDを、passwordにはアクセスポイントのパスワードを入力します。

○プログラム
・データ送信
 IchigoJamで、次のBASICプログラムを入力します。

1 'temperature
2 c=(ana(2)*32-5000)/100
3 ?"MJ POST START dweet.io/dweet/for/ichigojam?val=";c
4 ?"MJ POST END"
5 wait 3600
6 goto 1
view raw temp.bas hosted with ❤ by GitHub

・データ受信用HTML
 テキストエディタで、次のHTMLコードを入力します。

<!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 = "ichigojam" // 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.val);
Gauge.draw(Data, Options);
});
}
function unsubscribe(){
dweetio.stop_listening_for(thingName);
Data.setValue(0, 1, 0);
Gauge.draw(Data, Options);
}
</script>
</body>
</html>
 BASICプログラム中の「dweet.io/dweet/for/ichigojam?val=」とHTMLコード中の「var thingName = "ichigojam"」の「ichigojam」にデータを送受信するための固有名で、同じ名前を指定します。これは、任意の名前を指定できます。

○動作の確認
 動作を確認するには、次のように操作します。
①IchigoJamでプログラムを実行します。
②ブラウザでデータ受信用HTMLを開き、[接続]ボタンをクリックします。
 

MP3モジュールの制御 - IchigoJam偏

 IchigoJamは、プログラミン言語にBASICを採用しているボードマイコンです。今回は、このIchigoJamでMP3モジュールを制御してみました。

○使用部品

・その他必要なモノ

○配線
MP3
IchigoJam
RX
TXD
TX
RXD
VCC
CN5の1ピン
GND
CN5の5ピン

 

○プログラム
1 'MP3
2 uart 1:bps 9600
3 gosub 20:gosub 25:gosub 40
5 if btn(UP) gosub 50
6 if btn(DOWN) gosub 55
7 if btn(LEFT) gosub 30
8 if btn(RIGHT) gosub 35
15 goto 5
16 end
20 'seldev
21 ? chr$(#7E);chr$(#FF);chr$(#06);chr$(#09);chr$(#0);chr$(#0);chr$(#02);chr$(#EF)
22 wait 120
23 rtn
25 'start
26 ? chr$(#7E);chr$(#FF);chr$(#06);chr$(#03);chr$(#0);chr$(#0);chr$(#1);chr$(#EF)
27 wait 30
28 rtn
30 'playnext
31 ? chr$(#7E);chr$(#FF);chr$(#06);chr$(#01);chr$(#0);chr$(#0);chr$(#0);chr$(#EF)
32 wait 30
33 rtn
35 'playprev
36 ? chr$(#7E);chr$(#FF);chr$(#06);chr$(#02);chr$(#0);chr$(#0);chr$(#0);chr$(#EF)
37 wait 30
38 rtn
40 'setvol
41 ? chr$(#7E);chr$(#FF);chr$(#06);chr$(#06);chr$(#0);chr$(#0);chr$(#10);chr$(#EF)
42 wait 30
43 rtn
50 'volup
51 ? chr$(#7E);chr$(#FF);chr$(#06);chr$(#04);chr$(#0);chr$(#0);chr$(#0);chr$(#EF)
52 wait 30
53 rtn
55 'voldown
56 print chr$(#7E);chr$(#FF);chr$(#06);chr$(#05);chr$(#0);chr$(#0);chr$(#0);chr$(#EF)
57 wait 30
58 rtn
view raw mp3.bas hosted with ❤ by GitHub



 キーボードの方向キーの上下でボリュームのアップダウン、方向キーの左右で前曲/次曲への移動となっています。プログラムの制限が1KBなので、イコライザーなど他の機能を追加するには、プログラムを少し工夫する必要があります。


2016年5月10日火曜日

Johnny-Fiveでマイコン制御5 - 超音波距離センサー

○使用部品

○超音波距離センサー制御端子
Arduino 0~13、A0~A5
Raspberry Pi(※) GPIO04~026

○基本回路/プログラム

◇Arduino
・PingFirmataのインストール
 Arduinoで以下の超音波距離センサーモジュールを使用するには、「PingFirmata」を書き込む必要があります。

・SR04 or HCSR04
・SRF05
・Parallax Ping
・SeeedStudio Ultrasonic Range
・Grove - Ultrasonic Ranger

 「PingFirmata」のソースをコピーして、Arduino IDEから書き込んでください。

・配線
 

・プログラム
http://johnny-five.io/examples/proximity-hcsr04/(デジタル入力端子使用の場合)
http://johnny-five.io/examples/proximity-hcsr04-analog/(アナログ入力端子使用の場合)

◇Raspberry Pi
Raspberry Piでは、Johnny-Fiveを使って超音波距離センサーモジュールを制御することができないため、代替えの方法を紹介します。

・「r-pi-usonic」と「math-statistics」モジュールのインストール
 次のように操作して、「r-pi-usonic」と「math-statistics」モジュールをインストールします。
①ターミナルを起動し、作業用のフォルダに移動します。
②「npm install r-pi-usonic math-statistics [Enter]」と入力します。

・配線
 

・プログラム

var usonic = require('r-pi-usonic');
var statistics = require('math-statistics');
var print = function (distances) {
var distance = statistics.median(distances);
process.stdout.clearLine();
process.stdout.cursorTo(0);
if (distance < 0) {
process.stdout.write('Error: Measurement timeout.\n');
} else {
process.stdout.write('Distance: ' + distance.toFixed(2) + ' cm');
}
};
var initSensor = function (config) {
var sensor = usonic.createSensor(config.echoPin, config.triggerPin, config.timeout);
console.log('Config: ' + JSON.stringify(config));
var distances;
(function measure() {
if (!distances || distances.length === config.rate) {
if (distances) {
print(distances);
}
distances = [];
}
setTimeout(function () {
distances.push(sensor());
measure();
}, config.delay);
}());
};
var echoPin = 24; // GPIO24(18pin)
var triggerPin = 23; // GPIO23(16pin)
var timeout = 750; // μs
var delay = 60; // ms
var rate = 5; // per sample
usonic.init(function (error) {
if (error) {
console.log("error");
} else {
initSensor({
echoPin: echoPin,
triggerPin: triggerPin,
timeout: timeout,
delay: delay,
rate: rate
});
}
});
view raw usonic.js hosted with ❤ by GitHub

 

2016年5月2日月曜日

MP3モジュールの制御 Rasberry Pi&Node.js偏

秋月で購入したMP3モジュールを、Rasberry PiのGPIOに接続して、Node.jsで制御してみました。
 

※Raspberry Pi 3では動作しません。

○下準備
・シリアルコンソールの無効化
 次のように操作して、シリアルコンソールを無効に設定します。
①[Menu]→[設定]→[Raspberry Piの設定]を選択します。
②「インターフェイス」タブを選択し、シリアルを無効に設定し、[OK]をクリックします。

・「serialport」「socket.io」モジュールのインストール
 次のように操作して、「serialport」と「socket.io」モジュールをインストールします。
①ターミナルを起動し、作業用のフォルダに移動します。
②「npm install serialport socket.io[Enter]」と入力します

○配線
モジュール
Raspberry Pi
RX
8
TX
10
VCC
4(または2)
GND
6

○プログラム
・サーバー
 次のJavaScriptコードを入力し、「mp3.js」と名前を付けて作業用フォルダに保存します。
var serialport = require('serialport');
var port = new serialport.SerialPort(
'/dev/ttyAMA0', {
baudrate: 9600,
parser: serialport.parsers.readline('\r\n')
}
);
var html = require('fs').readFileSync('index.html');
var http = require('http').createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html'
});
res.end(html);
});
var io = require('socket.io')(http);
http.listen(3000);
var eqmode = 0;
port.on('open', function () {
SelectPlayerDevice(0x02);
SetVolume(1);
SetEQ(0);
io.on('connection', function(socket) {
socket.on('msg', function(data) {
console.log(data);
if(data == "play"){
SpecifyMusicPlay(1);
}
if(data == "pause"){
PlayPause();
}
if(data == "resume"){
PlayResume();
}
if(data == "prev"){
PlayPrevious();
}
if(data == "next"){
PlayNext();
}
if(data == "loop"){
PlayLoop();
}
if(data == "down"){
DecreaseVolume();
}
if(data == "up"){
IncreaseVolume();
}
if(data == "repon"){
StartRepeat();
}
if(data == "repoff"){
StopRepeat();
}
if(data == "eq"){
eqmode ++;
if (eqmode > 5) eqmode = 0;
SetEQ(eqmode);
}
});
});
});
function SelectPlayerDevice(device) {
var buf = new Buffer([0x7E,0xFF,0x06,0x09,0x00,0,device,0xEF]);
setTimeout(port.write(buf),100);
}
function SpecifyMusicPlay(index) {
var hbyte = parseInt(index / 256);
var lbyte = parseInt(index % 256);
var buf = new Buffer([0x7E,0xFF,0x06,0x03,0x00,hbyte,lbyte,0xEF]);
setTimeout(port.write(buf),1000);
}
function PlayPause() {
var buf = new Buffer([0x7E,0xFF,0x06,0x0E,0x00,0x00,0x00,0xEF]);
setTimeout(port.write(buf),1000);
}
function PlayResume() {
var buf = new Buffer([0x7E,0xFF,0x06,0x0D,0x00,0x00,0x00,0xEF]);
setTimeout(port.write(buf),1000);
}
function PlayNext() {
var buf = new Buffer([0x7E,0xFF,0x06,0x01,0x00,0x00,0x00,0xEF]);
setTimeout(port.write(buf),1000);
}
function PlayPrevious() {
var buf = new Buffer([0x7E,0xFF,0x06,0x02,0x00,0x00,0x00,0xEF]);
setTimeout(port.write(buf),1000);
}
function PlayLoop() {
var buf = new Buffer([0x7E,0xFF,0x06,0x11,0x00,0x00,0x01,0xEF]);
setTimeout(port.write(buf),1000);
}
function SetVolume(volume) {
var buf = new Buffer([0x7E,0xFF,0x06,0x06,0x00,0x00,volume,0xEF]);
setTimeout(port.write(buf),1000);
}
function IncreaseVolume() {
var buf = new Buffer([0x7E,0xFF,0x06,0x04,0x00,0x00,0x00,0xEF]);
setTimeout(port.write(buf),1000);
}
function DecreaseVolume() {
var buf = new Buffer([0x7E,0xFF,0x06,0x05,0x00,0x00,0x00,0xEF]);
setTimeout(port.write(buf),1000);
}
function StartRepeat() {
var buf = new Buffer([0x7E,0xFF,0x06,0x19,0x00,0x00,0x00,0xFE,0xE2,0xEF]);
setTimeout(port.write(buf),1000);
}
function StopRepeat() {
var buf = new Buffer([0x7E,0xFF,0x06,0x19,0x00,0x00,0x01,0xFE,0xE1,0xEF]);
setTimeout(port.write(buf),1000);
}
function SetEQ(mode) {
var buf = new Buffer([0x7E,0xFF,0x06,0x07,0x00,0x00,mode,0xEF]);
setTimeout(port.write(buf),1000);
}
view raw mp3.js hosted with ❤ by GitHub


・クライアント
 次のHTMLコードを入力し、「index.html」と名前を付けて作業用フォルダに保存します。
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>MP3 TEST</title>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
</head>
<body>
<script>
var socket = io();
function play() {
socket.emit('msg', 'play');
}
function pause() {
socket.emit('msg', 'pause');
}
function resume() {
socket.emit('msg', 'resume');
}
function prev() {
socket.emit('msg', 'prev');
}
function next() {
socket.emit('msg', 'next');
}
function up() {
socket.emit('msg', 'up');
}
function down() {
socket.emit('msg', 'down');
}
function loop() {
socket.emit('msg', 'loop');
}
function seteq() {
socket.emit('msg', 'eq');
}
function repon() {
socket.emit('msg', 'repon');
}
function repoff() {
socket.emit('msg', 'repoff');
}
</script>
<form>
<input type="button" value="PLAY" onclick="play()"/>
<input type="button" value="PAUSE" onclick="pause()"/>
<input type="button" value="RESUME" onclick="resume()"/>
<input type="button" value="<<" onclick="prev()"/>
<input type="button" value=">>" onclick="next()"/>
<input type="button" value="<" onclick="down()"/>
<input type="button" value=">" onclick="up()"/>
<input type="button" value="LOOP" onclick="loop()"/>
<input type="button" value="EQ" onclick="seteq()"/>
<input type="button" value="REP ON" onclick="repon()"/>
<input type="button" value="REP OFF" onclick="repoff()"/>
</form>
</body>
</html>
view raw index.html hosted with ❤ by GitHub


○動作の確認
 次のように操作して、動作を確認します。
①ターミナルを起動し、作業用フォルダに移動します。
②「sudo node mp3.js」と入力します。
③ブラウザで「http://localhost:3000」にアクセスします。
④各ボタンをクリックし、動作を確認します。