MQTTで始めるIoTデバイスの作り方 第5回:部屋の明るさを「パブリッシュ」するMQTTで始めるIoTデバイスづくり(5)(3/5 ページ)

» 2016年07月21日 07時00分 公開
[今岡通博MONOist]

 次のリストが部屋の明るさをフォトセンサーで捉えて、MQTTのパブリッシュメッセージを定期的に送出するプログラムです。

  1. #include <SoftwareSerial.h>
  2. SoftwareSerial mySerial(10, 11); // RX, TX
  3. 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'};
  4. byte pub[]={0x30,0x11,0x00,0x0b,'a','r','d','u','i','n','o','/','a','2','/','0','0','0','0'};
  5. void getResponse(int j){
  6. int i;
  7. for (i=0;i<j;i++){
  8. if (mySerial.available())
  9. Serial.write(mySerial.read());
  10. delay(1);
  11. }
  12. }
  13. void setup()
  14. {
  15. int i,j;
  16. Serial.begin(9600);
  17. mySerial.begin(9600);
  18. while(!Serial);
  19. mySerial.print("AT+RST\r\n");
  20. getResponse(5000);
  21. mySerial.print("AT+CIPSTART=\"TCP\",\"192.168.1.16\",1883\r\n");
  22. getResponse(1000);
  23. mySerial.print("AT+CIPSEND=35\r\n");
  24. getResponse(1000);
  25. for (i=0;i<35;i++)mySerial.write(con[i]);
  26. getResponse(1000);
  27. }
  28. void loop(){
  29. int i,v,n;
  30. mySerial.print("AT+CIPSEND=19\r\n");
  31. getResponse(1000);
  32. v = analogRead(2);
  33. n=int(v/1000);
  34. pub[15]='0'+n;
  35. v = v -(n*1000);
  36. n=int(v/100);
  37. pub[16]='0'+n;
  38. v = v - (n*100);
  39. n=int(v/10);
  40. pub[17]='0'+n;
  41. v = v - (n*10);
  42. pub[18]='0'+v;
  43. for (i=0;i<19;i++)mySerial.write(pub[i]);
  44. getResponse(1000);
  45. }

Copyright © ITmedia, Inc. All Rights Reserved.