Skip to content

Instantly share code, notes, and snippets.

@ydniw
Created February 19, 2022 19:14
Show Gist options
  • Save ydniw/9434e5fc9e1e4f53b5537cb624324914 to your computer and use it in GitHub Desktop.
Save ydniw/9434e5fc9e1e4f53b5537cb624324914 to your computer and use it in GitHub Desktop.
Arduino Lesson: SIM800 mqtt
#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