I use photon. I would like to use the simplest multithreading task operation (not timer). Because my delay() operations are stopping the flow of the program.
For example;
Void simple_function () {
DigitalWrite (D1, HIGH);
Delay (5,000);
DigitalWrite (D1, LOW);
}
I want to handle this function as multithreading, and most IMPORTANT I need to put back the space used in the RAM after I finish using it.
Yes i tried and tried it. But I can not undo the RAM I am using. This consumes the RAM after several uses and the device is locked. Do I need another way or should I be able to reclaim the used ram?
@pusent, threads cannot be destroyed on Particle devices. You should be using an Software Timers or a non-blocking FSM (finite state machine) in loop() to implement your controls.
@pusent, if you use a software Timer set for 1 second “ticks” that will be the basis for your timed GPIO transition. You simply need to have a flag to indicate a start of sequence which will be looked at in the timer callback. Something like this:
#define WAIT 0
#define ON 1
#define OFF 2
Timer timer(1000, control_pin);
volatile int pin_state;
void control_pin() { // This gets called by the Software Timer every 1000ms
static on_time;
switch(pin_state) {
case WAIT: // waiting for an ON command so do nothing and exit
break;
case ON: // Now in ON state so set pin HIGH and reset ON timer
digitalWrite(D1, HIGH);
on_time = 4; // It will take 1 sec to get to next state so only count down 4 more secs
pin_state = OFF; // change the state for the next pass
break;
case OFF: // Count down the on_time. Exit if not at zero
if (--on_time > 0) // 4 secs have not elapsed yet so exit
break;
digitalWrite(D1, LOW);
pin_state = WAIT; // cycle complete, reset FSM to wait for next start
break;
}
}
void setup() {
// ... other code
pin_state = WAIT;
timer.start();
}
void loop() {
// ... other code
// Set FSM pin_state to ON to start the cycle. First check that FSM in not in a cycle already.
if (pin_state == WAIT) // Could also loop waiting for WAIT
pin_state = ON;
}
This example can simplified but I wrote it so you could (hopefully) understand how the FSM and timer work. The timer could be made much smaller since, as it stands, the pin won’t change states for up to 1 second. If you make it 1 ms, then on_time needs to be changed to the value necessary for 5 secs - 1ms or 4999.
The same approach can be taken using a non-blocking millis() timer in loop(), stepping through each state like what is done in the timer.