So what I am hoping (and believe) is that someone else has already done this, or done a code that is similar enough so I can use it for what I am doing.
Long story short, I have been messing around with SEMI_AUTOMATIC mode and manually turning on and of the cellular modem based on if I have something to publish or not, and to make the story short, I am not having much of a success, have tried all kinds of waitFor, Wait until etc. to wait until the electron is online and ready to publish data. But usually I end up with green blinking LED for ever, not resulting in any timeout even though I put in a timeout in the waitFor statement. I an not sure if I should use SYSTEM_THREAD or not.
the goal with this project is to measure a waterlevel using a pressure transducer and then if the waterlevel has changed by more than a given number (5cm in this code) then the electron should turn on the cellular modem, go online and publish the data using particle.publish, after that the waterlevel should be stored in EEPROM for later use/comparison and the electron should turn of the cellular and go to deep sleep for a fixed time and keep the cellular off when it wakes up and only turn it on and publish if the waterlevel has changed by more than 5cm, else it should go back to deep sleep.
in the code below I need help with the “void publishData()” part, I intentionally deleted all the waitFor or waitUntill connected so I would get a comment on where and how I should implement that part for best results.
Hope someone is willing to help me.
SYSTEM_MODE(SEMI_AUTOMATIC);
//SYSTEM_THREAD(ENABLED);
char publishStr[20];
int sleepInterval = 1;
int maxChange = 5; //the ammount in centimeters that the waterlevel has to change so it will be published
uint16_t waterlevel;
uint16_t oldWaterlevel;
uint32_t start;
void publishData() {
Cellular.on();
Cellular.connect();
Particle.connect();
sprintf(publishStr, "%i cm", waterlevel);
Particle.publish("Waterlevel", publishStr, PRIVATE, NO_ACK);
Cellular.off();
}//void publishData()
void getWaterlevel(){
//has not been implemented yet
//read waterlevel sensor and put the outcome in the waterlevel integer
waterlevel=100; //for test purposes
oldWaterlevel=94; //for test purposes so that the differnce between new and old waterlevel is more than maxChange, resulting in particle.publish
}
void setup() {
//nothing to setup
}//setup()
void loop() {
EEPROM.get(0, oldWaterlevel); //get the last published waterlevel to be able to compare
getWaterlevel(); //get new waterlevel
if (abs(waterlevel-oldWaterlevel)>maxChange){ //publish data if waterlevel has changed by more than maxChange
publishData();
oldWaterlevel=waterlevel;
EEPROM.put(0, waterlevel); //safe Waterlevel in EEProm because deep sleep will reset the MCU
}
System.sleep(SLEEP_MODE_DEEP,60 * sleepInterval); //go to Deep sleep for "sleepInterval" minutes
}//loop