Last active
February 10, 2018 04:29
-
-
Save ma2shita/2e585c93a0aec7f3290b207f82ae7f8a to your computer and use it in GitHub Desktop.
Grove Buzzer Control via MQTT of PubNub and SORACOM Beam (for CodeZine)
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
/* CodeZine: Grove IoT Starter Kit for SORACOM <grove-buzzer-with-mqtt-and-soracom-beam.ino> */ | |
#include <WioLTEforArduino.h> | |
#include <WioLTEClient.h> | |
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient | |
#include <stdio.h> | |
#define APN "soracom.io" | |
#define USERNAME "sora" | |
#define PASSWORD "sora" | |
#define MQTT_SERVER_HOST "beam.soracom.io" | |
#define MQTT_SERVER_PORT (1883) | |
#define ID "pubnub-client0" | |
#define OUT_TOPIC "upstream" | |
#define IN_TOPIC "downstream" | |
#define INTERVAL (10000) | |
#define BUZZER_PIN (WIOLTE_D38) | |
WioLTE Wio; | |
WioLTEClient WioClient(&Wio); | |
PubSubClient MqttClient; | |
void callback(char* topic, byte* payload, unsigned int length) { | |
SerialUSB.print("Subscribe:"); | |
for (int i = 0; i < length; i++) SerialUSB.print((char)payload[i]); | |
SerialUSB.println(""); | |
digitalWrite(BUZZER_PIN, HIGH); | |
delay(100); | |
digitalWrite(BUZZER_PIN, LOW); | |
} | |
void setup() { | |
delay(200); | |
SerialUSB.println(""); | |
SerialUSB.println("--- START ---------------------------------------------------"); | |
SerialUSB.println("### I/O Initialize."); | |
Wio.Init(); | |
pinMode(BUZZER_PIN, OUTPUT); | |
digitalWrite(BUZZER_PIN, LOW); | |
SerialUSB.println("### Power supply ON."); | |
Wio.PowerSupplyLTE(true); | |
delay(500); | |
SerialUSB.println("### Turn on or reset."); | |
if (!Wio.TurnOnOrReset()) { | |
SerialUSB.println("### ERROR! ###"); | |
return; | |
} | |
SerialUSB.println("### Connecting to \""APN"\"."); | |
if (!Wio.Activate(APN, USERNAME, PASSWORD)) { | |
SerialUSB.println("### ERROR! ###"); | |
return; | |
} | |
SerialUSB.println("### Connecting to MQTT server \""MQTT_SERVER_HOST"\""); | |
MqttClient.setServer(MQTT_SERVER_HOST, MQTT_SERVER_PORT); | |
MqttClient.setCallback(callback); | |
MqttClient.setClient(WioClient); | |
if (!MqttClient.connect(ID)) { | |
SerialUSB.println("### ERROR! ###"); | |
return; | |
} | |
MqttClient.subscribe(IN_TOPIC); | |
SerialUSB.println("### Setup completed."); | |
} | |
void loop() { | |
char data[100]; | |
sprintf(data, "{\"uptime\":%lu}", millis() / 1000); | |
SerialUSB.print("Publish:"); | |
SerialUSB.print(data); | |
SerialUSB.println(""); | |
MqttClient.publish(OUT_TOPIC, data); | |
err: | |
unsigned long next = millis(); | |
while (millis() < next + INTERVAL) | |
{ | |
MqttClient.loop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment