Last active
November 27, 2016 02:08
-
-
Save haru01/05e21f9bc17add26dc57d3e47f1360e7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#include <Wire.h> | |
#include <SPI.h> | |
#include <SparkFunLSM9DS1.h> | |
LSM9DS1 imu; | |
#define LSM9DS1_M 0x1E // Would be 0x1C if SDO_M is LOW | |
#define LSM9DS1_AG 0x6B // Would be 0x6A if SDO_AG is LOW | |
#define PRINT_SPEED 250 // 250 ms between prints | |
#include <ESP8266WiFi.h> | |
#include <WiFiClient.h> | |
#include <PubSubClient.h> | |
const char* ssid = "******"; | |
const char* wifi_password = "******"; | |
const char* mqtt_server = "******"; | |
const int port = ******; | |
const char* username = "******"; | |
const char* password = "******"; | |
WiFiClient espClient; | |
PubSubClient client(espClient); | |
void setup() | |
{ | |
Serial.begin(115200); | |
setupWifi(); | |
client.setServer(mqtt_server, port); | |
imu.settings.device.commInterface = IMU_MODE_I2C; | |
if (!imu.begin()) | |
{ | |
Serial.println("Failed to communicate with LSM9DS1."); | |
while (1) | |
; | |
} | |
} | |
void loop() | |
{ | |
if (getGyroZ() > 120.0 || getGyroZ() < -120.0) { | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.loop(); | |
client.publish("key", "shake!"); | |
Serial.print("shake!"); | |
delay(1000); | |
} | |
delay(100); | |
} | |
double getGyroZ() | |
{ | |
imu.readGyro(); | |
return imu.calcGyro(imu.gz); | |
} | |
void setupWifi() { | |
delay(10); | |
Serial.println(); | |
Serial.print("Connecting to "); | |
Serial.println(ssid); | |
WiFi.begin(ssid, wifi_password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println(""); | |
Serial.println("WiFi connected"); | |
Serial.println("IP address: "); | |
Serial.println(WiFi.localIP()); | |
} | |
void reconnect() { | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
if (client.connect("1-go-ki", username, password)) { | |
Serial.println("connected"); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(client.state()); | |
Serial.println(" try again in 5 seconds"); | |
delay(5000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment