arduino线程更新volatile变量

arduino thread update volatile variable

我想在 Arduino 上使用多线程编程。

我写了一些代码来更新变量 tempsPose 但它不起作用(led 始终以相同的速度闪烁)。

当在循环函数中修改此变量时,如何更改以下代码以更新函数 blinkled13 中的 tempsPose 变量?

#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;
    }
  }

示例都是"one-shot"(没有无限循环),代码if (thread.shouldRun()) thread.run();loop()里面。所以我想在你的情况下它根本不会进入 loop()

例如更具交互性的代码(“+”增加 100 毫秒,“-”减少 100 毫秒):

#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);
  }
}