这是已经使用的代码。使用的 IP 位于我的笔记本电脑所连接的同一 WiFi 网络上。只有最后一位数字不同。
#include <Ethernet.h>
#include<SPI.h>
#include <PubSubClient.h>
byte mac[] = { 0x12, 0xED, 0xBA, 0xFE, 0x2E, 0xED };
String macstr="12edbafe2eed";
byte ip[] = {192,16,1,1};
EthernetClient ethClient;
char servername[]="99elnd.messaging.internetofthings.ibmcloud.com";
PubSubClient client(servername, 1883,ethClient);
void setup()
{
Serial.begin(9600);
Serial.println("Arduino MQTT v.1.2");
Ethernet.begin(mac,ip);
}
void loop()
{
char clientStr[33];
String clientName = String("d:99elnd:arduno_mitul:12edbafe2ee2");
clientName.toCharArray(clientStr,33);
char token[] = "mituliot7450";
while (!client.connected()) {
Serial.println("Reconnecting client … ");
client.connect(clientStr, "use-token-auth", token);
}
String data = "{\"d\": {\"TEST\":";
data+=random(10);
data+="} }";
char jsonStr[33];
data.toCharArray(jsonStr,33);
char topicStr[33];
String topicName = String("iot-2/evt/status/fmt/json");
topicName.toCharArray(topicStr,33);
Serial.print("attempt to send");
Serial.print(jsonStr);
Serial.print("to");
Serial.println(topicStr);
if (client.publish(topicStr,jsonStr))
Serial.println("successfully sent");
else
Serial.println("unsuccessfully sent");
Serial.println("Disconnecting client … ");
client.disconnect();
delay(5000);
}
串行监视器打印:
Arduino MQTT v.1.2
Reconnecting client …
Reconnecting client …
Reconnecting client …
Reconnecting client …
Reconnecting client …