Skip to content

Instantly share code, notes, and snippets.

@m2mIO-gister
Created September 26, 2013 22:38
Show Gist options
  • Save m2mIO-gister/6721582 to your computer and use it in GitHub Desktop.
Save m2mIO-gister/6721582 to your computer and use it in GitHub Desktop.
Arduino sketch for reading MaKey MaKey digital output pins and sending them via MQTT.
#include <SPI.h>
#include <PubSubClient.h>
#include <WiFi.h>
#include <Timer.h>
#define M2MIO_USERNAME "<2lemetry platform username>"
#define M2MIO_PASSWORD "<MD5 hash of 2lemetry password>"
#define M2MIO_DOMAIN "<domain on 2lemetry platform>"
#define M2MIO_STUFF "arduino"
#define M2MIO_DEVICE_ID "teslamqtt"
#define MQTT_SERVER "q.m2m.io"
char ssid[] = "<myssid>"; // network SSID (name)
char pass[] = "<mynetworkpassphrase>"; // network passphrase
int status = WL_IDLE_STATUS; // the Wifi radio's status
WiFiClient wifiClient;
PubSubClient mmClient(MQTT_SERVER, 1883, mmCallback, wifiClient);
char clientID[50];
char topic[50];
char msg[50];
#define PROCESSING_INTERVAL 600
Timer t;
int kbPin = 3;
int clPin = 4;
int kbVal = 0;
int clVal = 0;
/*
* SETUP
*
*/
void setup()
{
// init serial link for debugging
Serial.begin(9600);
pinMode(kbPin, INPUT);
pinMode(clPin, INPUT);
// connect to WiFi access point
Serial.print("Attempting to connect to WiFi...");
status = WiFi.begin(ssid, pass);
// if you're not connected, stop here:
if ( status != WL_CONNECTED) {
Serial.print("ERROR: couldn't get a wifi connection.");
while(true);
}
else {
Serial.print("connected.");
}
Serial.println();
String clientIDStr = M2MIO_DEVICE_ID;
clientIDStr.toCharArray(clientID, clientIDStr.length()+1);
Serial.println(clientIDStr);
mmClient.connect(clientID, M2MIO_USERNAME, M2MIO_PASSWORD);
String topicStr = M2MIO_DOMAIN;
topicStr.concat("/");
topicStr.concat(M2MIO_STUFF);
topicStr.concat("/");
topicStr.concat(M2MIO_DEVICE_ID);
topicStr.toCharArray(topic, topicStr.length()+1);
Serial.println(topicStr);
// setup timer
int flowEvent = t.every(PROCESSING_INTERVAL, readPins);
}
/*
* LOOP
*
*/
void loop()
{
t.update();
mmClient.loop();
}
void readPins() {
if (mmClient.connected()) {
//Serial.println("C");
} else {
Serial.println("NC");
Serial.println("Client Connecting...");
mmClient.connect(clientID, M2MIO_USERNAME, M2MIO_PASSWORD);
}
kbVal = digitalRead(kbPin);
clVal = digitalRead(clPin);
if (kbVal == HIGH || clVal == HIGH) {
String mmMsg = "{\"button\":\"";
if (kbVal == HIGH) {
mmMsg.concat("kb\"}");
} else if (clVal == HIGH) {
mmMsg.concat("cl\"}");
} else {
mmMsg.concat("na\"}");
}
Serial.println(mmMsg);
mmMsg.toCharArray(msg, mmMsg.length()+1);
mmClient.publish(topic, msg);
}
}
/*
* Message Received Callback
*
*/
void mmCallback(char* topic, byte* payload, unsigned int length) { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment