1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

mqtt を使って Arduino をLチカ

Posted at

mqtt を使って Arduino をLチカさせます。

こんな感じに ubuntu 側から mqtt で myTestRoom に green と送ると Arduino が緑色になります。
Eu4O0muVgAY5b2p.jpeg
まずは、Ubuntu 側でデバッグ様にルームの購読

mosquitto_sub -d -t myTestRoom ;

次にそのルームにメッセージを送信

mosquitto_pub -d -t myTestRoom -m "green ;

毎回送信するのが面倒なので watch コマンドで定期的にメッセージを送るよう設定

watch 'mosquitto_pub -d -t myTestRoom -m "green"' ;

あとは Arduino 側で、ルームを購読して特定の文字が来たら実行を行います。

設定IPアドレス(あとで書きます)

|項目 |設定値 |
|---|---|---|
|1 |2 |
|4 |5 |

使用機材(あとで書きます)

|項目 |設定値 |
|---|---|---|
|1 |2 |
|4 |5 |

使用ライブラリ(あとで書きます)

|項目 |設定値 |
|---|---|---|
|1 |2 |
|4 |5 |

接続方法(あとで書きます)

|項目 |設定値 |
|---|---|---|
|1 |2 |
|4 |5 |

ソースコード(あとでリファクタリングを行います)

mqtt.ino
#include <SPI.h>

// Set your MAC address and IP address here
#include <UIPEthernet.h>
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x78, 0xEE  };  
IPAddress ip(192, 168, 0, 117);
IPAddress myDns(192, 168, 0, 1);                        
EthernetClient ethClient;

// Make sure to leave out the http and slashes!
#include <PubSubClient.h>
const char* mqttServer = "192.168.0.104";
const char* mqttRoom = "myTestRoom";
const char* mqttClientName = "myArduino";
PubSubClient mqttClient(ethClient);
void subscribeReceive(char* topic, byte* payload, unsigned int length);

//
#include <Adafruit_NeoPixel.h>
#define PIN            2
#define NUMPIXELS      16
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int delayval = 250; // delay for half a second

//
void setup(){
  
  Serial.begin(9600);

  pixels.begin(); // This initializes the NeoPixel library.
  
  Ethernet.begin(mac, ip , myDns );
  Serial.println("Ethernet init success");

  Serial.print("localIP: ");
  Serial.println(Ethernet.localIP());
  Serial.print("subnetMask: ");
  Serial.println(Ethernet.subnetMask());
  Serial.print("gatewayIP: ");
  Serial.println(Ethernet.gatewayIP());
  Serial.print("dnsServerIP: ");
  Serial.println(Ethernet.dnsServerIP());
  
  delay(3000);                          
 
  mqttClient.setServer( mqttServer , 1883);   

  mqttReconect();

}
void mqttReconect(){

  if(mqttClient.connect( mqttClientName )) {

    Serial.println("Connection has been established, well done");
    mqttClient.setCallback(subscribeReceive);
  
  } else{
    mqttReconect();
  }

}

//
void loop(){

  mqttClient.loop();
  mqttClient.subscribe( mqttRoom );
  
  /*
  char* mqttMessage = "Hello from Arduino init";
  if(mqttClient.publish( mqttRoom , mqttMessage )){
    Serial.println("Publish message success");
  }
  //
  else{
    Serial.println("Could not send message :(");
  }
  //delay(4000);
  */
 
}

//
void subscribeReceive(char* topic, byte* payload, unsigned int length){

  // Print the topic
  //Serial.print("Topic: ");
  //Serial.println(topic);
 
  // Print the message
  //Serial.print("Message: ");
  /*
  char* resultMessage = "";
  for(int i = 0; i < length; i ++){
    //Serial.println(char(payload[i]));
    resultMessage[ i ] = payload[i];
  }
  resultMessage[ length ] = '\0';
  */
  payload[ length ] = '\0';
  String resultMessage = String((char*) payload);

  // color red
  if(  resultMessage == "red" ){

    Serial.println("LED RED start");
    
    for(int i=0;i<NUMPIXELS;i++){
      pixels.setPixelColor(i, pixels.Color(10,0,0));
      pixels.show();
      delay(delayval);
    }

  }
  
  // color blue
  else if( resultMessage == "blue"){

    for(int i=0;i<NUMPIXELS;i++){
      pixels.setPixelColor(i, pixels.Color(0,0,10));
      pixels.show();
      delay(delayval);
    }

  }
  
  // color green
  else if( resultMessage == "green"){
    
    for(int i=0;i<NUMPIXELS;i++){
      pixels.setPixelColor(i, pixels.Color(0,10,0));
      pixels.show();
      delay(delayval);
    }

  }
 
}
~~~~

mqtt で制御ができるので、うまくすれば、いろいろと遊べそうです。
###参考リンク
- [How To Use Basic MQTT on Arduino ](https://www.digikey.com/en/maker/blogs/2018/how-to-use-basic-mqtt-on-arduino)
- [UbuntuMosquittoをインストールしてMQTTブローカーを構築 - Qiita]( https://qiita.com/kyoro353/items/b862257086fca02d3635)
- [MQTTMQTTの導入 mosquittoのインストール/動作確認まで - Qiita ](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F426354%2Fe6ec1314-653b-3dd2-31d7-dc1619f14f1f.png?ixlib=rb-1.2.2&auto=format&gif-q=60&q=75&w=1400&fit=max&s=db11f2f6ac35734839ad300c26beb937)
- [hawksnowlog: Arduino でバイト配列を文字列に変換する方法 ](https://hawksnowlog.blogspot.com/2017/06/convert-byte-array-to-string.html)
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?