Here is my code blow, the general idea is in the semi automaic mode, let the LED to breath when it is connected to the cloud, and let the LED blink when it is disconnected from the cloud.
I did one experiment that when the device is connected to the cloud, i will shutdown the WIFI network, then according the logics in my code the led will start to blink quickly and continuously to add a number n and print it out. However, in the real tests, when the WIFI is disconnected, I didn’t see anything happening on the blue led blinking quickly, nor any prints out with the number on the serial. The serial will only print out a number when the WIFI network is recovered and device is connected to cloud again.
if(!Spark.connected() ){
blink(A6);
if(millis()>timerout)
connect();
Serial.println("un connected ");
Serial.println(n);
n++;
}
Here is my full code below.
#include <math.h>
int n;
unsigned long timerout;
float breathing_val;
SYSTEM_MODE(SEMI_AUTOMATIC);
void setup() {
pinMode(A5, OUTPUT);
pinMode(A6, OUTPUT);
pinMode(A7, OUTPUT);
reset_timeout();
dark(A5);dark(A6);dark(A7);
Serial.begin(9600);
}
bool waitForWifi(unsigned timeout) {
unsigned start = millis();
while (!WiFi.ready() && (millis()-start)<timeout) {
SPARK_WLAN_Loop();
delay(1000);
}
return WiFi.ready();
}
bool waitForCloud(bool state, unsigned timeout) {
unsigned start = millis();
while (Spark.connected()!=state && (millis()-start)<timeout) {
SPARK_WLAN_Loop();
delay(100);
}
return Spark.connected()==state;
}
void connect() {
WiFi.on();
WiFi.setCredentials("Android123", "12345678");
WiFi.connect();
if (waitForWifi(20000)) {
Spark.connect();
if (waitForCloud(true, 30000)) {
}
}
}
void loop() {
if(!Spark.connected() ){
blink(A6);
if(millis()>timerout)
connect();
Serial.println("un connected ");
Serial.println(n);
n++;
}
if(Spark.connected()){
breathing_val = (exp(sin(millis()/2000.0*M_PI)) - 0.36787944)*108.0;
breath(A5);
breath(A6);
breath(A7);
}
}
void reset_timeout(){
timerout = millis() + 20000;
}
void blink(int pin){
digitalWrite(pin, HIGH);
delay(60);
digitalWrite(pin, LOW);
delay(60);
}
void breath(int pin){
analogWrite(pin, breathing_val);
}
void dark(int pin){
digitalWrite(pin, HIGH);
}