Search code examples
multithreadingarduinovolatile

arduino thread update volatile variable


I want to use multithread programming with Arduino.

I wrote some code ato update the variable tempsPose but it doesn't work (the led blinks always at the same speed).

How can I change the following code in order to update tempsPose variable in the function blinkled13 when this variable is mofified in the loop function?

#include <Thread.h>
Thread myThread = Thread();

int ledPin = 13;
volatile int tempsPose ;

void blinkLed13()
{
  \\i would like the value of 'tempspose' to be updated
  \\ when the value of the variable changes in the blinkLed13 function
  while(1){
    digitalWrite(ledPin, HIGH);
    delay(tempsPose);
    digitalWrite(ledPin, LOW);
    delay(tempsPose);
  }
}


void setup() {
  tempsPose = 100;
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  myThread.onRun(blinkLed13);
  if(myThread.shouldRun())
    myThread.run();
}

void loop() {
  for(int j=0; j<100; j++){
    delay(200);
    \\some code which change the value of 'tempsPose' 
    \\this code is pseudo code
    tempsPose = tempsPose + 1000;
    }
  }

Solution

  • Examples are all "one-shot" (no infinite loops) and the code if (thread.shouldRun()) thread.run(); is inside of loop(). So I suppose it won't get into the loop() at all in your case.

    For example more interactive code ('+' adds 100ms, '-' substracts 100ms):

    #include <Thread.h>
    
    Thread myThread = Thread();
    int ledPin = 13;
    volatile int tempsPose;
    
    void blinkLed13() {
      // i would like the value of 'tempspose' to be updated
      // when the value of the variable changes in the blinkLed13 function
      static bool state = 0;
    
      state = !state;
      digitalWrite(ledPin, state);
    
      Serial.println(state ? "On" : "Off");
    }
    
    void setup() {
      tempsPose = 100;
      pinMode(13,OUTPUT);
      Serial.begin(9600);
      myThread.onRun(blinkLed13);
      myThread.setInterval(tempsPose);
    }
    
    void loop() {
      if(myThread.shouldRun()) myThread.run();
    
      if (Serial.available()) {
        uint8_t ch = Serial.read(); // read character from serial
        if (ch == '+' && tempsPose < 10000) { // no more than 10s
          tempsPose += 100;
          myThread.setInterval(tempsPose);
        } else if (ch == '-' && tempsPose > 100) { // less than 100ms is not allowed here
          tempsPose -= 100;
          myThread.setInterval(tempsPose);
        }
        Serial.println(tempsPose);
      }
    }