Created
May 25, 2018 07:07
-
-
Save shahrulnizam/584cec622bc902c767a764135833cb14 to your computer and use it in GitHub Desktop.
Arduino Lesson: SIM800 mqtt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define TINY_GSM_MODEM_SIM800 | |
#include <SoftwareSerial.h> | |
#include <TinyGsmClient.h> | |
#include <PubSubClient.h> | |
SoftwareSerial SerialAT(2,3); // RX, TX | |
//Network details | |
const char apn[] = "my3g"; | |
const char user[] = ""; | |
const char pass[] = ""; | |
// MQTT details | |
const char* broker = "broker.hivemq.com"; | |
const char* topicOut = "shahrulnizam/out"; | |
const char* topicIn = "shahrulnizam/in"; | |
TinyGsm modem(SerialAT); | |
TinyGsmClient client(modem); | |
PubSubClient mqtt(client); | |
void setup() | |
{ | |
Serial.begin(9600); | |
SerialAT.begin(9600); | |
Serial.println("System start."); | |
modem.restart(); | |
Serial.println("Modem: " + modem.getModemInfo()); | |
Serial.println("Searching for telco provider."); | |
if(!modem.waitForNetwork()) | |
{ | |
Serial.println("fail"); | |
while(true); | |
} | |
Serial.println("Connected to telco."); | |
Serial.println("Signal Quality: " + String(modem.getSignalQuality())); | |
Serial.println("Connecting to GPRS network."); | |
if (!modem.gprsConnect(apn, user, pass)) | |
{ | |
Serial.println("fail"); | |
while(true); | |
} | |
Serial.println("Connected to GPRS: " + String(apn)); | |
mqtt.setServer(broker, 1883); | |
mqtt.setCallback(mqttCallback); | |
Serial.println("Connecting to MQTT Broker: " + String(broker)); | |
while(mqttConnect()==false) continue; | |
Serial.println(); | |
} | |
void loop() | |
{ | |
if(Serial.available()) | |
{ | |
delay(10); | |
String message=""; | |
while(Serial.available()) message+=(char)Serial.read(); | |
mqtt.publish(topicOut, message.c_str()); | |
} | |
if(mqtt.connected()) | |
{ | |
mqtt.loop(); | |
} | |
} | |
boolean mqttConnect() | |
{ | |
if(!mqtt.connect("GsmClientTest")) | |
{ | |
Serial.print("."); | |
return false; | |
} | |
Serial.println("Connected to broker."); | |
mqtt.subscribe(topicIn); | |
return mqtt.connected(); | |
} | |
void mqttCallback(char* topic, byte* payload, unsigned int len) | |
{ | |
Serial.print("Message receive: "); | |
Serial.write(payload, len); | |
Serial.println(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
excuse me, can you explain what's the different between topic in and topic out?