Hi,
I’m running into an issue with wifi.off(). I have the core set to semi-automatic mode. Everytime wifi.off() is called, the core powers the wifi back on and reconnects. What am I missing?
The app im creating is for a door sensor, because it runs on batteries, i need to be able to power the wifi module on and off. Any help is greatly appreciated and thank you in advance for your time
// This #include statement was automatically added by the Spark IDE.
#include "MQTT/MQTT.h"
SYSTEM_MODE(SEMI_AUTOMATIC);
double state = 0;
double old_state = 0;
int last_change;
int current_time;
volatile boolean pinChange = false;
void post();
void pinPoll();
void connect();
void callback(char* topic, byte* payload, unsigned int length);
byte ip[] = { 192, 168, 42, 1 };
MQTT client(ip, 1883, callback);
// recieve message
void callback(char* topic, byte* payload, unsigned int length) {
char p[length + 1];
memcpy(p, payload, length);
p[length] = NULL;
String message(p);
/* if (message.equals("RED"))
RGB.color(255, 0, 0);
else if (message.equals("GREEN"))
RGB.color(0, 255, 0);
else if (message.equals("BLUE"))
RGB.color(0, 0, 255);
else
RGB.color(255, 255, 255);
delay(1000);
*/
}
void setup() {
pinMode(A7, INPUT);
client.connect("OCSensor");
if (client.isConnected()) {
client.publish("door","Connected!");
}
last_change = Time.now();
}
void loop() {
current_time = Time.now();
if ( client.isConnected() && WiFi.ready() ) client.loop();
state = analogRead(A7);
pinPoll();
if(pinChange){
post();
pinChange = false;
last_change = Time.now();
}
//should the wifi be turned off?
if(current_time - last_change > 45) { //one minute
RGB.control(true);
RGB.color(255, 0, 0);
if( WiFi.ready() ) Spark.disconnect();
WiFi.off(); //turn off the wifi module
delay(1000);
}
else if(current_time - last_change < 46) connect();
RGB.color(0, 0, 255);
}
void post(){
if( !WiFi.ready() ) connect(); //reconnect
RGB.control(true);
RGB.color(0, 0, 255);
//publish the state
if(state > 4000) client.publish("door", "CLOSED");
else if(state < 500) client.publish("door", "OPEN");
RGB.control(false);
}
void pinPoll(){
if( abs(state - old_state) > 3000) {
pinChange = true;
old_state = state;
}
}
void connect(){
RGB.control(false);
if( !WiFi.ready() ) {
WiFi.on(); //turn on the wifi
WiFi.connect(); //connect to the wireless network
while( !WiFi.ready() ){
//do nothing
}
Spark.connect();
client.connect("OCSensor");
// publish/subscribe
if (client.isConnected()) {
client.publish("door","Connected!");
}
}
}
any help is greatly appreciated! thank you!