ivanseidel / ArduinoThread

⏳ A simple way to run Threads on Arduino
MIT License
955 stars 196 forks source link

Interrupt the main thread #37

Closed JustinMartinDev closed 6 years ago

JustinMartinDev commented 6 years ago

Hello,

I would like to do somethings like that :

#include "Thread.h"
#include "ThreadController.h"
#include <DueTimer.h>

class SensorThread: public Thread {
public:
    int value;
    int pin;

    void run(){
        value = map(analogRead(pin), 0,1023,0,255);
        if(value > 1000) {
                      //i want to pause the main thread
                      doSomethings();
                      //i want to resume the main thread
                }
                runned();
    }
        void doSomethings(){
        }
};

// Now, let's use our new class of Thread
SensorThread analog1 = SensorThread();
SensorThread analog2 = SensorThread();

// Instantiate a new ThreadController
ThreadController controller = ThreadController();

// This is the callback for the Timer
void timerCallback(){
    controller.run();
}

void setup(){

    Serial.begin(9600);

    // Configures Thread analog1
    analog1.pin = A1;
    analog1.setInterval(100);

    // Configures Thread analog2
    analog2.pin = A2;
    analog2.setInterval(100);

    // Add the Threads to our ThreadController
    controller.add(&analog1);
    controller.add(&analog2);

    Timer1.attachInterrupt(timerCallback).start(10000);
}

void loop(){
    delay(1000);    
    Serial.print("Analog1 Thread: ");
    Serial.println(analog1.value);

    Serial.print("Analog2 Thread: ");
    Serial.println(analog2.value);
    delay(1000);
}

Do you think it's possible ?

CAHEK7 commented 6 years ago

When you are in interrupt handler (timerCallback), it kind of stops the main thread automatically. Instead of executing loop() it starts to execute timerCallback() and does not return back to loop() until timerCallback finished. The actual execution will be something like this

void timerCallback(){
//pause the main thread
    controller.run(); //check timing and calls all of the SensorThread.run() methods
//resume the main thread
}

This is how timer(or any others) interrupts work. If this is not the desired behavior, nothing can be done here.

JustinMartinDev commented 6 years ago

Yes indeed, I had forgotten that was not a real parallelism :smile:. So that works nice

Thank you