次のリストが部屋の明るさをフォトセンサーで捉えて、MQTTのパブリッシュメッセージを定期的に送出するプログラムです。
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
byte con[]={0x10,0x21,0x00,0x06,'M','Q','I','s','d','p',0x03,0x02,0x00,0x3c,0x00,0x13,'m','o','s','q','s','u','b','/','1','2','5','1','6','-','h','i','r','o','3'};
byte pub[]={0x30,0x11,0x00,0x0b,'a','r','d','u','i','n','o','/','a','2','/','0','0','0','0'};
void getResponse(int j){
int i;
for (i=0;i<j;i++){
if (mySerial.available())
Serial.write(mySerial.read());
delay(1);
}
}
void setup()
{
int i,j;
Serial.begin(9600);
mySerial.begin(9600);
while(!Serial);
mySerial.print("AT+RST\r\n");
getResponse(5000);
mySerial.print("AT+CIPSTART=\"TCP\",\"192.168.1.16\",1883\r\n");
getResponse(1000);
mySerial.print("AT+CIPSEND=35\r\n");
getResponse(1000);
for (i=0;i<35;i++)mySerial.write(con[i]);
getResponse(1000);
}
void loop(){
int i,v,n;
mySerial.print("AT+CIPSEND=19\r\n");
getResponse(1000);
v = analogRead(2);
n=int(v/1000);
pub[15]='0'+n;
v = v -(n*1000);
n=int(v/100);
pub[16]='0'+n;
v = v - (n*100);
n=int(v/10);
pub[17]='0'+n;
v = v - (n*10);
pub[18]='0'+v;
for (i=0;i<19;i++)mySerial.write(pub[i]);
getResponse(1000);
}
MQTTで始めるIoTデバイスの作り方 第4回:ArduinoをMQTTブローカーに接続する
MQTTで始めるIoTデバイスの作り方 第3回:ESP8266でMQTT
MQTTで始めるIoTデバイスの作り方 第2回:MQTTのプロトコルを解析して挙動を理解する
MQTTで始めるIoTデバイスの作り方 第1回:「MQTT」を知り「Mosquitto」を導入するCopyright © ITmedia, Inc. All Rights Reserved.
組み込み開発の記事ランキング
コーナーリンク